 which defines what kind of role of user that attendee can talk to, there are the different privilege as following.
   *
   * | privilege value | describe                                            |
   * | --------------- | --------------------------------------------------- |
   * | 1               | attendee can talk to all or privately to someone    |
   * | 4               | attendee can talk to no one                         |
   * | 5               | attendee can only talk to all                       |
   *
   * **there is a special user**
   *
   * **EVERY_ONE**: If someone send chat message to all use {@link sendChatToAll}, the chat data that other will receive include the reader property which is represent the EVERY_ONE user.
   *
   * #### example
   *
   * ```js
   * const MEETING_PRIVILEGE_ALL = 1;
   * chat.changePrivilege(MEETING_PRIVILEGE_ALL)
   * .then((v) => {
   *      const { chatPrivilege } = v;
   *      // success
   *  })
   * .catch(v => {
   *      // fail
   *      console.log(v)
   *  })
   * ```
   *
   * @param privilege
   *
   * @return
   *
   * - `{ chatPrivilege: number }`: success
   * - `Error`: Failure. Following the details of Error:
   *     - `IMPROPER_MEETING_STATE`: It works only when user is in meeting
   *     - `INSUFFICIENT_PRIVILEGES`: Only host or manager can mute other participants
   *     - `INTERNAL_ERROR`: Set privilege failed
   *     - `OPERATION_TIMEOUT`: Set privilege timeout
   *     - `INVALID_PARAMETERS`: Invalid privilege value of parameter
   */
  function changePrivilege(
    privilege: number,
  ): Promise<{ chatPrivilege: number } | Error>;

  /**
   * Return the current privilege value
   * #### example
   * ```js
   * const privilege = chat.getPrivilege();
   * console.log(privilege);
   * ```
   * @return
   */
  function getPrivilege(): number;
}
export default ChatClient;
/**
 * Describes the size of something by stating how much of a certain unit is present.
 */
export interface Size {
  unit: string;
  amount: number;
}

export const UNIT_BYTES = 'bytes';
describe('isolated Tests', () => {
    it('should trigger the search with the correct parameters for people search', () => {
        // intercept the api with the correct URL and parameters
        cy.intercept(
            'GET',
            'https://swapi.py4e.com/api/people/?search=Luke',
            { fixture: 'no-results.json'}
        );

        // search
        cy.visit('https://starwarssearch.coding42.cyou/');
        cy.get('[data-testid=search-card]').should('be.visible');
        cy.get('[for="people"]').click();
        cy.get('#query').type('Luke');
        cy.get('[data-testid=search-button]').click();
    });

    it('should trigger the search with the correct parameters for planet search', () => {
        // intercept the api with the correct URL and parameters
        cy.intercept(
            'GET',
            'https://swapi.py4e.com/api/planets/?search=Luke',
            { fixture: 'no-results.json'}
        );

        // search
        cy.visit('https://starwarssearch.coding42.cyou/');
        cy.get('[data-testid=search-card]').should('be.visible');
        cy.get('[for="planets"]').click();
        cy.get('#query').type('Luke');
        cy.get('[data-testid=search-button]').click();
    });

    it('should display Not Found when no search result is returned', () => {
        // intercep


import os
from io import BytesIO

import boto3
from moto import mock_s3

from CTFd.utils.uploads import S3Uploader, rmdir
from tests.helpers import create_ctfd, destroy_ctfd

@mock_s3
def test_s3_uploader():
    conn = boto3.resource("s3", region_name="test-region")
    conn.create_bucket(
        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "test-region"}
    )

    app = create_ctfd()
    with app.app_context():
        app.config["UPLOAD_PROVIDER"] = "s3"
        app.config["AWS_ACCESS_KEY_ID"] = "AKIAIOSFODNN7EXAMPLE"
        app.config["AWS_SECRET_ACCESS_KEY"] = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
        app.config["AWS_S3_BUCKET"] = "bucket"
        app.config["AWS_S3_REGION"] = "test-region"

        uploader = S3Uploader()

        assert uploader.s3
        assert uploader.bucket == "bucket"

        fake_file = BytesIO("fakedfile".encode())
        path = uploader.upload(fake_file, "fake_file.txt")

        assert "fake_file.txt" in uploader.download(path).location
    destroy_ctfd(app)

@mock_s3
def test_s3_uploader_custom_prefix():
    conn = boto3.resource("s3", region_name="test-region")
    conn.create_bucket(
        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "test-region"}
    )

    app = create_ctfd()
    with app.app_context():
        app.config["UPLOAD_PROVIDER"] = "s3"
        app.config["AWS_ACCESS_KEY_ID"] = "AKIAIOSFODNN7EXAMPLE"
        app.config["AWS_SECRET_ACCESS_KEY"] = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
        app.config["AWS_S3_BUCKET"] = "bucket"
        app.config["AWS_S3_REGION"] = "test-region"
        app.config["AWS_S3_CUSTOM_PREFIX"] = "prefix"

        uploader = S3Uploader()

        assert uploader.s3
        assert uploader.bucket == "bucket"

        fake_file = BytesIO("fakedfile".encode())
        path = uploader.upload(fake_file, "fake_file.txt")
        assert "fake_file.txt" in uploader.download(path).location

        fake_file2 = BytesIO("fakedfile".encode())
        path2 = uploader.upload(fake_file2, "fake_file.txt", "path")
        assert "/prefix/path/fake_file.txt" in uploader.download(path2).location
    destroy_ctfd(app)

@mock_s3
def test_s3_sync():
    conn = boto3.resource("s3", region_name="test-region")
    conn.create_bucket(
        Bucket="bucket", CreateBucketConfiguration={"LocationConstraint": "test-region"}
    )

    app = create_ctfd()
    with app.app_context():
        app.config["UPLOAD_PROVIDER"] = "s3"
        app.config["AWS_ACCESS_KEY_ID"] = "AKIAIOSFODNN7EXAMPLE"
        app.config["AWS_SECRET_ACCESS_KEY"] = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
        app.config["AWS_S3_BUCKET"] = "bucket"
        app.config["AWS_S3_REGION"] = "test-region"

        uploader = S3Uploader()
        uploader.sync()

        fake_file = BytesIO("fakedfile".encode())
        path = uploader.upload(fake_file, "fake_file.txt")
        full_path = os.path.join(app.config["UPLOAD_FOLDER"], path)

        try:
            uploader.sync()
            with open(full_path) as f:
                assert f.read() == "fakedfile"
        finally:
            rmdir(os.path.dirname(full_path))
    destroy_ctfd(app)


())
}

pub fn serialize_structure_crate_model_caption_selector_settings(
    object: &mut aws_smithy_json::serialize::JsonObjectWriter,
    input: &crate::model::CaptionSelectorSettings,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
    if let Some(var_785) = &input.ancillary_source_settings {
        let mut object_786 = object.key("ancillarySourceSettings").start_object();
        crate::json_ser::serialize_structure_crate_model_ancillary_source_settings(
            &mut object_786,
            var_785,
        )?;
        object_786.finish();
    }
    if let Some(var_787) = &input.arib_source_settings {
        let mut object_788 = object.key("aribSourceSettings").start_object();
        crate::json_ser::serialize_structure_crate_model_arib_source_settings(
            &mut object_788,
            var_787,
        )?;
        object_788.finish();
    }
    if let Some(var_789) = &input.dvb_sub_source_settings {
        let mut object_790 = object.key("dvbSubSourceSettings").start_object();
        crate::json_ser::serialize_structure_crate_model_dvb_sub_source_settings(
            &mut object_790,
            var_789,
        )?;
        object_790.finish();
    }
    if let Some(var_791) = &input.embedded_source_settings {
        let mut object_792 = object.key("embeddedSourceSettings").start_object();
        crate::json_ser::serialize_structure_crate_model_embedded_source_settings(
            &mut object_792,
            var_791,
        )?;
        object_792.finish();
    }
    if let Some(var_793) = &input.scte20_source_settings {
        let mut object_794 = object.key("scte20SourceSettings").start_object();
        crate::json_ser::serialize_structure_crate_model_scte20_source_settings(
            &mut object_794,
            var_793,
        )?;
        object_794.finish();
    }
    if let Some(var_795) = &input.scte27_source_settings {
        let mut object_796 = object.key("scte27SourceSettings").start_object();
        crate::json_ser::serialize_structure_crate_model_scte27_source_settings(
            &mut object_796,
            var_795,
        )?;
        object_796.finish();
    }
    if let Some(var_797) = &input.teletext_source_settings {
        let mut object_798 = object.key("teletextSourceSettings").start_object();
        crate::json_ser::serialize_structure_crate_model_teletext_source_settings(
            &mut object_798,
            var_797,
        )?;
        object_798.finish();
    }
    Ok(())
}

pub fn serialize_structure_crate_model_hls_input_settings(
    object: &mut aws_smithy_json::serialize::JsonObjectWriter,
    input: &crate::model::HlsInputSettings,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
    if input.bandwidth != 0 {
        object.key("bandwidth").number(
            #[allow(clippy::useless_conversion)]
            aws_smithy_types::Number::NegInt((input.bandwidth).into()),
        );
    }
    if input.buffer_segments != 0 {
        object.key("bufferSegments").number(
            #[allow(clippy::useless_conversion)]
            aws_smithy_types::Number::NegInt((input.buffer_segments).into()),


ue
        }
      }

      let text, rest, next
      if (textEnd >= 0) {
        rest = html.slice(textEnd)
        while (!endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest)) {
          // < in plain text, be forgiving and treat it as text
          next = rest.indexOf('<', 1)
          if (next < 0) break
          textEnd += next
          rest = html.slice(textEnd)
        }
        text = html.substring(0, textEnd)
      }

      if (textEnd < 0) {
        text = html
      }

      if (text) {
        advance(text.length)
      }

      if (options.chars && text) {
        options.chars(text, index - text.length, index)
      }
    } else {
      let endTagLength = 0
      const stackedTag = lastTag.toLowerCase()
      const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
      const rest = html.replace(reStackedTag, function (all, text, endTag) {
        endTagLength = endTag.length
        if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
          text = text
            .replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298
            .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
        }
        if (shouldIgnoreFirstNewline(stackedTag, text)) {
          text = text.slice(1)
        }
        if (options.chars) {
          options.chars(text)
        }
        return ''
      })
      index += html.length - rest.length
      html = rest
      parseEndTag(stackedTag, index - endTagLength, index)
    }

    if (html === last) {
      options.chars && options.chars(html)
      if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
        options.warn(`Mal-formatted tag at end of template: "${html}"`, {
          start: index + html.length
        })
      }
      break
    }
  }

  // Clean up any remaining tags
  parseEndTag()

  function advance(n) {
    index += n
    html = html.substring(n)
  }

  function parseStartTag() {
    const start = html.match(startTagOpen)
    if (start) {
      const match = {
        tagName: start[1],
        attrs: [],
        start: index
      }
      advance(start[0].length)
      let end, attr
      while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) {
        attr.start = index
        advance(attr[0].length)
        attr.end = index
        match.attrs.push(attr)
      }
      if (end) {
        match.unarySlash = end[1]
        advance(end[0].length)
        match.end = index
        return match
      }
    }
  }

  function handleStartTag(match) {
    const tagName = match.tagName
    const unarySlash = match.unarySlash

    if (expectHTML) {
      if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
        parseEndTag(lastTag)
      }
      if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
        parseEndTag(tagName)
      }
    }

    const unary = isUnaryTag(tagName) || !!unarySlash

    const l = match.attrs


"""
Copyright (joint work) 2024 The Rockstor Project <https://rockstor.com>

Rockstor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.

Rockstor 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/>.
"""

from smart_manager.models import Service
from storageadmin.models import Setup

def register_services() -> None:
    services = {
        "NFS": "nfs",
        "Samba": "smb",
        "NIS": "nis",
        "NTP": "ntpd",
        "Active Directory": "active-directory",
        "LDAP": "ldap",
        "SFTP": "sftp",
        "Replication": "replication",
        "SNMP": "snmpd",
        "Rock-on": "docker",
        "S.M.A.R.T": "smartd",
        "NUT-UPS": "nut",
        # ZTaskd display/service names maintained: but are now huey pseudonyms.
        "ZTaskd": "ztask-daemon",
        "Bootstrap": "rockstor-bootstrap",
        "Shell In A Box": "shellinaboxd",
        "Rockstor": "rockstor",
        "Tailscale": "tailscaled",
    }

    # N.B. all other services have null as their default config with service.
    # Consider bringing shellinaboxd in line with this now default behaviour.
    services_configs = {
        "shellinaboxd": (
            '{"detach": false, "css": "white-on-black", ' '"shelltype": "LOGIN"}'
        )
    }

    for k, v in services.items():
        try:
            so = Service.objects.get(name=v)
            so.display_name = k
            # Apply any configuration defaults found in services_configs.
            if v in services_configs:
                so.config = services_configs[v]
        except Service.DoesNotExist:
            so = Service(display_name=k, name=v)
        finally:
            so.save()
    for so in Service.objects.filter():
        if so.display_name not in services:
            so.delete()

def create_setup():
    setup = Setup.objects.all()
    if len(setup) == 0:
        s = Setup()
        s.save()

def main():
    create_setup()
    register_services()


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.ServiceModel.Security;
using System.Xml;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace System.ServiceModel.Channels
{
    public abstract class TransportBindingElement
        : BindingElement
    {
        private bool _manualAddressing;
        private long _maxBufferPoolSize;
        private long _maxReceivedMessageSize;

        protected TransportBindingElement()
        {
            _manualAddressing = TransportDefaults.ManualAddressing;
            _maxBufferPoolSize = TransportDefaults.MaxBufferPoolSize;
            _maxReceivedMessageSize = TransportDefaults.MaxReceivedMessageSize;
        }

        protected TransportBindingElement(TransportBindingElement elementToBeCloned)
            : base(elementToBeCloned)
        {
            _manualAddressing = elementToBeCloned._manualAddressing;
            _maxBufferPoolSize = elementToBeCloned._maxBufferPoolSize;
            _maxReceivedMessageSize = elementToBeCloned._maxReceivedMessageSize;
        }

        [DefaultValue(TransportDefaults.ManualAddressing)]
        public virtual bool ManualAddressing
        {
            get
            {
                return _manualAddressing;
            }

            set
            {
                _manualAddressing = value;
            }
        }

        [DefaultValue(TransportDefaults.MaxBufferPoolSize)]
        public virtual long MaxBufferPoolSize
        {
            get
            {
                return _maxBufferPoolSize;
            }
            set
            {
                if (value < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value,
                        SRP.ValueMustBeNonNegative));
                }
                _maxBufferPoolSize = value;
            }
        }

        [DefaultValue(TransportDefaults.MaxReceivedMessageSize)]
        public virtual long MaxReceivedMessageSize
        {
            get
            {
                return _maxReceivedMessageSize;
            }
            set
            {
                if (value <= 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value,
                        SRP.ValueMustBePositive));
                }
                _maxReceivedMessageSize = value;
            }
        }

        public abstract string Scheme { get; }

        internal static IChannelFactory<TChannel> CreateChannelFactory<TChannel>(TransportBindingElement transport)
        {
            Binding binding = new CustomBinding(transport);
            return binding.BuildChannelFactory<TChannel>();
        }

        public override T GetProperty<T>(BindingContext context)
        {
            if (context == null)
            {


void onMeterAdded(String metricName, Meter meter)
            {
                // Given metricName consists of appender name in logback.xml + "." + metric name.
                // We first separate appender name
                int separator = metricName.lastIndexOf('.');
                String appenderName = metricName.substring(0, separator);
                String metric = metricName.substring(separator + 1); // remove "."
                ObjectName name = DefaultNameFactory.createMetricName(appenderName, metric, null).getMBeanName();
                CassandraMetricsRegistry.Metrics.registerMBean(meter, name);
            }
        });
        logger = LoggerFactory.getLogger(CassandraDaemon.class);
    }

    private void maybeInitJmx()
    {
        // If the standard com.sun.management.jmxremote.port property has been set
        // then the JVM agent will have already started up a default JMX connector
        // server. This behaviour is deprecated, but some clients may be relying
        // on it, so log a warning and skip setting up the server with the settings
        // as configured in cassandra-env.(sh|ps1)
        // See: CASSANDRA-11540 & CASSANDRA-11725
        if (System.getProperty("com.sun.management.jmxremote.port") != null)
        {
            logger.warn("JMX settings in cassandra-env.sh have been bypassed as the JMX connector server is " +
                        "already initialized. Please refer to cassandra-env.(sh|ps1) for JMX configuration info");
            return;
        }

        System.setProperty("java.rmi.server.randomIDs", "true");

        // If a remote port has been specified then use that to set up a JMX
        // connector server which can be accessed remotely. Otherwise, look
        // for the local port property and create a server which is bound
        // only to the loopback address. Auth options are applied to both
        // remote and local-only servers, but currently SSL is only
        // available for remote.
        // If neither is remote nor local port is set in cassandra-env.(sh|ps)
        // then JMX is effectively  disabled.
        boolean localOnly = false;
        String jmxPort = System.getProperty("cassandra.jmx.remote.port");

        if (jmxPort == null)
        {
            localOnly = true;
            jmxPort = System.getProperty("cassandra.jmx.local.port");
        }

        if (jmxPort == null)
            return;

        try
        {
            jmxServer = JMXServerUtils.createJMXServer(Integer.parseInt(jmxPort), localOnly);
            if (jmxServer == null)
                return;
        }
        catch (IOException e)
        {
            exitOrFail(1, e.getMessage(), e.getCause());
        }
    }

    static final CassandraDaemon instance = new CassandraDaemon();

    private volatile Server thriftServer;
    private volatile NativeTransportService nativeTransportService;
    private JMXConnectorServer jmxServer;

    private final boolean runManaged;
    protected final StartupChecks startupChecks;
    private boolean setupCompleted;

    public CassandraDaemon()
    {
        this(false);
    }

    public CassandraDaemon(boolean runManaged)
    {
        this.runManaged = runManaged;
        this.startupChecks = new StartupChecks().withDefaultTests();
        this.setupCompleted = false;
    }

    /**
     * This is a hook for concrete daemons to initialize themselves suitably.
     *
     * Subclasses should override this to finish the job (listening on ports, etc.)
     */
    protected void setup()
    {


Disr) -> bool {
            match ty {
                ast::TyU8 => disr as u8 as Disr == disr,
                ast::TyU16 => disr as u16 as Disr == disr,
                ast::TyU32 => disr as u32 as Disr == disr,
                ast::TyU64 => disr as u64 as Disr == disr,
                ast::TyU => uint_in_range(ccx, ccx.tcx.sess.targ_cfg.uint_type, disr)
            }
        }
        fn int_in_range(ccx: @CrateCtxt, ty: ast::IntTy, disr: ty::Disr) -> bool {
            match ty {
                ast::TyI8 => disr as i8 as Disr == disr,
                ast::TyI16 => disr as i16 as Disr == disr,
                ast::TyI32 => disr as i32 as Disr == disr,
                ast::TyI64 => disr as i64 as Disr == disr,
                ast::TyI => int_in_range(ccx, ccx.tcx.sess.targ_cfg.int_type, disr)
            }
        }
        match ty {
            attr::UnsignedInt(ty) => uint_in_range(ccx, ty, disr),
            attr::SignedInt(ty) => int_in_range(ccx, ty, disr)
        }
    }

    fn do_check(ccx: @CrateCtxt,
                vs: &[ast::P<ast::Variant>],
                id: ast::NodeId,
                hint: attr::ReprAttr)
                -> ~[@ty::VariantInfo] {

        let rty = ty::node_id_to_type(ccx.tcx, id);
        let mut variants: ~[@ty::VariantInfo] = ~[];
        let mut disr_vals: ~[ty::Disr] = ~[];
        let mut prev_disr_val: Option<ty::Disr> = None;

        for &v in vs.iter() {

            // If the discriminant value is specified explicitly in the enum check whether the
            // initialization expression is valid, otherwise use the last value plus one.
            let mut current_disr_val = match prev_disr_val {
                Some(prev_disr_val) => prev_disr_val + 1,
                None => ty::INITIAL_DISCRIMINANT_VALUE
            };

            match v.node.disr_expr {
                Some(e) => {
                    debug!("disr expr, checking {}", pprust::expr_to_str(e, ccx.tcx.sess.intr()));

                    let fcx = blank_fn_ctxt(ccx, rty, e.id);
                    let declty = ty::mk_int_var(ccx.tcx, fcx.infcx().next_int_var_id());
                    check_const_with_ty(fcx, e.span, e, declty);
                    // check_expr (from check_const pass) doesn't guarantee
                    // that the expression is in an form that eval_const_expr can
                    // handle, so we may still get an internal compiler error

                    match const_eval::eval_const_expr_partial(&ccx.tcx, e) {
                        Ok(const_eval::const_int(val)) => current_disr_val = val as Disr,
                        Ok(const_eval::const_uint(val)) => current_disr_val = val as Disr,
                        Ok(_) => {
                            ccx.tcx.sess.span_err(e.span, "expected signed integer constant");
                        }
                        Err(ref err) => {
                            ccx.tcx.sess.span_err(e.span, format!("expected constant: {}", (*err)));
                        }
                    }
                },
                None => ()
            };

            // Check for duplicate discriminant


},
        prefilterCubeSize: 32
      },
      exposure: 1,
      hsv: [0, 0.34, 0],
      orientation: 0
    }
  }
});

const vt = new maptalks.VectorTileLayer("vt", {
  urlTemplate: "http://tile.maptalks.com/test/planet-single/{z}/{x}/{y}.mvt"
});

const style = {
  style: [
    {
      filter: ["all", ["==", "$layer", "building"], ["==", "$type", "Polygon"]],
      renderPlugin: {
        dataConfig: {
          type: "fill"
        },
        sceneConfig: {},
        type: "fill"
      },
      symbol: {
        polygonBloom: true,
        polygonFill: [0.345, 0.345, 0.502, 1],
        polygonOpacity: 1
      }
    }
  ]
};
vt.setStyle(style);

const groupLayer = new maptalks.GroupGLLayer("group", [vt], {
  sceneConfig: {
    environment: {
      enable: true,
      mode: 1,
      level: 0,
      brightness: 0
    },
    postProcess: {
      enable: true,
      bloom: {
        enable: true,
        threshold: 0.01,
        factor: 1,
        radius: 0.02
      }
    },
    ground: {
      enable: true,
      renderPlugin: {
        type: "fill"
      },
      symbol: {
        polygonFill: [0.3294117, 0.3294117, 0.3294117, 1],
        polygonOpacity: 1
      }
    }
  }
});
groupLayer.addTo(map);
/**end**/
// https://maptalks.org/maptalks.three/demo/extrudepolygon-china.html
const map = new maptalks.Map("map", {
  center: [97.4656881809608, 21.4667907971768],
  zoom: 4.3,
  bearing: -3.63,
  pitch: 35.2,
  lights: {
    directional: { direction: [-1, -1, -1], color: [1, 1, 1] },
    ambient: {
      resource: {
        url: {
          front: "{res}/hdr/923/front.jpg",
          back: "{res}/hdr/923/back.jpg",
          left: "{res}/hdr/923/left.jpg",
          right: "{res}/hdr/923/right.jpg",
          top: "{res}/hdr/923/top.jpg",
          bottom: "{res}/hdr/923/bottom.jpg"
        }
      },
      exposure: 1.426,
      hsv: [0, 0, 0],
      orientation: 302.553
    }
  }
});

const geoLayer1 = new maptalks.GeoJSONVectorTileLayer("发光数据", {
  data: "https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json",
  style: "{res}/styles/administrative1.json"
});

const geoLayer2 = new maptalks.GeoJSONVectorTileLayer("省份", {
  data: "https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json",
  style: "{res}/styles/administrative2.json"
});

const vtLayer = new maptalks.VectorTileLayer("底图", {
  urlTemplate: "http://tile.maptalks.com/test/planet-single/{z}/{x}/{y}.mvt",
  style: "{res}/styles/administrative3.json"
});

const gltfLayer = new maptalks.GLTFLayer("重点区域");

const gltfMarker = new maptalks.GLTFMarker([86.10452197331779, 37.02245639276353], {
  symbol: {
    shadow: true,
    url: "{res}/gltf/664/scene.gltf",
    shader: "pbr",
    uniforms:


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

#pragma once

namespace GafferTestModule
{

void testConcurrentAccessToDifferentInstances();
void testConcurrentAccessToSameInstance();

} // namespace GafferTestModule


// cross grid
      calcLine(p, MemEnd, Bounds, zBuffer);

      p += dy;
      calcLine(p, MemEnd, Bounds, zBuffer);

      // mark the area of the polygon (stored in "*Bounds") as used
      for(i=x2()-1; i>=0; i--)  // all x coordinates
        if( (Bounds+i)->max > INT_MIN) {
          pc = zBuffer + i * ((y2()+7)>>3);
          for(j=(Bounds+i)->min; j<=(Bounds+i)->max; j++) // all y coordinates
            *(pc + (j>>3)) |= (1 << (j & 7));
        }

      zp++;   // next polygon
    }

  }  // of "for(Graphs)"

#if 0
  qDebug("--------------------------- hidden lines %d", pMem-Mem);
  for(tPoint3D *p=Mem; p<pMem; p++)
    qDebug("xyPoints:  %d/%d - %d - %d", p->x, p->y, p->No, p->done);
#endif

  free(zMem);

  // sort "No" (least one first)
  qsort(Mem, pMem - Mem, sizeof(tPoint3D), comparePoint3D);

#if 0
  qDebug("--------------------------- last sorting %d", pMem-Mem);
  for(tPoint3D *p=Mem; p<pMem; p++)
    qDebug("xyPoints:  %d/%d - %d - %d", p->x, p->y, p->No, p->done);
  qDebug("\n");
#endif
}

// --------------------------------------------------------------
// Removes the invisible parts of the coordinate cross.
void Rect3DDiagram::removeHiddenCross(int x1_, int y1_, int x2_, int y2_,
                                      char *zBuffer, tBound *Bounds)
{
  pMem = Mem;

  pMem->x  = x1_;
  pMem->y  = y1_;
  pMem->No = 0;
  pMem->done = 0;
  pMem++;

  pMem->x  = x2_;
  pMem->y  = y2_;
  pMem->No = 1;
  pMem->done = 0;
  pMem++;

  tPoint3D *p = Mem+6;
  calcLine(Mem, p, Bounds, zBuffer);
  *pMem = *(Mem+1);
  *(Mem+1) = *Mem;
  p = Mem+2;
  do {
    if(((p-1)->done & 4) == 0)
      Lines.push_back(qucs::Line((p-1)->x, (p-1)->y, p->x, p->y, QPen(Qt::black,0)));
    p++;
  } while(p <= pMem);
}

// --------------------------------------------------------------
void Rect3DDiagram::calcLimits()
{
  int i;
  double a, b, c;

  if(xAxis.autoScale) {// check before, to preserve limit exchange (max < min)
    if(xAxis.log) {
      calcAxisLogScale(&xAxis, i, a, b, c, x2());
      xAxis.step = 1.0;
    }
    else  calcAxisScale(&xAxis, a, b, c, xAxis.step, double(x2()));
    xAxis.limit_min = xAxis.low;
    xAxis.limit_max = xAxis.up;
  }

  if(yAxis.autoScale) {// check before, to preserve limit exchange (max < min)
    if(yAxis.log) {
      calcAxisLogScale(&yAxis, i, a, b, c, y2());
      yAxis.step = 1.0;
    }
    else  calcAxisScale(&yAxis, a, b, c, yAxis.step, double(y2()));
    yAxis.limit_min = yAxis.low;
    yAxis.limit_max = yAxis.up;
  }

  if(zAxis.autoScale) {// check before, to preserve limit exchange (max < min)
    if(zAxis.log) {
      calcAxisLogScale(&zAxis, i, a, b, c, y2());
      zAxis.step = 1.0


g.Assert(result);
            BytesPending += bytesWritten;
        }

        private void WriteNumberIndented(ReadOnlySpan<byte> escapedPropertyName, ulong value)
        {
            int indent = Indentation;
            Debug.Assert(indent <= _indentLength * _options.MaxDepth);

            Debug.Assert(escapedPropertyName.Length < int.MaxValue - indent - JsonConstants.MaximumFormatUInt64Length - 5 - _newLineLength);

            int minRequired = indent + escapedPropertyName.Length + JsonConstants.MaximumFormatUInt64Length + 4; // 2 quotes for property name, 1 colon, and 1 space
            int maxRequired = minRequired + 1 + _newLineLength; // Optionally, 1 list separator and 1-2 bytes for new line

            if (_memory.Length - BytesPending < maxRequired)
            {
                Grow(maxRequired);
            }

            Span<byte> output = _memory.Span;

            if (_currentDepth < 0)
            {
                output[BytesPending++] = JsonConstants.ListSeparator;
            }

            Debug.Assert(_options.SkipValidation || _tokenType != JsonTokenType.PropertyName);

            if (_tokenType != JsonTokenType.None)
            {
                WriteNewLine(output);
            }

            WriteIndentation(output.Slice(BytesPending), indent);
            BytesPending += indent;

            output[BytesPending++] = JsonConstants.Quote;

            escapedPropertyName.CopyTo(output.Slice(BytesPending));
            BytesPending += escapedPropertyName.Length;

            output[BytesPending++] = JsonConstants.Quote;
            output[BytesPending++] = JsonConstants.KeyValueSeparator;
            output[BytesPending++] = JsonConstants.Space;

            bool result = Utf8Formatter.TryFormat(value, output.Slice(BytesPending), out int bytesWritten);
            Debug.Assert(result);
            BytesPending += bytesWritten;
        }

        internal void WritePropertyName(uint value)
            => WritePropertyName((ulong)value);

        internal void WritePropertyName(ulong value)
        {
            Span<byte> utf8PropertyName = stackalloc byte[JsonConstants.MaximumFormatUInt64Length];

            bool result = Utf8Formatter.TryFormat(value, utf8PropertyName, out int bytesWritten);
            Debug.Assert(result);

            WritePropertyNameUnescaped(utf8PropertyName.Slice(0, bytesWritten));
        }
    }
}


资列表页*/\r\n#invest .list_title{padding:10px 0 10px 3%; margin:10px 0;background:#fff;border-top:1px solid #c7c8cc; border-bottom: 1px solid #c7c8cc;}\r\n#invest .list_title,#invest_con .list_title a,#users_main .list_title a{width:100%;min-height:30px; line-height: 30px; display: inline-block; color:#666; font-weight: normal; text-decoration: none;}\r\n#invest .list_title:active,#invest_con .list_title a:active{color:#ff5c5f;}\r\n#invest .list_title div.invest_title_name{border-bottom: 1px solid #c8c8ca}\r\n#users_main .list_title label{display: inline; float: right;}\r\n#invest .list_title i,#invest_con .list_title i,#users_main .list_title i,.user_info i{width:14px;height:14px;margin-top:8px;float:right;background:url("../images/icons-png/carat-r-grey.png")}\r\n#invest .invest_list li{width:31%;list-style: none; display: inline-block; }\r\n#invest .invest_list_title{padding-bottom:10px;border-bottom: 1px solid #e4e8e9;}\r\n#invest .invest_list_detail_title{color:#8a8a8a; font-size: 13px;margin:0;}\r\n#invest .invest_list_detail{font-size:24px;color:#ff5c5f;}\r\n#invest .list_title .yield{position: absolute; top:8px; left:56px; line-height: 14px; font-size:12px; border:1px solid #ff5c5f; border-radius: 4px; padding:0 2px;}\r\n#invest .list_title .invest_list_bottom{float:left; width: 97%; margin-right: 3%; border-top:1px solid #c8c8ca}\r\n#invest .list_title .invest_list_bottom .assign:before{width: 9px;height: 9px; background: #999; content: ""; display: inline-block;}\r\n.invest_limit{margin-bottom: 2px}\r\n#invest .invest_list .invest_btn{margin-top:10px;background: #ff5c5f; border:1px solid #e92c2f; color:#fff; font-size: 14px;}\r\n#invest .invest_list .invest_btn:hover{background: #e92c2f;color:#fff;}\r\n#invest .product_title_item{margin-left: 5px; padding: 3px 5px 2px 5px;border: 1px solid #7c91c8; color: #7c91c8; border-radius: 4px;}\r\n#invest .wrap, #invest .invest_circle, #invest .percent{position:absolute;width:60px;height:60px;border-radius:50%}\r\n#invest .wrap{top:20px;right:15px;background-color:#e7e7e7}\r\n#invest .invest_circle{box-sizing:border-box;border:4px solid #e7e7e7;clip:rect(0,60px,60px,30px)}\r\n#invest .clip-auto{clip:rect(auto,auto,auto,auto)}\r\n#invest .percent{box-sizing:border-box;top:-4px;left:-4px}\r\n#invest .left{transition:transform ease;border:4px solid #ff9b9e;clip:rect(0,30px,60px,0);-webkit-transform:rotate(70deg)}\r\n#invest .right{border:4px solid #ff9b9e;clip:rect(0,60px,60px,30px)}\r\n#invest .wth0{width:0}\r\n#invest .num{position:absolute;box-sizing:border-box;width:52px;height:52px;line-height:52px;text-align:center;


 12) | ((capt) << 16))

//	Quiescent search.  This lets captures play out at the end of the search,
//	so I don't end up aborting a line at a stupid place.

//#define QS_MARGIN   75
//#define QS_MARGIN   55
//#define QS_MARGIN   95
#define QS_MARGIN   150
//#define QS_MARGIN   (150+75)
//#define QS_MARGIN   (150+250)

static int SearchQpEG(PCON pcon, PSTE pste, int Alpha, int Beta);

static int SearchQ(PCON pcon, PSTE pste, int Alpha, int Beta, bool do_check)
{
//	pcon->ss.nodes++;
    stats.QS_count ++;
    if (++pcon->ss.nodes >= pcon->ss.nodesNext) {
        pcon->ss.nodesNext = pcon->ss.nodes + 10000;
        VPrCallback(pcon);
        VCheckTime(pcon);
        if ((pcon->fAbort) || (pcon->fTimeout))
            return 0;
        if( pcon->smode == smodeTHINK || pcon->smode == smodeANALYZE )
            VPrSendUciCurrentLine(pcon, pste);
	}

	CM cmBest(0,0);
	pste->ccmPv = 0;
    pste->lastMove = 0;
	bool fFound = false;
    bool isPV = Beta != (Alpha+1);
    int iaminCheck = pste->checkf;
    int  f_max   = valMAX;
    int sp = valMIN;
    CM * p_moves;
    int depth = int(pste - pcon->argste) + 1;
    (pste+1)->lastMove = 0;
    if (FRepSet(pcon, pste, pste->hashkPc)) {
        stats.repCount++;
		return 0;
	}

#ifdef DISTANCE_PRUNING
#if 1
    // this is the lowest score I can get from here
    int i_am_mate_score = mateValue(depth + 1);
    if( i_am_mate_score > Alpha ) {
        Alpha = i_am_mate_score;
        // Beta is mate in n, best here is mate in n+m, so return
        if(i_am_mate_score >= Beta)
            return Beta; //i_am_mate_score;
//            return i_am_mate_score;
    }
#endif
#endif
    int OldAlpha = Alpha;
	//
	//	See if static eval will cause a cutoff or raise alpha.
	//
    // this will be the return value if king evasion does no capture
	int posVal = ValEval(pcon, pste, Alpha, Beta);
    // score is valMIN when in check or else it won't play moves that lead to loss of material when nearly mated
    int bestVal = valMIN;

    if( depth >= (csteMAX-2) )
        return posVal;

    // generate captures, if we are in check then generate all moves (evade)
	if (iaminCheck) {
		bGenEvasions(pcon, pste);
        //pste->plyRem++;
        //do_check = do_check || QS_CHECK_LIMIT;
	}
	else {
//        if( pste->valPcUs + pste->valPcThem == 0 ) {
//            return SearchQpEG(pcon, pste, Alpha, Beta);
//        }

#ifdef PRUNE_QS
        f_max = posVal + QS_MARGIN;
#endif
        bestVal = posVal;
        if (bestVal >= Beta)
		    return bestVal;
        if (bestVal > Alpha)
            Alpha = bestVal;
        else {
            //bestVal = Alpha;
        }
		p_moves = bGenCaptures(pcon, pste, pste->mlist_start);
        if( pste->plyRem >= -1 || (


2c::Write<Error = E>
        + Send
        + hal::blocking::i2c::WriteRead<Error = E>
        + 'static,
    E: Sync + Send + std::fmt::Debug + 'static,
{
    let addr = config.slave_address()?;
    ensure!(
        config.update_interval_millis != 0,
        "update_interval_millis must be > 0"
    );
    let mut dev = pwmdev::Pca9685::new(i2c, addr)
        .map_err(PCA9685::do_map_err::<I2C, E>)
        .context("unable to create PCA9685")?;

    if config.inverted {
        dev.set_output_logic_state(pwmdev::OutputLogicState::Inverted)
            .map_err(PCA9685::do_map_err::<I2C, E>)
            .context("unable to set PCA9685 to inverted mode")?;
    } else {
        dev.set_output_logic_state(pwmdev::OutputLogicState::Direct)
            .map_err(PCA9685::do_map_err::<I2C, E>)
            .context("unable to set PCA9685 to non-inverted mode")?;
    }

    if config.output_driver_totem_pole {
        dev.set_output_driver(pwmdev::OutputDriver::TotemPole)
            .map_err(PCA9685::do_map_err::<I2C, E>)
            .context("unable to set PCA9685 to totem pole")?;
    } else {
        dev.set_output_driver(pwmdev::OutputDriver::OpenDrain)
            .map_err(PCA9685::do_map_err::<I2C, E>)
            .context("unable to set PCA9685 to open drain")?;
    }

    if config.use_external_clock {
        dev.use_external_clock()
            .map_err(PCA9685::do_map_err::<I2C, E>)
            .context("unable to set PCA9685 to external clock")?;
    }

    dev.enable()
        .map_err(PCA9685::do_map_err::<I2C, E>)
        .context("unable to enable PCA9685")?;

    // This needs to be set after the device is enabled, for some reason.
    dev.set_prescale(config.prescale)
        .map_err(PCA9685::do_map_err::<I2C, E>)
        .context("unable to set PCA9685 prescale")?;

    Ok(Pca9685Device {
        dev,
        last_change: Instant::now(),
        device_enabled: true,
        sleep_after: config
            .sleep_after_millis
            .clone()
            .map(|millis| Duration::from_millis(millis)),
    })
}

impl PCA9685Config {
    pub(crate) fn slave_address(&self) -> Result<pwmdev::Address> {
        let addr = self.i2c_slave_address;
        // PCA9685 has 0b1 fixed, and I2C addresses are 7 bits long,
        // so we check for a 0b01 prefix.
        ensure!((addr >> 6) ^ 0b01 == 0, "invalid address");

        Ok(pwmdev::Address::from(addr))
    }
}

pub struct PCA9685 {
    core: SynchronizedDeviceRWCore,
}

impl PCA9685 {
    pub fn new<I2C, E>(dev: I2C, config: &PCA9685Config, alias: String) -> Result<PCA9685>
    where
        I2C: hal::blocking::i2c::Write<Error = E>
            + Send
            + hal::blocking::i2c::WriteRead<Error = E>
            + 'static,
        E: Sync + Send + std::fmt::Debug + 'static,
    {
        let dev = set_up_device(dev, config)?;

        let inner = SynchronizedDeviceRWCore::new_from_core(DeviceRWCore::new_dirty(
            alias.clone(),
            16,
            ValueScaling::Logarithmic,
        ));
        let inner_thread = inner.clone();

        let update_interval_millise


         d="m1366 941.175 3.09-3.087a.577.577 0 0 1 .82 0c.23.227.23.597 0 .824l-3.09 3.088 3.09 3.088c.23.227.23.597 0 .824a.577.577 0 0 1-.82 0l-3.09-3.087-3.09 3.087a.577.577 0 0 1-.82 0 .58.58 0 0 1 0-.824l3.08-3.088-3.08-3.088a.58.58 0 0 1 0-.824.577.577 0 0 1 .82 0z"
                clipRule="evenodd"
            />
            <mask
                id="20_svg__h"
                width={10}
                height={10}
                x={1361}
                y={937}
                maskUnits="userSpaceOnUse"
                style={{maskType: "luminance"}}
            >
                <path
                    fill="#fff"
                    fillRule="evenodd"
                    d="m1366 941.175 3.09-3.087a.577.577 0 0 1 .82 0c.23.227.23.597 0 .824l-3.09 3.088 3.09 3.088c.23.227.23.597 0 .824a.577.577 0 0 1-.82 0l-3.09-3.087-3.09 3.087a.577.577 0 0 1-.82 0 .58.58 0 0 1 0-.824l3.08-3.088-3.08-3.088a.58.58 0 0 1 0-.824.577.577 0 0 1 .82 0z"
                    clipRule="evenodd"
                />
            </mask>
            <path
                fill="#2E2E2E"
                d="M206.824 949.128q-2.256 0-3.424-1.168t-1.168-3.44v-6.8h1.632v6.912q0 1.552.736 2.352.752.8 2.224.8 1.457 0 2.208-.8t.752-2.352v-6.912h1.632v6.8q0 2.256-1.184 3.44-1.168 1.168-3.408 1.168M217.953 941q1.008 0 1.792.512.8.511 1.232 1.44.448.928.448 2.144 0 1.2-.432 2.112a3.25 3.25 0 0 1-1.232 1.408q-.785.496-1.808.496-.88 0-1.552-.368a2.52 2.52 0 0 1-1.024-1.088v4.224h-1.616v-10.688h1.616v1.28a2.52 2.52 0 0 1 1.024-1.088q.672-.384 1.552-.384m-.384 6.832q1.056 0 1.632-.704.576-.72.576-2.032 0-1.328-.592-2.064-.576-.736-1.616-.736-1.056 0-1.632.72-.56.72-.56 2.048t.56 2.048q.576.72 1.632.72m12.845-10.112V949h-1.6v-1.344a2.53 2.53 0 0 1-1.024 1.088q-.672.368-1.552.368a3.3 3.3 0 0 1-1.808-.512q-.785-.511-1.232-1.44-.432-.928-.432-2.128 0-1.216.432-2.128.447-.912 1.232-1.408.783-.496 1.808-.496.879 0 1.536.384.672.368 1.024 1.056v-4.72zm-3.792 10.112q1.055 0 1.616-.72.576-.72.576-2.048t-.576-2.048q-.56-.72-1.616-.72t-1.648.72q-.576.703-.576 2.016 0 1.312.592 2.064.591.736 1.632.736m9.309-6.832q1.568 0 2.32.784.768.784.768 2.384V949h-1.552v-1.296a2.27 2.27


rustedui_nb_list, nb);
}

int trustedui_nb_send_event(unsigned long val, void *v)
{
	pr_info("%s:cmd = %ld mode = %d\n", __func__, val, (*(int *)v));
	return blocking_notifier_call_chain(&trustedui_nb_list, val, v);
}

void trustedui_set_mode(int mode)
{
	unsigned long flags;

	spin_lock_irqsave(&tui_lock, flags);
	if (tui_mode_3250 == mode) {
		spin_unlock_irqrestore(&tui_lock, flags);
		return;
	}
	pr_info("%s:mode[%d->%d]\n", __func__, tui_mode_3250, mode);
	tui_mode_3250 = mode;
	spin_unlock_irqrestore(&tui_lock, flags);
	trustedui_nb_send_event(TRUSTEDUI_MODE_CHANGE, (void *)&mode);
}
EXPORT_SYMBOL(trustedui_set_mode);

#endif /* CONFIG_SOC_EXYNOS3250 */


oryRaceTextAssetKeyClass = il2cpp_symbols::get_class_from_instance(key);
					StoryRaceTextAssetKeyClass_textField = { il2cpp_class_get_field_from_name(StoryRaceTextAssetKeyClass, "text") };
				}
				const auto text = il2cpp_symbols::read_field(key, StoryRaceTextAssetKeyClass_textField);
				il2cpp_symbols::write_field(key, StoryRaceTextAssetKeyClass_textField, il2cpp_symbols::NewWStr(localizedRaceData->textData[i++]));
			});
	}

	void* getLocalT2D(const std::filesystem::path& path);
	void DumpTexture2D(Il2CppObject* texture, const std::filesystem::path& savePath);

	void LocalizeAssets(void*& result, Il2CppString* name) {
		const auto cls = il2cpp_symbols::get_class_from_instance(result);
		if (cls == StoryTimelineDataClass)
		{
			const auto assetPath = std::filesystem::path(name->start_char).stem();
			const std::wstring_view assetName = assetPath.native();
			constexpr const wchar_t StoryTimelinePrefix[] = L"storytimeline_";
			constexpr const wchar_t HomeTimelinePrefix[] = L"hometimeline_";
			const auto storyId = assetName.starts_with(StoryTimelinePrefix) ? static_cast<std::size_t>(_wtoll(assetName.substr(std::size(StoryTimelinePrefix) - 1).data())) :
				assetName.starts_with(HomeTimelinePrefix) ? static_cast<std::size_t>(std::stoull([&] {
				auto range = assetName | std::ranges::views::drop(std::size(HomeTimelinePrefix) - 1) | std::ranges::views::filter([](wchar_t ch) { return ch != L'_'; });
				return std::wstring(std::ranges::begin(range), std::ranges::end(range));
					}())) : -1;
			if (storyId != -1)
			{
				LocalizeStoryTimelineData(result, storyId);
			}
		}
		else if (cls == StoryRaceTextAssetClass)
		{
			const auto assetPath = std::filesystem::path(name->start_char).stem();
			const std::wstring_view assetName = assetPath.native();
			constexpr const wchar_t RacePrefix[] = L"storyrace_";
			assert(assetName.starts_with(RacePrefix));
			LocalizeStoryRaceTextAsset(result, static_cast<std::size_t>(_wtoll(assetName.substr(std::size(RacePrefix) - 1).data())));
		}
		else if (cls == TextRubyDataClass) {
			LocalizeStoryTextRubyData(result);
		}
		else if (cls == Texture2DClass) {
			static const std::filesystem::path textureBasePath = "localized_data/res/texture2d/fromBundle";
			const std::filesystem::path texturePath = name->start_char;
			const auto localPath = textureBasePath / name->start_char;
			if (g_dump_bundle_tex) {
				DumpTexture2D((Il2CppObject*)result, texturePath.parent_path());
			}

			if (g_replace_assets) {
				const auto localReadPath = DLL_DIR / localPath;
				if (std::filesystem::exists(localReadPath)) {
					auto replaceT2D = getLocalT2D(localReadPath);
					if (replaceT2D) {
						result = replaceT2D;
					}
				}
			}
		}
	}

	void* AssetBundle_LoadAsset_orig;
	void* AssetBundle_LoadAsset_hook(void* _this, Il2CppString* name, Il2CppReflectionType* type)
	{
		UmaDatabase::setBundleHandleTargetCache(name->start_char, _this);
		//const auto stackTrace = environment_get_stacktrace();
		const auto& bundleHandle = GetBundleHandleByAssetName(name->start_char);
		if (bundleHandle)


End {
  FormalParameterBegin getBegin() {
    return children!.first as FormalParameterBegin;
  }
}

extension OptionalFormalParametersExtension on OptionalFormalParametersEnd {
  List<FormalParameterEnd> getFormalParameters() {
    List<FormalParameterEnd> result = [];
    for (ParserAstNode child in children!) {
      if (child is FormalParameterEnd) {
        result.add(child);
      }
    }
    return result;
  }
}

extension InitializersExtension on InitializersEnd {
  List<InitializerEnd> getInitializers() {
    List<InitializerEnd> result = [];
    for (ParserAstNode child in children!) {
      if (child is InitializerEnd) {
        result.add(child);
      }
    }
    return result;
  }

  InitializersBegin getBegin() {
    return children!.first as InitializersBegin;
  }
}

extension InitializerExtension on InitializerEnd {
  InitializerBegin getBegin() {
    return children!.first as InitializerBegin;
  }
}

void main(List<String> args) {
  File f = new File(args[0]);
  Uint8List data = f.readAsBytesSync();
  ParserAstNode ast = getAST(data);
  if (args.length > 1 && args[1] == "--benchmark") {
    Stopwatch stopwatch = new Stopwatch()..start();
    int numRuns = 100;
    for (int i = 0; i < numRuns; i++) {
      ParserAstNode ast2 = getAST(data);
      if (ast.what != ast2.what) {
        throw "Not the same result every time";
      }
    }
    stopwatch.stop();
    print("First $numRuns took ${stopwatch.elapsedMilliseconds} ms "
        "(i.e. ${stopwatch.elapsedMilliseconds / numRuns}ms/iteration)");
    stopwatch = new Stopwatch()..start();
    numRuns = 2500;
    for (int i = 0; i < numRuns; i++) {
      ParserAstNode ast2 = getAST(data);
      if (ast.what != ast2.what) {
        throw "Not the same result every time";
      }
    }
    stopwatch.stop();
    print("Next $numRuns took ${stopwatch.elapsedMilliseconds} ms "
        "(i.e. ${stopwatch.elapsedMilliseconds / numRuns}ms/iteration)");
  } else {
    print(ast);
  }
}

class ParserASTListener extends AbstractParserAstListener {
  @override
  void seen(ParserAstNode entry) {
    switch (entry.type) {
      case ParserAstType.BEGIN:
      case ParserAstType.HANDLE:
        // This just adds stuff.
        data.add(entry);
        break;
      case ParserAstType.END:
        // End should gobble up everything until the corresponding begin (which
        // should be the latest begin).
        int? beginIndex;
        for (int i = data.length - 1; i >= 0; i--) {
          if (data[i].type == ParserAstType.BEGIN) {
            beginIndex = i;
            break;
          }
        }
        if (beginIndex == null) {
          throw "Couldn't find a begin for ${entry.what}. Has:\n"
              "${data.map((e) => "${e.what}: ${e.type}").join("\n")}";
        }
        String begin = data[beginIndex].what;
        String end = entry.what;
        if (begin == end) {
          // Exact match.
        } else if (end == "TopLevelDeclaration" &&
            (begin == "ExtensionDeclarationPrelude" ||
                begin == "ClassOrMixinOrNamedMixinApplicationPrelude" ||
                begin == "TopLevelMember" ||
                begin == "UncategorizedTopLevelDeclaration")) {
          // endTopLevelDeclaration is started by one of
          // beginExtensionDeclarationPrelude,
          // beginClassOrNamedMixinApplicationPrelude
          // beginTopLevelMember or beginUncategorizedTopLevelDeclaration.
        } else if (begin == "Method" &&
            (end == "ClassConstructor" ||
                end == "ClassMethod" ||
                end == "ExtensionConstructor" ||
                end == "ExtensionMethod" ||
                end == "


,Inputs* inputs,IoModel* iomodel){

	int i,j;

	DataSet*     output_definitions      = NULL;
	int*         output_definition_enums = NULL;
	int          num_output_definitions;

	/*Create output_definitions dataset: */
	output_definitions=new DataSet();
	char** out_strings = NULL;
	iomodel->FetchData(&out_strings,&num_output_definitions,"md.outputdefinition.list");
	if(num_output_definitions>0){
		output_definition_enums=xNew<int>(num_output_definitions);
		for(int i=0;i<num_output_definitions;i++){
			output_definition_enums[i]=StringToEnumx(out_strings[i]);
		}
	}
	// free data:
	for(int i=0;i<num_output_definitions;i++) xDelete<char>(out_strings[i]);
	xDelete<char*>(out_strings);

	if(num_output_definitions){
		for (i=0;i<num_output_definitions;i++){
			if (output_definition_enums[i]==MassfluxatgateEnum){
				/*Deal with mass flux gates:{{{ */

				/*massfluxatgate variables: */
				int          temp,numgates;
				char       **gatenames           = NULL;
				char		  **gatedefinitionstrings = NULL;
				IssmDouble **gatesegments        = NULL;
				int         *gatesegments_M      = NULL;

				/*Fetch segments and names: */
				iomodel->FetchMultipleData(&gatenames,&numgates,                     "md.massfluxatgate.name");
				iomodel->FetchMultipleData(&gatedefinitionstrings,&temp,             "md.massfluxatgate.definitionstring"); _assert_(temp==numgates);
				iomodel->FetchMultipleData(&gatesegments,&gatesegments_M,NULL,&temp, "md.massfluxatgate.segments");         _assert_(temp==numgates);

				for(j=0;j<numgates;j++){
					output_definitions->AddObject(new Massfluxatgate<IssmDouble>(gatenames[j],StringToEnumx(gatedefinitionstrings[j]),gatesegments_M[j],gatesegments[j]));
				}
				/*Free resources:*/
				for(j=0;j<numgates;j++){
					char*       string  = gatenames[j];             xDelete<char>(string);
					char*       string2 = gatedefinitionstrings[j]; xDelete<char>(string2);
					IssmDouble* gate    = gatesegments[j];          xDelete<IssmDouble>(gate);
				}
				xDelete<char*>(gatenames);
				xDelete<IssmDouble*>(gatesegments);
				xDelete<int>(gatesegments_M);
				xDelete<char*>(gatedefinitionstrings);
				/*}}}*/
			}
			else if (output_definition_enums[i]==MisfitEnum){
				/*Deal with misfits: {{{*/

				/*misfit variables: */
				int          nummisfits;
				char**       misfit_name_s						= NULL;
				char**		 misfit_definitionstring_s		= NULL;
				char**       misfit_model_string_s			= NULL;
				IssmDouble** misfit_observation_s			= NULL;
				char**		 misfit_observation_string_s	= NULL;
				int*         misfit_observation_M_s			= NULL;
				int*         misfit_observation_N_s			= NULL;
				int*         misfit_local_s					= NULL;
				char**       misfit_timeinterpolation_s	= NULL;
				IssmDouble** misfit_weights_s					= NULL;
				int*         misfit_weights_M_s				= NULL;
				int*         misfit_weights_N_s				= NULL;
				char**       misfit_weights_string_


#region License Information
/* HeuristicLab
 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
 *
 * This file is part of HeuristicLab.
 *
 * HeuristicLab is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * HeuristicLab 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 HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
 */
#endregion

using System;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Data;
using HeuristicLab.Operators;
using HeuristicLab.Optimization;
using HeuristicLab.Parameters;
using HEAL.Attic;

namespace HeuristicLab.Selection {
  [Item("Replacer", "Generic replacer that replaces sub-scopes of the remaining scope with those from the selected scope.")]
  [StorableType("E92517F6-5936-4143-B07A-E76BC7A508F3")]
  public class Replacer : AlgorithmOperator, IReplacer {
    public IValueLookupParameter<ISelector> ReplacedSelectorParameter {
      get { return (IValueLookupParameter<ISelector>)Parameters["ReplacedSelector"]; }
    }
    public IValueLookupParameter<ISelector> SelectedSelectorParameter {
      get { return (IValueLookupParameter<ISelector>)Parameters["SelectedSelector"]; }
    }

    [StorableConstructor]
    protected Replacer(StorableConstructorFlag _) : base(_) { }
    protected Replacer(Replacer original, Cloner cloner) : base(original, cloner) { }
    public override IDeepCloneable Clone(Cloner cloner) {
      return new Replacer(this, cloner);
    }
    public Replacer() {
      Parameters.Add(new ValueLookupParameter<ISelector>("ReplacedSelector", "The selection operator to select those scopes that are to be replaced. If no selection operator is defined, random selection will be applied."));
      Parameters.Add(new ValueLookupParameter<ISelector>("SelectedSelector", "The se


using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using Microsoft.Win32;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using Utils.Web;

namespace Utils.Wpf.Behaviors;

/// <summary>
/// Attaches additional behavior for WebView2 control.
/// </summary>
public static class WebView2Behavior
{
    public static bool GetIsAttached(DependencyObject obj) => (bool)obj.GetValue(IsAttachedProperty);

    public static void SetIsAttached(DependencyObject obj, bool value) => obj.SetValue(IsAttachedProperty, value);

    public static readonly DependencyProperty IsAttachedProperty =
        DependencyProperty.RegisterAttached("IsAttached", typeof(bool), typeof(WebView2), new PropertyMetadata(false, OnIsAttachedChanged));

    public static string[] GetAllowedHosts(DependencyObject obj) => (string[])obj.GetValue(AllowedHostsProperty);

    public static void SetAllowedHosts(DependencyObject obj, string[] value) => obj.SetValue(AllowedHostsProperty, value);

    public static readonly DependencyProperty AllowedHostsProperty =
        DependencyProperty.RegisterAttached("AllowedHosts", typeof(string[]), typeof(WebView2), new PropertyMetadata(Array.Empty<string>()));

    public static bool GetAllowLocalFilesAccess(DependencyObject obj) => (bool)obj.GetValue(AllowLocalFilesAccessProperty);

    public static void SetAllowLocalFilesAccess(DependencyObject obj, bool value) => obj.SetValue(AllowLocalFilesAccessProperty, value);

    public static readonly DependencyProperty AllowLocalFilesAccessProperty =
        DependencyProperty.RegisterAttached("AllowLocalFilesAccess", typeof(bool), typeof(WebView2), new PropertyMetadata(false));

    public static void OnIsAttachedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(bool)e.NewValue)
        {
            return;
        }

        var webView2 = (WebView2)d;

        UpdateWebView2Environment(webView2);

        webView2.NavigationStarting += WebView2_NavigationStarting;
        webView2.Unloaded += WebView2_Unloaded;
    }

    private static void WebView2_NavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e)
    {
        if (sender is not DependencyObject obj)
        {
            return;
        }

        var allowedHosts = GetAllowedHosts(obj);

        if (allowedHosts.Length == 0 || allowedHosts.Any(host => e.Uri.StartsWith(host)))
        {
            return;
        }

        e.Cancel = true;
    }

    private static void WebView2_Unloaded(object sender, RoutedEventArgs e)
    {
        var webView2 = (WebView2)sender;

        if (webView2 == null)
        {
            return;
        }

        webView2.NavigationStarting -= WebView2_NavigationStarting;
        webView2.Unloaded -= WebView2_Unloaded;

        try
        {
            var coreWebView = webView2.CoreWebView2;

            if (coreWebView != null)
            {
                // Prevent WebView for producing sound after unload
                coreWebView.IsMuted = true;

                if (webView2.DataContext is IWebInterop webInterop)
                {
                    webInterop.SendJsonMessage -= coreWebView.PostWebMessageAsJson;
                    webView2.WebMessageReceived -= WebView2_WebMessageReceived;
                    webView2.CoreWebView2.ProcessFailed -= CoreWebView2_ProcessFailed;
                }
            }
        }
        catch (InvalidOperationException exc


dʋgbɩ dʋɩ dʋkʋ dʋkʋɛ dʋkʋɩ dʋnyra Ebɛlɩ Efɛsɩ Efɛsɩdɩɔ Efɛsɩkʋɛ Eflaimʋ Efratɩ Elasɩ Eli Eliakimʋ Eliesɛ Elimasɩ Elisabɛtɩ Elise Eliudɩ Eloi Elʋmadamʋ Emausɩdɩɔ emelodɩ Ene Epafrasɩ Epafroditɩ Esai Esau Esekiasɩ Esipʋblʋgba Esipʋkʋɛ Esipʋkʋɛyu Esri Etiɛnɩ Etisɩ ɛ Falɛkɩ Falɛsɩ Falisi꞊tumu Felisɩ Fenisiblʋgba Fɛtusɩ figie figietu Filadɛfidɩɔ Filipʋ Filipʋdɩɔ Flisi flɔɔ flɔɔdʋ flɔɔkui flɔɔkuo flɔɔkʋtɩɔ flɔɔpupu ga gaawɩ Gabriɛ Galatɩblʋgba Galileblʋgba Galilekʋɛ Galilekʋɛyu Galio Gamaliɛlɩ Gayusɩ gba gba꞊a gbaa gbaalɛ gbagba gbagbɩ gbagbʋ gbahlɔn gbakuo gbata gbati gbatɩ gbe gbee gbɛ gbɛ꞊ɛ gbɛɛ gbɛɛgbɛ gbɛɛlɛ gbɛtɛɛ gbi gbɩ gbla gbla꞊a gble gblegble gblɛ gblo gblohɩan gblotayu gbloyɔ gbo gboklo gboklolɛ gbolugbo gbolugbokayu gbolugbonuulɛ gbɔ gbɔgbɔ gbɔgbʋyɔ gbu gbugbe gbugbukʋɛ gbʋgba gbʋgbɛ gbʋgbla Gelasakʋɛ gese Gɛsɩmanɩ Glɛkɩkʋɛ Glɛkɩkʋɛwin Glɛkɩkʋɛyu glɩ Gomɔlɩ Gomɔlɩdɩɔ Gɔlʋgɔta gʋlʋ gʋlʋbɛtɩyɛ gʋlʋklaʋn gʋlʋnapɩtio gʋlʋnʋma gʋlʋnʋmapʋ gʋlʋpʋɛlɩ gʋlʋya ha ha꞊a haa haawɩ haawɔ Hagalɩ Haladɩɔ halɔ handɛ Hanɩ hanmakɩ hannya hanyɔ hanyʋ hapɛ hapɛ'gba hawi Helɔdiadɩ Helɔdɩ Henɔkɩ Henɔsɩ hɛ hɛ꞊ɛ hɛ꞊hɩʋɛn hɛ꞊wlɩlɛkɛɛdɛ hɛcrɩɩn hɛdɛ hɛɛ hɛɛ꞊ɛ hɛɛlɛ hɛɛn hɛɛnyibli hɛɛnyib


shields.io/badge/Deutsch-white" alt="version">          <a href="https://


 64*8*2 + 7>
    addr_szLut : 4x<64*8*2 + 64*8*2 + 8>
    addr_lut   : 4x<64*8*2 + 64*8*2 + 10>

[+ params() +]

</CONSTANT_MAPPING>

<REGISTER_MAPPING>

     3, 2,11,10,19,18,27,26 : cx<0-7>y0
     7, 6,15,14,23,22,31,30 : cx<0-7>y1
     1, 0, 9, 8,17,16,25,24 : cx<0-7>y2
     5, 4,13,12,21,20,29,28 : cx<0-7>y3
    35,34,43,42,51,50,59,58 : cx<0-7>y4
    39,38,47,46,55,54,63,62 : cx<0-7>y5
    33,32,41,40,49,48,57,56 : cx<0-7>y6
    37,36,45,44,53,52,61,60 : cx<0-7>y7

       0-63 : czero<00-63>

      64-67 : mpqk<0-3>
      64-66 : m, p, q
      64-71 : idx_M, idx_P, idx_Q, idx_K, idx_N, tid, tidY, negOne
     72-113 ~ tid1, tidX, idx_MPQk, idx_PQk, idx_Qk, idx_k, magic_PQk, magic_Qk, neg_PQk, neg_Qk, neg_k, div1, div2, div3, idx_P2, idx_Q2, q1, q2
     72-113 ~ mask_shr, rst, lutStore, lutStore2, warp_count, mt, pr, qs, dep_thd_mask, dep_thd_bits, dep_thd_cnt, t, r, s, rs, x, y, z, ballot, warp_slices, partial, endCRST, str_d, str_h, str_w, rst_prime, x_prime, y_prime, z_prime

      64-79 : j0Ix<0-7>, j0Fy<0-7>
      80-95 : j1Ix<0-7>, j1Fy<0-7>

      96-99 : trackI<0-1>, trackF<0-1>
    100-115 : loadI<0-7>,  loadF<0-7>

    108-113 ~ offsetF, offsetIc, offsetFc
    114-115 : sliceI, sliceF
    114-115 : sliceIF<0-1>

    116-125 ~ writeS, offsetIn, offsetFk, posCRST, posCRSTf, channel, lutSize, lutSizeRcp, lutOffset, offsetI
    126-127 ~ readFs, readIs

    72-91   : cs<0-7>, c<0-3>, b<0-7>
    72-83   ~ x<0-7>
    92-99   : out<0-7>
   100-101  : Out<0-1>
   102-103  : Sum<0-1>
   104-125  ~ writeCs, readCs, alpha, k, n, sum<0-3>, offset, out_offset, bsum_offset, tidOX, tidOY, preds, one

</REGISTER_MAPPING>

--:-:1:-:1      S2R tid,      SR_TID.X;
--:-:2:-:1      S2R idx_MPQk, SR_CTAID.X;
--:-:3:-:1      S2R idx_K,    SR_CTAID.Y;
--:-:4:-:1      S2R idx_N,    SR_CTAID.Z;

<SCHEDULE_BLOCK>
01:-:-:-:1      ISETP.GE.AND P0, PT, tid, 32, PT;

[+ load_zeros()


  "ENFP": ResultVO(
      mbti: "ENFP",
      person: "베드로",
      char1: "노래, 말, 찬양, 행동으로 믿음을 표현하는 것을 가치 있게 여김",
      char2: "은사를 의욕적으로 이행함",
      char3: "어린아이 같은 면이 있음",
      desc1: "새로운 인간관계에 두려움이 없음",
      desc2: "순간 집중력이 좋아 벼락치기에 능통함"),
  "ENFJ": ResultVO(
      mbti: "ENFJ",
      person: "요나단",
      char1: "자신의 시간과 노력을 기꺼이 다른 이에게 헌신함",
      char2: "여러 생각을 말씀에 적용하는 능력이 뛰어나 훌륭한 영적 멘토가 될 수 있음",
      char3: "말로 사람의 마음을 움직이게 하는 능력이 탁월함",
      desc1: "오지랖이 심함",
      desc2: "다른 사람의 성장을 도우면 굉장히 뿌듯해 함"),
  "ISTP": ResultVO(
      mbti: "ISTP",
      person: "노아",
      char1: "자신이 믿는 것에 대해 열정을 갖고, 신념을 지켜나감",
      char2: "사회나 청년 사역에서 섬기는 역할을 많이함",
      char3: "대부분 사회 모임에 참여하길 꺼리고, 옳고 그름에 민감한 사상가",
      desc1: "새로운 것에 그다지 동요하지 않음",
      desc2: "일반적으로 조용하지만 필요에 의해서는 사교적임"),
  "ISTJ": ResultVO(
      mbti: "ISTJ",
      person: "아브라함",
      char1: "교회에서 중요한 역할을 맡는 사람이고, 신뢰감 있고 안정적인 타입",
      char2: "진리에 대한 욕심이 많음",
      char3: "즉흥적인 것을 싫어하고 계획 세우는 것을 잘함",
      desc1: "책임감이 강해 한 번 일을 맡기면 신중하게 처리함",
      desc2: "말투가 가끔 직설적이라 딱딱하다는 소리 자주 들음"),
};

List<String> mbtiList = [
  "ENTJ",
  "ENTP",
  "ENFJ",
  "ENFP",
  "ESFJ",
  "ESFP",
  "ESTJ",
  "ESTP",
  "INFJ",
  "INFP",
  "INTJ",
  "INTP",
  "ISFJ",
  "ISFP",
  "ISTJ",
  "ISTP",
];

// ENTJ - 바울
// ENTP - 에훗
// ENFP - 베드로
// ENFJ - 요나단
// ESFJ - 요한
// ESFP - 야고보
// ESTJ - 여호수아
// ESTP - 스가랴
// INFJ - 예레미야
// INFP - 세례요한
// INTJ - 모세
// INTP - 솔로몬
// ISFJ - 마리아
// ISFP - 아담
// ISTP - 노아
// ISTJ - 아브라함
import 'package:flutter/material.dart';

import '../../common.dart';

extension SnackbarContextExtension on BuildContext {
  ///Scaffold안에 Snackbar를 보여줍니다.
  void showSnackbar(String message, {Widget? extraButton}) {
    _showSnackBarWithContext(
      this,
      _SnackbarFactory.createSnackBar(this, message, extraButton: extraButton),
    );
  }

  ///Scaffold안에 빨간 Snackbar를 보여줍니다.
  void showErrorSnackbar(
    String message, {
    Color bgColor = A


 // Fetch the quotes for this job and pick the most recent one
    final quotes = await DaoQuote().getByJobId(job.id);
    String? quoteNumber;
    int? quoteId;
    if (quotes.isNotEmpty) {
      // Sort quotes by modified date descending
      quotes.sort((a, b) => b.modifiedDate.compareTo(a.modifiedDate));
      final latestQuote = quotes.first;
      quoteNumber = latestQuote.bestNumber;
      quoteId = latestQuote.id;
    }

    return CompleteJobInfo(
      totals: totals,
      customerName: customerName,
      statusName: statusName,
      quoteNumber: quoteNumber,
      quoteId: quoteId,
    );
  }

  Future<JobTotals> _loadJobTotals(Job job) async {
    final tasks = await DaoTask().getTasksByJob(job.id);
    var totalLabour = MoneyEx.zero;
    var totalMaterials = MoneyEx.zero;

    for (final task in tasks) {
      final items = await DaoTaskItem().getByTask(task.id);
      final hourlyRate = await DaoTask().getHourlyRate(task);
      final billingType = await DaoTask().getBillingType(task);

      for (final item in items) {
        if (item.itemType == TaskItemType.labour) {
          totalLabour += item.calcLabourCharges(hourlyRate);
        } else {
          totalMaterials += item.calcMaterialCharges(billingType);
        }
      }
    }

    return JobTotals(
      labourCharges: totalLabour,
      materialsCharges: totalMaterials,
    );
  }
}

/// Holds totals for a job
class JobTotals {
  final Money labourCharges;
  final Money materialsCharges;

  JobTotals({required this.labourCharges, required this.materialsCharges});
}

/// Holds all required details for displaying the job card fields.
class CompleteJobInfo {
  final JobTotals totals;
  final String customerName;
  final String statusName;
  final String? quoteNumber;
  final int? quoteId;

  CompleteJobInfo({
    required this.totals,
    required this.customerName,
    required this.statusName,
    this.quoteNumber,
    this.quoteId,
  });
}
/*
 Copyright © OnePub IP Pty Ltd. S. Brett Sutton. All Rights Reserved.

 Note: This software is licensed under the GNU General Public License,
         with the following exceptions:
   • Permitted for internal use within your own business or organization only.
   • Any external distribution, resale, or incorporation into products
      for third parties is strictly prohibited.

 See the full license on GitHub:
 https://github.com/bsutton/hmb/blob/main/LICENSE
*/

/// Dashlet for active jobs count
library;

import 'package:flutter/material.dart';

import '../../../../dao/dao.g.dart';
import '../../../../util/flutter/flutter_util.g.dart';
import '../dashlet_card.dart';

class ReceiptDashlet extends StatelessWidget {
  const ReceiptDashlet({super.key});

  @override
  Widget build(BuildContext context) => DashletCard<String>.route(
    label: 'Receipts',
    hint: 'Track and Scan receipts',
    icon: Icons.receipt,
    value: getReceiptsThisMonth,
    route: '/home/accounting/receipts',
  );

  Future<DashletValue<String>> getReceiptsThisMonth() async {
    final now = DateTime.now();
    final receipts = await DaoReceipt().getByFilter(
      dateFrom: DateTime(now.year, now.month),
      dateTo: DateTime(now.year, now.month + 1, 0),
    );
    var total = MoneyEx.zero;
    for (final r in receipts) {
      total += r.totalIncludingTax;
    }
    return DashletValue('mtd: ${total.format('S#')}');
  }
}
import 'package:flutter/material.dart';


::LONG, "TileWidth");
    addEntry(323, tiff::Const::Type::LONG, "TileLength");
    addEntry(324, tiff::Const::Type::LONG, "TileOffsets");
    addEntry(325, tiff::Const::Type::LONG, "TileByteCounts");
    addEntry(326, tiff::Const::Type::LONG, "BadFaxLines");
    addEntry(327, tiff::Const::Type::LONG, "CleanFaxData");
    addEntry(328, tiff::Const::Type::LONG, "ConsecutiveBadFaxLines");
    addEntry(332, tiff::Const::Type::SHORT, "InkSet");
    addEntry(333, tiff::Const::Type::ASCII, "InkNames");
    addEntry(334, tiff::Const::Type::SHORT, "NumberOfInks");
    addEntry(336, tiff::Const::Type::SHORT, "DotRange");
    addEntry(337, tiff::Const::Type::ASCII, "TargetPrinter");
    addEntry(338, tiff::Const::Type::SHORT, "ExtraSamples");
    addEntry(339, tiff::Const::Type::SHORT, tiff::KnownTags::SAMPLE_FORMAT);
    addEntry(340, tiff::Const::Type::UNDEFINED, "SMinSampleValue");
    addEntry(341, tiff::Const::Type::UNDEFINED, "SMaxSampleValue");
    addEntry(342, tiff::Const::Type::SHORT, "TransferRange");
    addEntry(512, tiff::Const::Type::SHORT, "JPEGProc");
    addEntry(513, tiff::Const::Type::LONG, "JPEGInterchangeFormat");
    addEntry(514, tiff::Const::Type::LONG, "JPEGInterchangeFormatLngth");
    addEntry(515, tiff::Const::Type::SHORT, "JPEGRestartInterval");
    addEntry(517, tiff::Const::Type::SHORT, "JPEGLosslessPredictors");
    addEntry(518, tiff::Const::Type::SHORT, "JPEGPointTransforms");
    addEntry(519, tiff::Const::Type::LONG, "JPEGQTables");
    addEntry(520, tiff::Const::Type::LONG, "JPEGDCTables");
    addEntry(521, tiff::Const::Type::LONG, "JPEGACTables");
    addEntry(529, tiff::Const::Type::RATIONAL, "YCbCrCoefficients");
    addEntry(530, tiff::Const::Type::SHORT, "YCbCrSubSampling");
    addEntry(531, tiff::Const::Type::SHORT, "YCbCrPositioning");
    addEntry(532, tiff::Const::Type::LONG, "ReferenceBlackWhite");
    addEntry(559, tiff::Const::Type::LONG, "StripRowCounts");
    addEntry(700, tiff::Const::Type::BYTE, "XMP");
    addEntry(32781, tiff::Const::Type::ASCII, "ImageID");
    addEntry(33432, tiff::Const::Type::ASCII, "Copyright");
    addEntry(34732, tiff::Const::Type::LONG, "ImageLayer");

    // GeoTIFF Tags
    addEntry(33550, tiff::Const::Type::DOUBLE, "ModelPixelScaleTag");
    addEntry(33922, tiff::Const::Type::DOUBLE, "ModelTiepointTag");
    addEntry(34264, tiff::Const::Type::DOUBLE, "ModelTransformationTag");
    addEntry(34735, tiff::Const::Type::SHORT, "GeoKeyDirectoryTag");
    addEntry(34736, tiff::Const::Type::DOUBLE, "GeoDoubleParamsTag");
    addEntry(34737, tiff::Const::Type::ASCII, "GeoAsciiParamsTag");
}

tiff::KnownTags::~KnownTags()
{
    for(std::map<unsigned short, tiff::IFDEntry*>::iterator it = mKnownTags.begin();
        it != mKnownTags.end(); ++it)
        delete it->second;
    mKnownTags.clear();
}

void tiff::KnownTags::addEntry(const unsigned short tag,
                               const unsigned short type,
                               const std::string& name)
{
    std::map<unsigned short, tiff::IFDEntry*>::iterator pos =
        mKnownTags.find(tag);
    i


: NaN, endTime: NaN }
        },
        departure: { latitude: 3.0766802, longitude: 101.60453519999999 },
        arrival: { latitude: 3.1326988, longitude: 101.67225259999998 },
        type: "rider"
    }, {
        id: "u10",
        name: "siva rao",
        phone: "019792111",
        address: "j446, jalan pjs 10/11a, pjs 10, 46150 petaling jaya, selangor",
        schedule: {
            1: { startTime: 850, endTime: 1800 },
            2: { startTime: 850, endTime: 1800 },
            3: { startTime: 850, endTime: 1800 },
            4: { startTime: 850, endTime: 1800 },
            5: { startTime: 850, endTime: 1800 },
            6: { startTime: NaN, endTime: NaN },
            7: { startTime: NaN, endTime: NaN }
        },
        departure: { latitude: 3.0766647, longitude: 101.60438899999997 },
        arrival: { latitude: 3.1326988, longitude: 101.67225259999998 },
        type: "rider"
    }
];
import { primeirasLetrasParaMaiusculas } from "./ex6";

describe("Ordena array em ordem crescente", () => {
  it("Primeiro teste", () => {
    const teste = "Oi! Sou uma string bem legal para testes!";
    const result = primeirasLetrasParaMaiusculas(teste);

    expect(result).toEqual("Oi! Sou Uma String Bem Legal Para Testes!");
  });
});
import __SInterface from '@coffeekraken/s-interface';

/**
 * @name           active
 * @as              @sugar.when
 * @namespace      node.mixin.when
 * @type           PostcssMixin
 * @platform      postcss
 * @interface       ./when
 * @status        wip
 *
 * This mixin allows you to set some css applied only WHEN a specific "state" has been
 * reached.
 * Supported states are:
 * - mounted: When a sugar webcomponent has the "mounted" attribute
 * - active: When the element has the "active" class or the "active" attribute
 * - dark: When the prefered color scheme is dark
 * - light: When the prefered color scheme is light
 *
 * @param       {'mounted'|'active'|'dark'|'light'}         state           The state you want to target
 * @param       {'self'|'sibling'|'parent'|'ancestor'|'theme'}      [context='self']        The context of the when
 * @return        {Css}         The generated css
 *
 * @example        css
 * .myElement {
 *      display: none;
 *
 *      @sugar.when mounted {
 *          display: block;
 *      }
 * }
 *
 * @since       2.0.0
 * @author         Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
 */

class postcssSugarPluginmountedMixinInterface extends __SInterface {
    static get _definition() {
        return {
            state: {
                type: 'String',
                values: ['mounted', 'active', 'dark', 'light'],
                required: true,
            },
            context: {
                type: 'String',
                values: ['self', 'sibling', 'parent', 'ancestor', 'theme'],
                default: 'self',
                required: true,
            },
        };
    }
}
export { postcssSugarPluginmountedMixinInterface as interface };

export interface postcssSugarPluginmountedMixinParams {
    state: 'mounted' | 'active' | 'dark' | 'light';
    context: 'self' | 'sibling' | 'parent' | 'ancestor' | 'theme';
}
export default function ({
    params,
    atRule,
    postcssApi,
}: {
    params: Partial<postcssSugarPluginmountedMixinParams>;
    atRule: any;
    postcssApi: any;
}) {
    const finalParams = <postcssSugarPluginmounte


n\\t$tw.utils.createDirectory(path.dirname(dstPath));\\n\\t// Copy the file\\n\\tvar srcFile = fs.openSync(srcPath,\\\"r\\\"),\\n\\t\\tdstFile = fs.openSync(dstPath,\\\"w\\\"),\\n\\t\\tbytesRead = 1,\\n\\t\\tpos = 0;\\n\\twhile (bytesRead > 0) {\\n\\t\\tbytesRead = fs.readSync(srcFile,fileBuffer,0,FILE_BUFFER_LENGTH,pos);\\n\\t\\tfs.writeSync(dstFile,fileBuffer,0,bytesRead);\\n\\t\\tpos += bytesRead;\\n\\t}\\n\\tfs.closeSync(srcFile);\\n\\tfs.closeSync(dstFile);\\n\\treturn null;\\n};\\n\\n/*\\nRemove trailing path separator\\n*/\\nexports.removeTrailingSeparator = function(dirPath) {\\n\\tvar len = dirPath.length;\\n\\tif(dirPath.charAt(len-1) === path.sep) {\\n\\t\\tdirPath = dirPath.substr(0,len-1);\\n\\t}\\n\\treturn dirPath;\\n};\\n\\n/*\\nRecursively create a directory\\n*/\\nexports.createDirectory = function(dirPath) {\\n\\tif(dirPath.substr(dirPath.length-1,1) !== path.sep) {\\n\\t\\tdirPath = dirPath + path.sep;\\n\\t}\\n\\tvar pos = 1;\\n\\tpos = dirPath.indexOf(path.sep,pos);\\n\\twhile(pos !== -1) {\\n\\t\\tvar subDirPath = dirPath.substr(0,pos);\\n\\t\\tif(!$tw.utils.isDirectory(subDirPath)) {\\n\\t\\t\\ttry {\\n\\t\\t\\t\\tfs.mkdirSync(subDirPath);\\n\\t\\t\\t} catch(e) {\\n\\t\\t\\t\\treturn \\\"Error creating directory '\\\" + subDirPath + \\\"'\\\";\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tpos = dirPath.indexOf(path.sep,pos + 1);\\n\\t}\\n\\treturn null;\\n};\\n\\n/*\\nRecursively create directories needed to contain a specified file\\n*/\\nexports.createFileDirectories = function(filePath) {\\n\\treturn $tw.utils.createDirectory(path.dirname(filePath));\\n};\\n\\n/*\\nRecursively delete a directory\\n*/\\nexports.deleteDirectory = function(dirPath) {\\n\\tif(fs.existsSync(dirPath)) {\\n\\t\\tvar entries = fs.readdirSync(dirPath);\\n\\t\\tfor(var entryIndex=0; entryIndex\u003Centries.length; entryIndex++) {\\n\\t\\t\\tvar currPath = dirPath + path.sep + entries[entryIndex];\\n\\t\\t\\tif(fs.lstatSync(currPath).isDirectory()) {\\n\\t\\t\\t\\t$tw.utils.deleteDirectory(currPath);\\n\\t\\t\\t} else {\\n\\t\\t\\t\\tfs.unlinkSync(currPath);\\n\\t\\t\\t}\\n\\t\\t}\\n\\tfs.rmdirSync(dirPath);\\n\\t}\\n\\treturn null;\\n};\\n\\n/*\\nCheck if a path identifies a directory\\n*/\\nexports.isDirectory = function(dirPath) {\\n\\treturn fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory();\\n};\\n\\n/*\\nCheck if a path identifies a directory that is empty\\n*/\\nexports.isDirectoryEmpty = function(dirPath) {\\n\\tif(!$tw.utils.isDirectory(dirPath)) {\\n\\t\\treturn false;\\n\\t}\\n\\tvar files = fs.readdirSync(dirPath),\\n\\t\\tempty = true;\\n\\t$tw.utils.each(files,function(file,index) {\\n\\t\\tif(file.charAt(0) !== \\\".\\\") {\\n\\t\\t\\temp


hingPortName, _ports[matchingPortName]!)));
      }
      return matchingPorts;
    }
  }

  /// Adds a single new port to this [Interface], associated with [tags]
  /// and with name [portName].
  ///
  /// If no [portName] is specified, then [port]'s name is used.
  void _setPort(Logic port, {Iterable<TagType>? tags, String? portName}) {
    portName ??= port.name;

    assert(!_ports.containsKey(portName),
        'Port named $portName already exists on this interface.');

    _ports[portName] = port;
    if (tags != null) {
      if (!_portToTagMap.containsKey(portName)) {
        _portToTagMap[portName] = <TagType>{};
      }
      _portToTagMap[portName]!.addAll(tags);
    }
  }

  /// Adds a collection of ports to this [Interface], each associated with all
  /// of [tags].
  ///
  /// All names of ports are gotten from the names of the [ports].
  @protected
  void setPorts(List<Logic> ports, [Iterable<TagType>? tags]) {
    for (final port in ports) {
      _setPort(port, tags: tags);
    }
  }

  /// Makes `this` drive interface signals tagged with [tags] on [other].
  void driveOther(Interface<TagType> other, Iterable<TagType> tags) {
    getPorts(tags).forEach((portName, thisPort) {
      other.port(portName) <= thisPort;
    });
  }

  /// Makes `this` signals tagged with [tags] be driven by [other].
  void receiveOther(Interface<TagType> other, Iterable<TagType> tags) {
    getPorts(tags).forEach((portName, thisPort) {
      thisPort <= other.port(portName);
    });
  }

  /// Makes `this` conditionally drive interface signals tagged with [tags] on
  /// [other].
  Conditional conditionalDriveOther(
          Interface<TagType> other, Iterable<TagType> tags) =>
      ConditionalGroup(getPorts(tags)
          .map((portName, thisPort) =>
              MapEntry(portName, other.port(portName) < thisPort))
          .values
          .toList(growable: false));

  /// Makes `this` signals tagged with [tags] be driven conditionally by
  /// [other].
  Conditional conditionalReceiveOther(
          Interface<TagType> other, Iterable<TagType> tags) =>
      ConditionalGroup(getPorts(tags)
          .map((portName, thisPort) =>
              MapEntry(portName, thisPort < other.port(portName)))
          .values
          .toList(growable: false));

  /// Creates a new [Interface] with the same ports as `this`.
  ///
  /// It is expected that any implementation will override this in a way that
  /// returns the same type as itself.
  @mustBeOverridden
  Interface<TagType> clone() {
    final newIntf = Interface<TagType>();
    _portToTagMap.forEach((portName, tags) {
      newIntf.setPorts([port(portName).clone()], tags);
    });
    return newIntf;
  }
}
// Copyright (C) 2023-2025 Intel Corporation
// SPDX-License-Identifier: BSD-3-Clause
//
// vcd_parser.dart
// Utility for parsing VCD files for tests
//
// 2023 January 5
// Author: Max Korbel <max.korbel@intel.com>

import 'package:rohd/rohd.dart';

/// State of VCD parsing
enum _VcdParseState { findSig, findDumpVars, findValue }

/// A parser for VCD files for testing purposes.
abstract class VcdParser {
  /// Checks that the contents of a VCD file ([vcdContents]) have [value] on
  /// [signalName] at time [timestamp].
  ///
  /// This function is basic and only works on flat, single modules, or at least
  /// cases where only one signal is named [signalName] across all scopes.
  static bool confirmValue(
      String vcdContents, String signalName, int timestamp, LogicValue value) {
    final lines = vcd


eToProjectionSet.hh"
#include "GateToInterfile.hh"
#include "GateARFSD.hh"  /* PY Descourt 08/09/2009 */
#include "GateDetectorConstruction.hh" /* PY Descourt 08/09/2009 */

// Constructor
GateSPECTHeadSystem::GateSPECTHeadSystem(const G4String& itsName) :
    GateVSystem(itsName, false), m_gateToProjectionSet(0), m_gateToInterfile(0)
{
  m_ARFStage = -2;
  //TODO GND 2022: Do not insert ARF SD by default
  //GateDetectorConstruction::GetGateDetectorConstruction()->insertARFSD(GetObjectName(),m_ARFStage);

  // Setup a messenger
  m_messenger = new GateClockDependentMessenger(this);
  m_messenger->SetDirectoryGuidance(G4String("Controls the system '") + GetObjectName() + "'" );

    m_messenger->SetARFCommands();

  // Define the scanner components
  m_crystalComponent = new GateSystemComponent("crystal",GetBaseComponent(),this);
  m_pixelComponent = new GateSystemComponent("pixel",m_crystalComponent,this);

  // Insert a projection-set maker and a Interfile writer into the output manager
  GateOutputMgr *outputMgr = GateOutputMgr::GetInstance();
  m_gateToProjectionSet = new GateToProjectionSet("projection",
                                                  outputMgr,
                                                  this,
                                                  GateOutputMgr::GetDigiMode());
  outputMgr->AddOutputModule((GateVOutputModule*)m_gateToProjectionSet);
  m_gateToInterfile = new GateToInterfile("interfile",
                                          outputMgr,
                                          this,
                                          GateOutputMgr::GetDigiMode());
  outputMgr->AddOutputModule((GateVOutputModule*)m_gateToInterfile);

  SetOutputIDName((char *)"headID",0);
  SetOutputIDName((char *)"crystalID",1);
  SetOutputIDName((char *)"pixelID",2);
}

// Destructor
GateSPECTHeadSystem::~GateSPECTHeadSystem()
{
  delete m_messenger;

  // Note that we don't delete our output modulesor components, as this will be done by the
  // output manager or byt the base-class respectively
}

/* PY Descourt 08/09/2009 */
void GateSPECTHeadSystem::setARFStage(G4String thestage)
{

  if (thestage == "generateData")
    m_ARFStage = 0;
  else if (thestage == "computeTables")
    m_ARFStage = 1;
  else if (thestage == "useTables")
    m_ARFStage = 2;

 GateARFSD* ARFSD = GateDetectorConstruction::GetGateDetectorConstruction()->GetARFSD();

  if (ARFSD != 0)
    ARFSD->SetStage(m_ARFStage);

  G4cout << " GateSPECTHeadSystem::setARFStage  stage = "
         << thestage
         << "  "
         << m_ARFStage
         << Gateendl;

  if (m_ARFStage == -2)
    {
    G4String msg = "GateSPECTHeadSystem::setARFStage stage '" + thestage + "' is not valid.";
    G4Exception("GateSPECTHeadSystem::setARFStage", "setARFStage", FatalException, msg);
    }
 }
/* PY Descourt 08/09/2009 */

/*----------------------
   Copyright (C): OpenGATE Collaboration

This software is distributed under the terms
of the GNU Lesser General  Public Licence (LGPL)
See LICENSE.md for further details
----------------------*/

/*! \file
  \brief Implementation of GateImageRegionalizedSubVolume
 */

#include "GateImageRegionalizedSubVolume.hh"
#include "GateImageRegionalizedSubVolumeMessenger.hh"
#include "GateImageRegionalizedSubVolumeSolid.hh"
#include "GateDetectorConstruction.hh


�合重要性和时间因素 - 创建复合得分
                memories.map { memory ->
                    val timeFactor = 1.0f / (1 + (System.currentTimeMillis() - memory.timestamp.time) / (1000 * 60 * 60 * 24 * 30f))
                    val importanceFactor = memory.importance / 10f
                    val hybridScore = importanceFactor * 0.7f + timeFactor * 0.3f

                    Pair(memory, hybridScore)
                }.sortedByDescending { it.second }
                    .take(memories.size / 3) // 取前三分之一作为候选
                    .map { it.first }
            }
        }

        // 确保返回足够的候选数量
        return if (candidateMemories.size < 5 && memories.size > 5) {
            // 如果候选太少，补充一些高重要性的记忆
            val additionalMemories = memories
                .filter { it !in candidateMemories }
                .sortedByDescending { it.importance }
                .take(5 - candidateMemories.size)

            (candidateMemories + additionalMemories).distinctBy { it.id }
        } else {
            candidateMemories
        }
    }

    /**
     * 检测是否包含最近时间引用
     */
    private fun containsRecentReference(text: String): Boolean {
        val recentPatterns = arrayOf(
            "(最近|近期|这几天|这段时间|上次|刚刚|之前|前几天|不久前)",
            "(上周|上个月|上次聊过|以前说过|前面提到)"
        )

        for (pattern in recentPatterns) {
            if (Regex(pattern).find(text) != null) {
                return true
            }
        }
        return false
    }

    /**
     * 检测是否包含时间引用
     */
    private fun containsTimeReference(text: String): Boolean {
        val timePatterns = arrayOf(
            "(昨天|今天|明天|后天|周末|下周|上周|上个月|下个月|年初|年底|春节|新年)",
            "(几点|时间|日期|几月|星期|哪天|早上|中午|下午|晚上|凌晨)",
            "(时间表|行程|计划|安排|日程|提醒|闹钟|定时|提醒)",
            "(多久|多长时间|几个月|几年|多少天)"
        )

        for (pattern in timePatterns) {
            if (Regex(pattern).find(text) != null) {
                return true
            }
        }
        return false
    }

    /**
     * 计算针对最近查询的时间提升因子
     */
    private fun calculateRecentTimeBoost(timestamp: Date): Float {
        val now = System.currentTimeMillis()
        val ageInDays = (now - timestamp.time) / (1000 * 60 * 60 * 24f)

        // 对于"最近"查询，最近7天记忆有显著提升，30天内有轻微提升
        return when {
            ageInDays <= 7 -> 1.5f
            ageInDays <= 30 -> 1.2f
            else -> 1.0f
        }
    }

    /**
     * 检查是否有精确的关键词匹配
     */
    private fun hasExactKeywordMatch(userWords: List<String>, memoryKeywords:


import os
import numpy as np

import torch

def create_if_not_exists(path: str) -> None:
    if not os.path.exists(path):
        os.makedirs(path)

def off_diagonal(x):
    n, m = x.shape
    assert n == m
    return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()

def save_networks(model, communication_idx):
    nets_list = model.nets_list
    model_name = model.NAME

    checkpoint_path = model.checkpoint_path
    model_path = os.path.join(checkpoint_path, model_name)
    model_para_path = os.path.join(model_path, 'para')
    create_if_not_exists(model_para_path)
    for net_idx, network in enumerate(nets_list):
        each_network_path = os.path.join(model_para_path, str(communication_idx) + '_' + str(net_idx) + '.ckpt')
        torch.save(network.state_dict(), each_network_path)

def save_protos(model, communication_idx):
    model_name = model.NAME

    checkpoint_path = model.checkpoint_path
    model_path = os.path.join(checkpoint_path, model_name)
    model_para_path = os.path.join(model_path, 'protos')
    create_if_not_exists(model_para_path)

    for i in range(len(model.global_protos_all)):
        label = i
        protos = torch.cat(model.global_protos_all[i], dim=0).cpu().numpy()
        save_path = os.path.join(model_para_path, str(communication_idx) + '_' + str(label) + '.npy')
        np.save(save_path, protos)


 "p": "jiàn", "sp": "jian", "r": "言", "sc": 15, "l": 5, "f": 8353},
  {"h": "謧", "p": "lí", "sp": "li", "r": "言", "sc": 17, "l": 5, "f": 8354},
  {
    "h": "謪",
    "p": "shāng",
    "sp": "shang",
    "r": "言",
    "sc": 18,
    "l": 5,
    "f": 8355
  },
  {"h": "譁", "p": "huá", "sp": "hua", "r": "言", "sc": 17, "l": 5, "f": 8356},
  {"h": "貤", "p": "yí", "sp": "yi", "r": "貝", "sc": 10, "l": 5, "f": 8357},
  {
    "h": "赪",
    "p": "chēng",
    "sp": "cheng",
    "r": "赤",
    "sc": 13,
    "l": 5,
    "f": 8358
  },
  {"h": "踖", "p": "jí", "sp": "ji", "r": "足", "sc": 15, "l": 5, "f": 8359},
  {"h": "軆", "p": "tǐ", "sp": "ti", "r": "身", "sc": 20, "l": 5, "f": 8360},
  {"h": "輈", "p": "zhōu", "sp": "zhou", "r": "車", "sc": 13, "l": 5, "f": 8361},
  {"h": "鄛", "p": "cháo", "sp": "chao", "r": "邑", "sc": 13, "l": 5, "f": 8362},
  {"h": "鄡", "p": "qiāo", "sp": "qiao", "r": "邑", "sc": 13, "l": 5, "f": 8363},
  {"h": "醖", "p": "yùn", "sp": "yun", "r": "酉", "sc": 16, "l": 5, "f": 8364},
  {"h": "屺", "p": "qǐ", "sp": "qi", "r": "山", "sc": 6, "l": 5, "f": 8365},
  {"h": "鍑", "p": "fù", "sp": "fu", "r": "金", "sc": 17, "l": 5, "f": 8366},
  {"h": "鏉", "p": "shòu", "sp": "shou", "r": "金", "sc": 19, "l": 5, "f": 8367},
  {"h": "雊", "p": "gòu", "sp": "gou", "r": "隹", "sc": 13, "l": 5, "f": 8368},
  {
    "h": "顓",
    "p": "zhuān",
    "sp": "zhuan",
    "r": "頁",
    "sc": 18,
    "l": 5,
    "f": 8369
  },
  {"h": "飐", "p": "zhǎn", "sp": "zhan", "r": "風", "sc": 9, "l": 5, "f": 8370},
  {"h": "稆", "p": "lǚ", "sp": "lu", "r": "禾", "sc": 11, "l": 5, "f": 8371},
  {"h": "駳", "p": "dàn", "sp": "dan", "r": "馬", "sc": 16, "l": 5, "f": 8372},
  {"h": "騽", "p": "xí", "sp": "xi"


antile(4.0/(d.Count-1)))
	assert.True(t, math.IsNaN(d.UpperQuantile(4.5/(d.Count-1))))
}
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2021 Datadog, Inc.

package store

import (
	"math"

	enc "github.com/DataDog/sketches-go/ddsketch/encoding"
)

type CollapsingHighestDenseStore struct {
	DenseStore
	maxNumBins  int
	isCollapsed bool
}

func NewCollapsingHighestDenseStore(maxNumBins int) *CollapsingHighestDenseStore {
	return &CollapsingHighestDenseStore{
		DenseStore:  DenseStore{minIndex: math.MaxInt32, maxIndex: math.MinInt32},
		maxNumBins:  maxNumBins,
		isCollapsed: false,
	}
}

func (s *CollapsingHighestDenseStore) Add(index int) {
	s.AddWithCount(index, float64(1))
}

func (s *CollapsingHighestDenseStore) AddBin(bin Bin) {
	index := bin.Index()
	count := bin.Count()
	if count == 0 {
		return
	}
	s.AddWithCount(index, count)
}

func (s *CollapsingHighestDenseStore) AddWithCount(index int, count float64) {
	if count == 0 {
		return
	}
	arrayIndex := s.normalize(index)
	s.bins[arrayIndex] += count
	s.count += count
}

// Normalize the store, if necessary, so that the counter of the specified index can be updated.
func (s *CollapsingHighestDenseStore) normalize(index int) int {
	if index > s.maxIndex {
		if s.isCollapsed {
			return len(s.bins) - 1
		} else {
			s.extendRange(index, index)
			if s.isCollapsed {
				return len(s.bins) - 1
			}
		}
	} else if index < s.minIndex {
		s.extendRange(index, index)
	}
	return index - s.offset
}

func (s *CollapsingHighestDenseStore) getNewLength(newMinIndex, newMaxIndex int) int {
	return min(s.DenseStore.getNewLength(newMinIndex, newMaxIndex), s.maxNumBins)
}

func (s *CollapsingHighestDenseStore) extendRange(newMinIndex, newMaxIndex int) {
	newMinIndex = min(newMinIndex, s.minIndex)
	newMaxIndex = max(newMaxIndex, s.maxIndex)
	if s.IsEmpty() {
		initialLength := s.getNewLength(newMinIndex, newMaxIndex)
		s.bins = append(s.bins, make([]float64, initialLength)...)
		s.offset = newMinIndex
		s.minIndex = newMinIndex
		s.maxIndex = newMaxIndex
		s.adjust(newMinIndex, newMaxIndex)
	} else if newMinIndex >= s.offset && newMaxIndex < s.offset+len(s.bins) {
		s.minIndex = newMinIndex
		s.maxIndex = newMaxIndex
	} else {
		// To avoid shifting too often when nearing the capacity of the array,
		// we may grow it before we actually reach the capacity.
		newLength := s.getNewLength(newMinIndex, newMaxIndex)
		if newLength > len(s.bins


, true); return _Size[type];
			case Type.s16: this.Buffer.setInt16(offset, value, true); return _Size[type];
			case Type.u32: this.Buffer.setUint32(offset, value, true); return _Size[type];
			case Type.s32: this.Buffer.setInt32(offset, value, true); return _Size[type];
			case Type.f32: this.Buffer.setFloat32(offset, value, true); return _Size[type];
			case Type.f64: this.Buffer.setFloat64(offset, value, true); return _Size[type];
			case Type.string: {
				for(var i = 0; i < (value as string).length; i++) {
					this.Buffer.setUint8(offset++, (value as string).charCodeAt(i));
				}
				this.Buffer.setUint8(offset++, 0x00);
				return offset;
			}
		}
		return offset;
	}

	/**
	 * Takes a type and value then writes it to the buffer and advances the current position
	 * @param type - The type of data to write to the buffer
	 * @param value - The value to write to the buffer
	 */
	Write(type:Type, value:any):any {
		this.Position += this.Poke(type, value);
		return true;
	}
}/**
 * Transforms callback-based function -- func(arg1, arg2 .. argN, callback) -- into an ES6-compatible Promise.
 * Promisify provides a default callback of the form (error, result) and rejects when `error` is not null. You can also
 * supply thisArg object as the second argument which will be passed to `apply`.
 */
export declare function promisify<T>(originalFn: (...args: any[]) => void, thisArg?: any): (...callArgs: any[]) => Promise<T>;
import type { Meta, StoryObj } from '@storybook/vue';

import NewDateInput from '@/components/stepforms/widgets/DateComponents/NewDateInput.vue';
import type { AvailableVariable } from '@/lib/variables';

export default {
  component: NewDateInput,
} as Meta<NewDateInput>;

const RELATIVE_SAMPLE_VARIABLES: AvailableVariable[] = [
  {
    label: 'Today',
    identifier: 'today',
    value: new Date('1/12/2021'),
  },
  {
    label: 'Last month',
    identifier: 'last_month',
    value: new Date('11/12/2021'),
  },
  {
    label: 'Last year',
    identifier: 'last_year',

    value: new Date('1/12/2020'),
  },
];

const SAMPLE_VARIABLES: AvailableVariable[] = [
  {
    identifier: 'dates.last_7_days',
    label: 'Last 7 days',
  },
  {
    identifier: 'dates.last_14_days',
    label: 'Last 14 days',
  },
  {
    identifier: 'dates.last_30_days',
    label: 'Last 30 days',
  },
  {
    identifier: 'dates.last_3_months',
    label: 'Last 3 Months',
  },
  {
    identifier: 'dates.last_12_months',
    label: 'Last 12 Months',
  },
  {
    identifier: 'dates.month_to_date',
    label: 'Month to date',
  },
  {
    identifier: 'dates.quarter_to_date',
    label: 'Quarter to date',
  },
  {
    identifier: 'dates.all_time',
    label: 'All time',
  },
  ...RELATIVE_SAMPLE_VARIABLES,
];

export const Default: StoryObj<NewDateInput> = {
  render: (args, { argTypes }) => ({
    components: { NewDateInput },
    props: Object.keys(argTypes),
    data() {
      return {
        value: undefined,
        actualRangeValue: undefined,
      };
    },
    template: `
      <div>
      <NewDateInput
        :available-variables="availableVariables"
        :variable-delimiters="variableDelimiters"