 *
 * The Apache Lucene ASCII Folding Filter is licensed to the Apache Software
 * Foundation (ASF) under one or more contributor license agreements. See the
 * NOTICE file distributed with this work for additional information regarding
 * copyright ownership. The ASF licenses this file to You under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
class ASCIIFolder {

    static foldReplacing(str = '', replacement = '') {
        return this._fold(str, () => replacement);
    }

    static foldMaintaining(str = '') {
        return this._fold(str, (char) => char);
    }

    static _fold(str, fallback) {
        if (str === null)
            return '';

        if (typeof str === 'number')
            return '' + str;

        if (typeof str !== 'string')
            throw new Error('Invalid input data type');

        return str.split('').map(character => {
            if (character.charCodeAt(0) < 128) {
                return character;
            } else {
                const replacement = this.mapping.get(character.charCodeAt(0));
                return (replacement === undefined) ? fallback(character) : replacement;
            }
        }).join('');
    }
}

ASCIIFolder.mapping = new Map([
    [0xC0, 'A'],
    [0xC1, 'A'],
    [0xC2, 'A'],
    [0xC3, 'A'],
    [0xC4, 'A'],
    [0xC5, 'A'],
    [0x100, 'A'],
    [0x102, 'A'],
    [0x104, 'A'],
    [0x18F, 'A'],
    [0x1CD, 'A'],
    [0x1DE, 'A'],
    [0x1E0, 'A'],
    [0x1FA, 'A'],
    [0x200, 'A'],
    [0x202, 'A'],
    [0x226, 'A'],
    [0x23A, 'A'],
    [0x1D00, 'A'],
    [0x1E00, 'A'],
    [0x1EA0, 'A'],
    [0x1EA2, 'A'],
    [0x1EA4, 'A'],
    [0x1EA6, 'A'],
    [0x1EA8, 'A'],
    [0x1EAA, 'A'],
    [0x1EAC, 'A'],
    [0x1EAE, 'A'],
    [0x1EB0, 'A'],
    [0x1EB2, 'A'],
    [0x1EB4, 'A'],
    [0x1EB6, 'A'],
    [0x24B6, 'A'],
    [0xFF21, 'A'],
    [0xE0, 'a'],
    [0xE1, 'a'],
    [0xE2, 'a'],
    [0xE3, 'a'],
    [0xE4, 'a'],
    [0xE5, 'a'],
    [0x101, 'a'],
    [0x103, 'a'],
    [0x105, 'a'],
    [0x1CE, 'a'],
    [0x1DF, 'a'],
    [0x1E1, 'a'],
    [0x1FB, 'a'],
    [0x201, 'a'],
    [0x203, 'a'],
    [0x227, 'a'],
    [0x250, 'a'],
    [0x259, 'a'],
    [0x25A, 'a'],
    [0x1D8F, 'a'],
    [0x1D95, 'a'],
    [0x1E01, 'a'],
    [0x1E9A, 'a'],
    [0x1EA1,


surface.toByteArray(UTF_8)
            val leftId: Short = morpheme.leftId
            val rightId: Short = morpheme.rightId
            val cost: Int = morpheme.cost
            val feature: List<String> = deDupeFeatureArray(morpheme.feature.split(","))
            val mType: Byte = morpheme.mType.id().toByte()
            val poses: ByteArray by lazy {
                val buffer = ByteBuffer.allocate(morpheme.poses.length())
                buffer.rewind()
                morpheme.poses.foreach { buffer.put(it.id().toByte()) }
                buffer.array()
            }

            return SafeCompressedMorpheme(surface, leftId, rightId, cost, feature, mType, poses)
        }

        /**
         * Scala 2.12의 WrappedArray가 포함되어 De-Serialization에 문제가 있던 TermDict를 다시 추출합니다.
         * 실행은 ./gradlew :koalanlp-eunjeon:run으로 간단히 수행되며,
         * 실행 결과로 저장되는 파일은 자동으로 필요한 resource path에 추가됩니다.
         * 배포되는 SEunjeon 패키지에는 이 파일이 포함되어 있으나, Github에는 업로드 크기 정책으로 인해 올라가지 않습니다.
         */
        @JvmStatic
        fun main(args: Array<String>) {
            val file = File("src/main/resources/" + DictBuilder.TERM_DICT() + ".kt")
            if (!file.parentFile.exists())
                file.parentFile.mkdirs()

            if (!file.exists()) {
                val lexicon = LexiconDict().load(true)
                val termDict = lexicon.termDict().map { apply(it) }.toTypedArray()
                val objectOutputStream = ObjectOutputStream(File("./src/main/resources/" + DictBuilder.TERM_DICT() + ".koala")
                        .outputStream().buffered(16 * 1024))
                objectOutputStream.writeObject(termDict)
                objectOutputStream.close()
            }
        }
    }
}

/**
 * 은전한닢 사용자사전 인터페이스입니다.
 *
 * @since 1.x
 */
object Dictionary : CanCompileDict {
    @JvmStatic
    private val leftIDMap: Map<String, Short> by lazy {
        NngUtil::class.java.classLoader.getResourceAsStream(DictBuilder.LEFT_ID_DEF().drop(1)).bufferedReader().lines()
                .iterator().asSequence()
                .map {
                    val splits = it.split(" ")
                    splits[1].replace("^([^,]+,[^,]+),.*".toRegex(), "$1") to splits[0].toShort()
                }.groupBy { it.first }
                .filterValues { it.isNotEmpty() }
                .mapValues { it.value.maxBy { x -> x.second }!!.second }
    }

    @JvmStatic
    private val rightIDMap: Map<String, Short> by lazy {
        NngUtil::class.java.classLoader.getResourceAsStream(DictBuilder.RIGHT_ID_DEF().drop(1)).bufferedReader().lines()
                .iterator().asSequence()
                .map {
                    val splits = it.split(" ")
                    splits[1].replace("^([^,]+,[^,]+


  IRHitachiAc424 ac(kGpioUnused);
  ac.on();
  EXPECT_EQ(ac.getButton(), kHitachiAc424ButtonPowerMode);
  ac.setButton(kHitachiAc424ButtonTempUp);
  EXPECT_EQ(ac.getButton(), kHitachiAc424ButtonTempUp);
  ac.setButton(kHitachiAc424ButtonSwingV);
  EXPECT_EQ(ac.getButton(), kHitachiAc424ButtonSwingV);
}

TEST(TestIRHitachiAc424Class, ToggleSwingVertical) {
  IRHitachiAc424 ac(kGpioUnused);
  ac.on();
  EXPECT_EQ(ac.getButton(), kHitachiAc424ButtonPowerMode);
  ac.setSwingVToggle(true);
  EXPECT_TRUE(ac.getSwingVToggle());
  EXPECT_EQ(ac.getButton(), kHitachiAc424ButtonSwingV);
  ac.setSwingVToggle(false);
  EXPECT_FALSE(ac.getSwingVToggle());
  EXPECT_EQ(ac.getButton(), kHitachiAc424ButtonPowerMode);
}

TEST(TestIRHitachiAc424Class, HumanReadable) {
  IRHitachiAc424 ac(kGpioUnused);

  ac.setMode(kHitachiAc424Heat);
  ac.setTemp(kHitachiAc424MaxTemp);
  ac.on();
  ac.setFan(kHitachiAc424FanHigh);
  EXPECT_EQ(
      "Power: On, Mode: 6 (Heat), Temp: 32C, Fan: 4 (High), "
      "Button: 66 (Fan), Swing(V) Toggle: Off",
      ac.toString());
  ac.setMode(kHitachiAc424Cool);
  ac.setFan(kHitachiAc424FanMin);
  ac.setTemp(kHitachiAc424MinTemp);
  EXPECT_EQ(
      "Power: On, Mode: 3 (Cool), Temp: 16C, Fan: 1 (Min), "
      "Button: 67 (Temp Down), Swing(V) Toggle: Off",
      ac.toString());
  ac.setSwingVToggle(true);
  EXPECT_EQ(
      "Power: On, Mode: 3 (Cool), Temp: 16C, Fan: 1 (Min), "
      "Button: 129 (Swing(V)), Swing(V) Toggle: On",
      ac.toString());
  ac.setTemp(ac.getTemp() + 1);
  EXPECT_EQ(
      "Power: On, Mode: 3 (Cool), Temp: 17C, Fan: 1 (Min), "
      "Button: 68 (Temp Up), Swing(V) Toggle: Off",
      ac.toString());
  ac.setTemp(ac.getTemp() - 1);
  EXPECT_EQ(
      "Power: On, Mode: 3 (Cool), Temp: 16C, Fan: 1 (Min), "
      "Button: 67 (Temp Down), Swing(V) Toggle: Off",
      ac.toString());
}

TEST(TestIRHitachiAc424Class, toCommon) {
  IRHitachiAc424 ac(kGpioUnused);
  ac.setPower(true);
  ac.setMode(kHitachiAc424Cool);
  ac.setTemp(20);
  ac.setFan(kHitachiAc424FanMax);
  // Now test it.
  ASSERT_EQ(decode_type_t::HITACHI_AC424, ac.toCommon().protocol);
  ASSERT_EQ(-1, ac.toCommon().model);
  ASSERT_TRUE(ac.toCommon().power);
  ASSERT_TRUE(ac.toCommon().celsius);
  ASSERT_EQ(20, ac.toCommon().degrees);
  ASSERT_EQ(stdAc::opmode_t::kCool, ac.toCommon().mode);
  ASSERT_EQ(stdAc::fanspeed_t::kMax, ac.toCommon().fanspeed);
  // Unsupported.
  ASSERT_EQ(


#!/usr/bin/env python3
"""
Basic Flask app module
"""

from flask_babel import Babel
from flask import Flask, render_template, request

class Config:
    """
    Class representing a Flask Babel configuration.

    Attributes:
        LANGUAGES (list): List of supported languages.
        BABEL_DEFAULT_LOCALE (str): Default locale for translations.
        BABEL_DEFAULT_TIMEZONE (str): Default timezone for translations.
    """
    LANGUAGES = ["en", "fr"]
    BABEL_DEFAULT_LOCALE = "en"
    BABEL_DEFAULT_TIMEZONE = "UTC"

app = Flask(__name__)
app.config.from_object(Config)
app.url_map.strict_slashes = False
babel = Babel(app)

@babel.localeselector
def get_locale() -> str:
    """
    Function that retrieves the locale for a web page.

    Returns:
        str: The locale for the web page.
    """
    return request.accept_languages.best_match(app.config["LANGUAGES"])

@app.route('/')
def get_index() -> str:
    """
    Home/index page function

    Returns:
        str: The rendered template for the index page.
    """
    return render_template('2-index.html')

if __name__ == '__main__':
    app.run()


Write   (ref Writer writer, sbyte? slot)            => writer.format.AppendInt(ref writer.bytes, (sbyte)slot);
        public override void        WriteVar(ref Writer writer, in Var value)           => Write(ref writer, value.SInt8Null);
        public override DiffType    DiffVar (Differ differ, in Var left, in Var right)  => Diff(differ, left.SInt8Null, right.SInt8Null);
        public override DiffType    Diff    (Differ differ, sbyte? left, sbyte? right)  => left == right ? Equal : differ.AddNotEqual(new Var(left), new Var(right));
        public override Var         ToVar   (sbyte? value)


);
    expect(me.hash(null), null.hashCode);
  });
}

/// Wrapper objects for an `id` value.
///
/// Compares the `id` value by equality and for comparison.
/// Allows creating simple objects that are equal without being identical.
class Element implements Comparable<Element> {
  final Comparable id;
  const Element(this.id);
  @override
  int get hashCode => id.hashCode;
  @override
  bool operator ==(Object other) => other is Element && id == other.id;
  @override
  int compareTo(Element other) => id.compareTo(other.id);
}
// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:collection';

import 'utils.dart';

/// A priority queue is a priority based work-list of elements.
///
/// The queue allows adding elements, and removing them again in priority order.
/// The same object can be added to the queue more than once.
/// There is no specified ordering for objects with the same priority
/// (where the `comparison` function returns zero).
///
/// Operations which care about object equality, [contains] and [remove],
/// use [Object.==] for testing equality.
/// In most situations this will be the same as identity ([identical]),
/// but there are types, like [String], where users can reasonably expect
/// distinct objects to represent the same value.
/// If elements override [Object.==], the `comparison` function must
/// always give equal objects the same priority,
/// otherwise [contains] or [remove] might not work correctly.
abstract class PriorityQueue<E> {
  /// Creates an empty [PriorityQueue].
  ///
  /// The created [PriorityQueue] is a plain [HeapPriorityQueue].
  ///
  /// The [comparison] is a [Comparator] used to compare the priority of
  /// elements. An element that compares as less than another element has
  /// a higher priority.
  ///
  /// If [comparison] is omitted, it defaults to [Comparable.compare]. If this
  /// is the case, `E` must implement [Comparable], and this is checked at
  /// runtime for every comparison.
  factory PriorityQueue([int Function(E, E)? comparison]) =
      HeapPriorityQueue<E>;

  /// Number of elements in the queue.
  int get length;

  /// Whether the queue is empty.
  bool get isEmpty;

  /// Whether the queue has any elements.
  bool get isNotEmpty;

  /// Checks if [object] is in the queue.
  ///
  /// Returns true if the element is found.
  ///
  /// Uses the [Object.==] of elements in the queue to check
  /// for whether they are equal to [object].
  /// Equal objects objects must have the same priority
  /// according to the comparison function.
  /// That is, if `a == b` then `comparison(a, b) == 0`.
  /// If that is not the case, this check might fail to find
  /// an object.
  bool contains(E object);

  /// Provides efficient access to all the elements currently in the queue.
  ///
  /// The operation should be performed without copying or moving
  /// the elements, if at all possible.
  ///
  /// The elements are iterated in no particular order.
  /// The order is stable as long as the queue is not modified.
  /// The queue must not be modified during an iteration.
  Iterable<E> get unorderedElements;

  /// Adds element to the queue.
  ///
  /// The element will become the next to be removed by [


#pragma once
typedef void *FILE;

int printf(const char * restrictformat, ... );


/*	$NetBSD: sigcode.S,v 1.5 2004/03/26 14:11:01 drochner Exp $	*/

/*	$OpenBSD: locore.S,v 1.46 2001/09/20 18:33:03 mickey Exp $	*/

/*
 * Copyright (c) 1998-2001 Michael Shalayeff
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Michael Shalayeff.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR OR HIS RELATIVES 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 MIND, 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.
 *
 * Portitions of this file are derived from other sources, see
 * the copyrights and acknowledgements below.
 */
/*
 * Copyright (c) 1990,1991,1992,1994 The University of Utah and
 * the Computer Systems Laboratory (CSL).  All rights reserved.
 *
 * THE UNIVERSITY OF UTAH AND CSL PROVIDE THIS SOFTWARE IN ITS "AS IS"
 * CONDITION, AND DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES
 * WHATSOEVER RESULTING FROM ITS USE.
 *
 * CSL requests users of this software to return to csl-dist@cs.utah.edu any
 * improvements that they make and grant CSL redistri


64 PfsDirectory::preadv(const Libraries::Kernel::OrbisKernelIovec* iov, s32 iovcnt, s64 offset) {
    const u64 old_dirent_index = dirents_index;
    dirents_index = 0;
    s64 data_to_skip = offset;
    // If offset is part-way through one dirent, that dirent is skipped.
    while (data_to_skip > 0) {
        const auto dirent = dirents[dirents_index++];
        data_to_skip -= dirent.d_reclen;
        if (dirents_index == dirents.size()) {
            // We've reached the end of the dirents, nothing more can be skipped.
            break;
        }
    }

    const s64 bytes_read = readv(iov, iovcnt);
    dirents_index = old_dirent_index;
    return bytes_read;
}

s64 PfsDirectory::lseek(s64 offset, s32 whence) {
    switch (whence) {
    // Seek start
    case 0: {
        dirents_index = 0;
    }
    case 1: {
        // There aren't any dirents left to pass through.
        if (dirents_index >= dirents.size()) {
            dirents_index = dirents_index + offset;
            break;
        }
        s64 data_to_skip = offset;
        while (data_to_skip > 0) {
            const auto dirent = dirents[dirents_index++];
            data_to_skip -= dirent.d_reclen;
            if (dirents_index == dirents.size()) {
                // We've passed through all file dirents.
                // Set dirents_index to directory_size + remaining_offset instead.
                dirents_index = directory_content_size + data_to_skip;
                break;
            }
        }
        break;
    }
    case 2: {
        // Seems like real hardware gives up on tracking dirents_index if you go this route.
        dirents_index = directory_size + offset;
        break;
    }
    default: {
        UNREACHABLE_MSG("lseek with unknown whence {}", whence);
    }
    }

    return dirents_index;
}

s32 PfsDirectory::fstat(Libraries::Kernel::OrbisKernelStat* stat) {
    stat->st_mode = 0000777u | 0040000u;
    stat->st_size = directory_size;
    stat->st_blksize = 0x10000;
    stat->st_blocks = 0x80;
    return ORBIS_OK;
}

s64 PfsDirectory::getdents(void* buf, u64 nbytes, s64* basep) {
    // basep is set at the start of the function.
    if (basep != nullptr) {
        *basep = dirents_index;
    }

    if (dirents_index >= dirents.size()) {
        if (dirents_index < directory_content_size) {
            // We need to find the appropriate dirents_index to start from.
            s64 data_to_skip = dirents_index;
            u64 corrected_index = 0;
            while (data_to_skip > 0) {
                const auto dirent = dirents[corrected_index++];
                data_to_skip -= dirent.d_reclen;
            }
            dirents_index = corrected_index;
        } else {
            // Nothing left to read.
            return ORBIS_OK;
        }
    }

    s64 bytes_remaining = nbytes > directory_size ? directory_size : nbytes;
    memset(buf, 0, bytes_remaining);

    u64 bytes_written = 0;
    char* current_dirent = static_cast<char*>(buf);
    // getdents has to convert pfs dirents to normal dirents
    PfsDirectoryDirent dirent = dirents[di


  ; start MFMA loop, 16x16 wave tile with 2x2 repeat, 1x1 step, k_pack:16
    s_waitcnt vmcnt(4)
    ds_write_b128 v[v_sst_b_os], v[v_gld_b+0:v_gld_b+0+3]
    ds_write_b128 v[v_sst_b_os], v[v_gld_b+4:v_gld_b+4+3] offset:256
    ds_write_b128 v[v_sst_b_os], v[v_gld_b+8:v_gld_b+8+3] offset:512
    ds_write_b128 v[v_sst_b_os], v[v_gld_b+12:v_gld_b+12+3] offset:768

    s_waitcnt vmcnt(0)
    ds_write_b128 v[v_sst_a_os], v[v_gld_a+0:v_gld_a+0+3]
    ds_write_b128 v[v_sst_a_os], v[v_gld_a+4:v_gld_a+4+3] offset:256
    ds_write_b128 v[v_sst_a_os], v[v_gld_a+8:v_gld_a+8+3] offset:512
    ds_write_b128 v[v_sst_a_os], v[v_gld_a+12:v_gld_a+12+3] offset:768

    .v_clear_nc a_c, 16
    ; make sure acc WAR harzard, at least 1 nop for src_c
    s_sub_i32 s[s_kitr], s[s_knum], 256
    s_cmp_gt_i32 s[s_kitr], 0
    s_cbranch_scc0 L_igemm_fwd_gtcx35_nhwc_int8_bx0_ex0_bt64x64x256_wt16x16x64_ws1x1_wr2x2_ta1x16x4x1_1x16x1x16_tb1x16x4x1_1x16x1x16_mfma_end

    s_add_u32 s[s_in_offset],  s[s_move_slice_k_stride_c], s[s_in_offset]
    v_add_u32 v[v_wei_os], s[s_move_slice_k_stride_c], v[v_wei_os]

    s_waitcnt lgkmcnt(0)
    s_barrier
    ds_read_b128 v[v_a:v_a+3], v[v_sld_a_os] offset:0
    ds_read_b128 v[v_b:v_b+3], v[v_sld_b_os] offset:0
    ds_read_b128 v[v_b+4:v_b+4+3], v[v_sld_b_os] offset:512
    ds_read_b128 v[v_a+4:v_a+4+3], v[v_sld_a_os] offset:512
L_igemm_fwd_gtcx35_nhwc_int8_bx0_ex0_bt64x64x256_wt16x16x64_ws1x1_wr2x2_ta1x16x4x1_1x16x1x16_tb1x16x4x1_1x16x1x16_mfma_body:
    ; do fma accumulate with unroll 256
    s_waitcnt lgkmcnt(2)
    v_mfma_i32_16x16x64i8 v[a_c+0:a_c+3], v[v_a+0:v_a+3], v[v_b+0:v_b+3], v[a_c+0:a_c+3]     ; repeat:0x0, step:0x0, num_a_c:4
    v_cmpx_le_u32


 windows.")
}

/// Get all children of a specific process.
/// The Vec<i32> is just a placeholder.
pub fn get_children(_pid: i32) -> Option<Vec<i32>> {
    None
}

/// Send a signal to multiple processes.
/// The Vec<i32> is just a placeholder.
pub fn send_signal_to_processes(_processes: Vec<i32>, _action: &ProcessAction) {}
mod var_idx_vec;
mod lit_idx_vec;
mod var_heap;

// re-export everything
pub use self::var_idx_vec::VarIdxVec;
pub use self::lit_idx_vec::LitIdxVec;
pub use self::var_heap::VarHeap;<reponame>ecatlabs/renote
pub(crate) mod note;
pub(crate) mod repo;
<reponame>kiwiyou/solvedacbot
use db::ProfileImages;
use serde_json::Value;
use std::result::Result;
use telbot_cf_worker::types::markup::ParseMode;
use telbot_cf_worker::types::message::{Message, MessageKind, SendMessage};
use telbot_cf_worker::types::query::AnswerInlineQuery;
use telbot_cf_worker::types::update::*;
use telbot_cf_worker::Api;
use worker::js_sys::{Number, RegExp};
use worker::*;

use crate::command::Command;
use crate::db::RatingAlarms;

mod command;
mod db;
mod formatter;
mod solved;
mod utils;

fn log_request(req: &Request) {
    console_log!(
        "{} - [{}], located at: {:?}, within: {}",
        Date::now().to_string(),
        req.path(),
        req.cf().coordinates().unwrap_or_default(),
        req.cf().region().unwrap_or_else(|| "unknown region".into())
    );
}

#[event(fetch)]
pub async fn main(req: Request, env: Env) -> worker::Result<Response> {
    log_request(&req);
    utils::set_panic_hook();
    let token = env.secret("BOT_TOKEN")?.to_string();
    let api = telbot_cf_worker::Api::new(&token);
    let router = Router::with_data(api);
    let bot_endpoint = format!("/{}", token);
    let rating_endpoint = format!("/rating/{}", token);
    router
        .post_async(&bot_endpoint, |req, ctx| async {
            if let Err(e) = handle_request(req, ctx).await {
                web_sys::console::error_1(&e.to_string().into());
            }
            Response::empty()
        })
        .get_async(&rating_endpoint, |_, ctx| async move {
            let ratings = RatingAlarms::setup(ctx.kv("RATING_ALARMS")?);
            for subscriber in ratings.all_subscribers().await? {
                if let Some(rating) = ratings.get_subscription(subscriber).await? {
                    if let Some(user_info) = solved::user_show(&rating.target).await? {
                        let new_rating = user_info.get("rating").unwrap().as_u64().unwrap();
                        if rating.rating != new_rating {
                            ctx.data()
                                .send_json(&formatter::rating_update_to_message(
                                    subscriber,
                                    &rating.target,
                                    rating.rating,
                                    user_info,
                                ))
                                .await
                                .map_err(convert_error)?;
                            ratings
                                .set_subscription(subscriber, rating.target, new_rating)
                                .await?;
                        }
                    }
                }
            }
            Response::empty()
        })
        .run(req, env)
        .await
}

async fn handle_request(mut req: Request, ctx: RouteContext<Api>) -> worker::Result<()> {
    let update = req.json::<Update>().await?;
    match update.kind {
        UpdateKind::InlineQuery { inline_query } => {
            let (page, parity) = match inline_query.offset.parse::<u32>() {
                Ok(page) if page > 0 => ((page + 1) / 2, (page + 1) % 2),


 => props.theme.scope[key];

const hideable = props => `
  transition: opacity .5s ${props.theme.scope.baseEase};
`;

const palable = props => `
  transition: all .2s ${props.theme.scope.baseEase};
`;

const blinkable = props => `
  animation: blinking 1.5s infinite ${props.theme.scope.baseEase};
`;

const colorable = props => `
  transition: background-color .3s ${props.theme.scope.baseEase};
`;

/* add this class to truncate text with ellipsis, container needs width */
const truncate = () => `
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const shadow2 = props => `
  box-shadow: 0 3px 10px ${transparentize(0.84, props.theme.colors.black)}, 0 3px 10px ${transparentize(0.77, props.theme.colors.black)};
`;

const btnOpacity = props => `
  ${palable(props)};
  opacity: ${props.theme.scope.btnOpacityDefault};
  &-selected {
    opacity: ${props.theme.scope.btnOpacitySelected};
  }
  &[disabled] {
    cursor: default;
    opacity: ${props.theme.scope.btnOpacityDisabled};
  }
  &:not([disabled]):hover {
    opacity: ${props.theme.scope.btnOpacityHover};
  }
`;

/* From https://stackoverflow.com/a/18294634 */
const fullyPannable = () => `
  width: 100%;
  height: 100%;
  /* stylelint-disable value-no-vendor-prefix */
  /* Grabbable */
  cursor: move; /* fallback if grab cursor is unsupported */
  cursor: grab;
  cursor: -moz-grab;
  cursor: -webkit-grab;

  &.panning {
    /* Grabbing */
    cursor: grabbing;
    cursor: -moz-grabbing;
    cursor: -webkit-grabbing;
  }
  /* stylelint-enable value-no-vendor-prefix */
`;

const overlayWrapper = props => `
  align-items: center;
  background-color: ${transparentize(0.1, props.theme.colors.purple25)};
  border-radius: ${props.theme.borderRadius.soft};
  color: ${props.theme.scope.textTertiaryColor};
  display: flex;
  font-size: ${props.theme.fontSizes.tiny};
  justify-content: center;
  padding: 5px;
  position: fixed;
  bottom: 11px;

  button {
    ${btnOpacity(props)};
    background-color: transparent;
    border: 1px solid transparent;
    border-radius: ${props.theme.borderRadius.soft};
    color: ${props.theme.scope.textSecondaryColor};
    cursor: pointer;
    line-height: 20px;
    padding: 1px 3px;
    outline: 0;

    i {
      font-size: ${props.theme.fontSizes.small};
      position: relative;
      top: 2px;
    }

    &:hover, &.selected {
      border: 1px solid ${props.theme.scope.textTertiaryColor};
    }

    &.active {
      & > * { ${blinkable(props)}; }
      border: 1px solid ${props.theme.scope.textTertiaryColor};
    }
  }
`;

const GlobalStyle = createGlobalStyle`
  /*
  * Contain all the styles in the root div instead of having them truly
  * global, so that they don't interfere with the app they're injected into.
  */
  .scope-app, .terminal-app {

    /* Extendable classes */
    .hideable { ${hideable}; }
    .palable { ${palable}; }
    .blinkable { ${blinkable}; }
    .colorable { ${colorable}; }
    .truncate { ${truncate


   = 269,
    CIRDAS_CAVERNS                  = 270,
    CIRDAS_CAVERNS_U                = 271,
    DHO_GATES                       = 272,
    WOH_GATES                       = 273,
    OUTER_RAKAZNAR                  = 274,
    OUTER_RAKAZNAR_U                = 275,
    RAKAZNAR_INNER_COURT            = 276,
    RAKAZNAR_TURRIS                 = 277,
    WALK_OF_ECHOES_P2               = 279,
    MOG_GARDEN                      = 280,
    LEAFALLIA                       = 281,
    MOUNT_KAMIHR                    = 282,
    SILVER_KNIFE                    = 283,
    CELENNIA_MEMORIAL_LIBRARY       = 284,
    FERETORY                        = 285,
    MAQUETTE_ABDHALJS_LEGION_B      = 287,
    ESCHA_ZITAH                     = 288,
    ESCHA_RUAUN                     = 289,
    DESUETIA_EMPYREAL_PARADOX       = 290,
    REISENJIMA                      = 291,
    REISENJIMA_HENGE                = 292,
    REISENJIMA_SANCTORIUM           = 293,
    DYNAMIS_SAN_DORIA_D             = 294,
    DYNAMIS_BASTOK_D                = 295,
    DYNAMIS_WINDURST_D              = 296,
    DYNAMIS_JEUNO_D                 = 297,
    WALK_OF_ECHOES_P1               = 298,

    -- Increment this when adding new zones
    MAX_ZONE                        = 299
}

tpz.expansionRegion = tpz.expansionRegion or {}
tpz.expansionRegion.ORIGINAL_ROTZ =
{
    [tpz.region.RONFAURE]        = true,
    [tpz.region.ZULKHEIM]        = true,
    [tpz.region.NORVALLEN]       = true,
    [tpz.region.GUSTABERG]       = true,
    [tpz.region.DERFLAND]        = true,
    [tpz.region.SARUTABARUTA]    = true,
    [tpz.region.KOLSHUSHU]       = true,
    [tpz.region.ARAGONEU]        = true,
    [tpz.region.FAUREGANDI]      = true,
    [tpz.region.VALDEAUNIA]      = true,
    [tpz.region.QUFIMISLAND]     = true,
    [tpz.region.LITELOR]         = true,
    [tpz.region.KUZOTZ]          = true,
    [tpz.region.VOLLBOW]         = true,
    [tpz.region.ELSHIMOLOWLANDS] = true,
    [tpz.region.ELSHIMOUPLANDS]  = true,
    [tpz.region.SANDORIA]        = true,
    [tpz.region.BASTOK]          = true,
    [tpz.region.WINDURST]        = true,
    [tpz.region.JEUNO]           = true,
    [tpz.region.DYNAMIS]         = true
}

-----------------------------------
-- SetExplorerMoogles
----------------------------------

function SetExplorerMoogles(moogle)
    if EXPLORER_MOOGLE_LV ~= 0 then
        local npc = GetNPCByID(moogle)
        if npc == nil then
            printf("'SetExplorerMoogles' Error trying to load undefined npc (%d)", moogle)
        else
            npc:setStatus(0)
        end
    end
end


                    tessellator.draw();
                }
            }
        }
        GlStateManager.popMatrix();
    }
}
package gregtech.client.renderer.texture.cube;

import gregtech.api.GTValues;
import gregtech.client.renderer.ICubeRenderer;
import gregtech.client.renderer.texture.Textures;

import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;

import codechicken.lib.render.CCRenderState;
import codechicken.lib.render.pipeline.IVertexOperation;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Matrix4;

public class SimpleCubeRenderer implements ICubeRenderer {

    protected final String basePath;

    protected TextureAtlasSprite sprite;

    public SimpleCubeRenderer(String basePath) {
        this.basePath = basePath;
        Textures.CUBE_RENDERER_REGISTRY.put(basePath, this);
        Textures.iconRegisters.add(this);
    }

    @Override
    public void registerIcons(TextureMap textureMap) {
        String modID = GTValues.MODID;
        String basePath = this.basePath;
        String[] split = this.basePath.split(":");
        if (split.length == 2) {
            modID = split[0];
            basePath = split[1];
        }
        sprite = textureMap.registerSprite(new ResourceLocation(modID, basePath));
    }

    @Override
    public TextureAtlasSprite getParticleSprite() {
        return sprite;
    }

    @Override
    public void renderOrientedState(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline,
                                    Cuboid6 bounds, EnumFacing frontFacing, boolean isActive,
                                    boolean isWorkingEnabled) {
        Textures.renderFace(renderState, translation, pipeline, frontFacing, bounds, sprite,
                BlockRenderLayer.CUTOUT_MIPPED);
    }
}
package gregtech.client.shader.postprocessing;

import gregtech.client.shader.PingPongBuffer;
import gregtech.client.shader.Shaders;
import gregtech.client.utils.RenderUtil;
import gregtech.common.ConfigHolder;

import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.shader.Framebuffer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;

@SideOnly(Side.CLIENT)
public class BloomEffect {

    private static Framebuffer[] downSampleFBO;
    private static Framebuffer[] upSampleFBO;

    public static float strength = (float) ConfigHolder.client.shader.strength;
    public static float baseBrightness = (float) ConfigHolder.client.shader.baseBrightness;
    public static float highBrightnessThreshold = (float) ConfigHolder.client.shader.highBrightnessThreshold;
    public static float lowBrightnessThreshold = (float) ConfigHolder.client.shader.lowBrightnessThreshold;
    public static float step = (float) ConfigHolder.client.shader.step;

    private static void blend(Framebuffer bloom, Framebuffer backgroundFBO) {
        // bind main fbo
        GlStateManager.setActiveTexture(GL13.GL_TEXTURE0);
        GlStateManager.enableTexture2D();
        backgroundFBO.bindFramebufferTexture();

        // bind blur fbo
        GlStateManager.setActiveTexture(GL13.GL_TEXTURE1);
        GlStateManager.enableTex


|------|
| `attribute_demo.rs` | derive macroと属性の仕組み |
| `trait_use_demo.rs` | traitとC#拡張メソッドの類似性 |
| `prelude_explanation.rs` | Rustのimportシステム |
| `std_vs_crates.rs` | stdと一般クレートの違い |

## 🎯 設計思想：使い分けの指針

### ライブラリ開発 → thiserror
```rust
// 呼び出し元がパターンマッチできる構造化エラー
match database.find_user(id) {
    Ok(user) => process_user(user),
    Err(DatabaseError::NotFound { id }) => create_default_user(id),
    Err(DatabaseError::Connection { .. }) => retry_connection(),
    Err(e) => handle_other_error(e),
}
```

### アプリケーション開発 → anyhow
```rust
// コンテキスト豊富な統一エラー処理
fn main() -> anyhow::Result<()> {
    let config = load_config()
        .context("設定ファイルの読み込みに失敗")?;

    let data = fetch_data(&config.url)
        .context("データの取得に失敗")?;

    process_data(data)
        .context("データ処理中にエラー")?;

    Ok(())
}
```

### 組み合わせパターン
```rust
// ライブラリ境界での適切な変換
fn app_logic() -> anyhow::Result<()> {
    database::find_user("123")
        .map_err(|e| match e {
            DatabaseError::NotFound { id } => {
                anyhow::anyhow!("ユーザー {} が見つかりません", id)
            }
            _ => anyhow::Error::from(e),
        })?;
    Ok(())
}
```

## 🔍 学習の進め方

### 1. 基礎理解（30分）
1. `basic_thiserror.rs` → thiserrorの基本を把握
2. `basic_anyhow.rs` → anyhowの基本を把握
3. 2つの違いを理解

### 2. 実践パターン（1時間）
1. `library_errors.rs` → ライブラリ設計パターン
2. `application_errors.rs` → アプリケーション処理パターン
3. `mixed_usage.rs` → 両方の組み合わせ

### 3. 高度な活用（1時間）
1. `error_patterns.rs` → 高度なエラー処理パターン
2. `hidden_features.rs` → anyhowの隠し機能
3. 実際のプロジェクトでの応用

### 4. Rust理解の深化（補足）
1. `attribute_demo.rs` → procedural macroの理解
2. `trait_use_demo.rs` → traitシステムの理解
3. `prelude_explanation.rs` → importシステムの理解

## 🛠 高度な機能

### anyhowの隠された機能
```bash
# バックトレース付きでエラー確認
RUST_LIB_BACKTRACE=1 cargo run --example hidden_features
```

- `error.chain()` - エラーチェーンの走査
- `error.root_cause()` - 最終的な原因の取得
- `error.is::<T>()` - 特定エラー型の検査
- `ensure!` - 条件チェック付きのbail!

### thiserrorの活用パターン
- 階層的エラー設計（メイン型→詳細型）
- `From`トレイトによる自動変換
- エラーチェーンの構築
- 透過的エラー（`#[error(transparent)]`）

## 📖 詳細な学習ノート

プロジェクトの詳細な学習ノートは [`notes.md`](./notes.md) をご覧ください。以下の内容が含まれています：

- **なぜthiserrorとanyhowが必要なのか？**
- **実践的な使い分けパターン**
- **よくある質問と回答**
- **隠された便利機能**
- **補足：Rustのimportシステムとprelud


#!/usr/bin/python

import sys, os;

f = open("network", "w");

numCores = 32;
l1iPrefix = "l1i-";
l1dPrefix = "l1d-";
l2Prefix = "l2-";
l3Prefix = "l3-0b";
xDim = 6;
yDim = 6;
linkLat = 0;
routerLat = 2;
totalLat = linkLat + routerLat;

# 32-core 6x6 mesh with 4 memory controllers, each handling 2 channels

# . . x . . .
# .         .
# .         x
# x         .
# .         .
# . . . x . .

channelsPerController = 2;
memControllers=[[2, 0],
                [5, 2],
                [0, 3],
                [3, 5]];

added = [];

# Generate core mapping. Mesh stops without memory controllers contain a core.

cores = [];

x = 0;
y = 0;
for i in range(xDim*yDim):
    isMem = False;
    for c in range(len(memControllers)):
        if(x == memControllers[c][0] and y == memControllers[c][1]):
            isMem = True;
    if(not isMem):
        cores.append([x, y]);

    x = x + 1;
    if(x == xDim):
        x = 0;
        y = y + 1;

print(cores);
print(len(cores));

# Write header
f.write(str(xDim)+" "+str(yDim)+" "+str(totalLat)+"\n");

# Write all possible point-to-point interconnect mappings
for i in range(numCores):
    l1i = l1iPrefix+str(i);
    l1d = l1dPrefix+str(i);
    l2 = l2Prefix+str(i);
    l3 = l3Prefix+str(i);
    mem = "mem";
    dist = 0; # latency is already measured in cache
    print "Connecting "+l1i+" to "+l2;
    f.write(l1i+" "+l2+" "+"0 0\n");

    print "Connecting "+l1d+" to "+l2;
    f.write(l1d+" "+l2+" "+"0 0\n");

    # Calculate min distance from L3 bank to mesh edge
    l3x = cores[i][0];
    l3y = cores[i][1];

    channel = 0;
    for mc in memControllers:
        dist = abs(l3x - mc[0])+abs(l3y - mc[1]);
        for c in range(channelsPerController):
            print "Connecting "+l3+" to mem-"+str(channel)+", dist "+str(dist);
            f.write(l3+" mem-"+str(channel)+" 1 "+str(l3x)+" "+str(l3y)+" "+str(mc[0])+" "+str(mc[1])+"\n");
            channel = channel + 1;

    for j in range(numCores):
        l2 = l2Prefix+str(i);
        l3 = l3Prefix+str(j);
        l2x = cores[i][0];
        l2y = cores[i][1];
        l3x = cores[j][0];
        l3y = cores[j][1];
        dist = abs(l2x - l3x)+abs(l2y-l3y);
        lat = dist*(linkLat+routerLat);
        print "Connecting "+l2+" ("+str(l2x)+", "+str(l2y)+") to "+l3+" ("+str(l3x)+", "+str(l3y)+") = "+str(dist)+", "+str(lat)+" cycles";

        if((added.count(l2+l3) == 0) and (added.count(l3+l2) == 0)):
            added.append(l2+l3);
            added.append(l3+l2);
            f.write(l2+" "+l3+" 1 "+str(l2x)+" "+str(l2y)+" "+str(l3x)+" "+str(l3y)+"\n");
        else:
            print "ERROR";
            sys.exit();


counter)

    const counterBuffer = numberToBuffer(counter)

    const hash = crypto
      .createHmac(hmacAlgorithm, secret)
      .update(counterBuffer)
      .digest()

    const truncated = truncate(hash)

    const hotp = truncated % Math.pow(10, digits)

    return String(hotp).padStart(digits, '0')
  }

  const verify = (input: string, counter: number = 0) =>
    areOtpEqual(generate(counter), input)

  const uri = ({
    label,
    issuer
  }: Pick<GenerateHotpUriParameters, 'label' | 'issuer'>) =>
    generateUri({
      type: 'hotp',
      secret: base32Encode(secret),
      label,
      issuer,
      hmacAlgorithm,
      digits,
      initialCounter: 0
    })

  return {
    generate,
    verify,
    uri
  }
}
var require : any;
const fs = require('fs');
const rxjs = require('rxjs');
const mergeMap = require('rxjs/operators').mergeMap;
const map = require('rxjs/operators').map;

const arregloRespuestaTypes = [];
const arregloRespuestaAbilities = [];
const arregloRespuestaMove = [];
const arregloRespuestaXTypes = [];
const arregloRespuestaXAbilities = [];
const arregloRespuestaXMoves = [];

function inicialiarBDD() {
    return new Promise(
        (resolve, reject) => {
            fs.readFile(
                'data.json',
                'utf-8',
                (error, contenidoArchivo) => { // CALLBACK
                    if (error) {
                        reject({
                            mensaje: 'esta mal leido'
                        })
                    } else {
                        resolve({
                            mensaje: 'BDD leida',
                            bdd: JSON.parse(contenidoArchivo)
                        })
                    }
                }
            )
        }
    )
};

// 1) Busque los tipos de "types" en el arreglo data.json
// 2) Busque los tipos de "abilities" en el arreglo data.json
// 3) Busque los tipos de "move" en el arreglo data.json
// 4) Clasifique a los pokemon por types
// 5) Clasifique a los pokemon por abilities
async function main() {
    const inicializarBDD$ = rxjs.from(inicialiarBDD());
    inicializarBDD$
        .subscribe(res => {

            res.bdd.forEach(element => {
                element.types.forEach(tipo => {
                    const respuestaTypes = {
                        tipo: tipo.type.name
                    }
                    arregloRespuestaTypes.push(respuestaTypes)

                })
            });

            res.bdd.forEach(element => {
                element.abilities.forEach(habilidad => {
                    const respuestaAbilities = {
                        habilidad: habilidad.ability.name
                    }
                    arregloRespuestaAbilities.push(respuestaAbilities)

                })
            });

            res.bdd.forEach(element => {
                element.moves.forEach(movimiento => {
                    const respuestaMove = {
                        movimiento: movimiento.move.name
                    }
                    arregloRespuestaMove.push(respuestaMove)

                })
            });

            res.bdd.forEach(element => {
                element.types.forEach(tipo => {
                    const pokemonXTipo = {
                        nombre: tipo.type.name,
                        pokemons: [
                            {
                                id: element.id,
                                nombre: element.name
                            }
                        ]
                    }
                    arregloRespuestaXTypes.push(pokemonXTipo)
                })
            });

            res.bdd.forEach(element => {


FRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';
const common = require('../common');

const repl = require('repl');

const putIn = new common.ArrayStream();
repl.start('', putIn);

putIn.write = function(data) {
  // Don't use assert for this because the domain might catch it, and
  // give a false negative.  Don't throw, just print and exit.
  if (data === 'OK\n') {
    console.log('ok');
  } else {
    console.error(data);
    process.exit(1);
  }
};

putIn.run([
  'require("domain").create().on("error", function() { console.log("OK") })' +
  '.run(function() { throw new Error("threw") })'
]);
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';
const common = require('../common');
const assert = require('assert');

const zlib = require('zlib');
const gz = zlib.Gzip();
const emptyBuffer = Buffer.alloc(0);
let received = 0;
gz.on('data', function(c) {
  received += c.length;
});

gz.on('end', common.mustCall(function() {
  assert.strictEqual(received, 20);
}));
gz.on('finish', common.mustCall());
gz.write(emptyBuffer);
gz.end();
'use strict';

const common = require('../common');
const assert = require('assert');
const http = require('http');
const Countdown = require('../common/countdown');

function explicit(req, res) {
  assert.throws(() => {
    res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n');
  }, /Invalid character in statusMessage/);

  assert.throws(() => {
    res.writeHead(200, 'OK\u010D\u010AContent-Type: gotcha\r\n');
  }, /Invalid character in statusMessage/);

  res.statusMessage = 'OK';
  res.end();
}

function implicit(req, res) {
  assert.throws(() => {
    res.statusMessage = 'OK\r\nContent-Type: text/html\r\n';
    res.writeHead(200);
  }, /Invalid character in statusMessage/);
  res.statusMessage = 'OK';
  res.end();
}

const server = http.createServer((req, res) => {
  if (req.url === '/explicit') {
    explicit(req, res);
  } else {
    implicit(req, res);
  }
}).listen(0, common.mustCall(() => {
  const hostname = 'localhost';
  const countdown = new Countdown(2, () => server.close());
  const url = `http://${hostname}:${server.a


= 0:
            n = n / i;
            maximum_split+= 1

    # Condition to handle the case when n
    # is a prime number greater than 2
    if n > 2:
        maximum_split+= 1

    # check if maximum_split is less than K
    # then it not possible
    if maximum_split < k:
        print("No")
        return

    print("Yes")

# Driver code
N = 12
K = 3
KPrimeDivisors(N, K)
```

## C#

```
// C# implementation to Check if a
// number can be expressed as a
// product of exactly K prime divisors
using System;

class GFG {

    // function to find K prime divisors
    static void KPrimeDivisors(int N, int K)
    {
        int maximum_split = 0;

        // count number of 2s that divide N
        while (N % 2 == 0) {
            maximum_split++;
            N /= 2;
        }

        // N must be odd at this point.
        // So we can skip one element
        for (int i = 3; i * i <= N; i = i + 2) {

            while (N % i == 0) {

                // divide the value of N
                N = N / i;

                // increment count
                maximum_split++;
            }
        }

        // Condition to handle the case when n
        // is a prime number greater than 2
        if (N > 2)
            maximum_split++;

        // check if maximum_split is less than K
        // then it not possible
        if (maximum_split < K) {
            Console.WriteLine("No");
            return;
        }

        Console.WriteLine("Yes");
    }

    /* Driver code */
    public static void Main(String[] args)
    {
        // initialise N and K
        int N = 12;
        int K = 3;

        KPrimeDivisors(N, K);
    }
}

// This code is contributed by 29AjayKumar
```

## java 描述语言

```
<script>
// javascript implementation to Check if a
// number can be expressed as a
// product of exactly K prime divisors

// function to find K prime divisors
    function KPrimeDivisors(N , K)
    {
        var maximum_split = 0;

        // count number of 2s that divide N
        while (N % 2 == 0)
        {
            maximum_split++;
            N /= 2;
        }

        // N must be odd at this point.
        // So we can skip one element
        for (i = 3; i * i <= N; i = i + 2)
        {

            while (N % i == 0)
            {

                // divide the value of N
                N = N / i;

                // increment count
                maximum_split++;
            }
        }

        // Condition to handle the case when n
        // is a prime number greater than 2
        if (N > 2)
            maximum_split++;

        // check if maximum_split is less than K
        // then it not possible
        if (maximum_split < K)
        {
            document.write("No");
            return;
        }

        document.write("Yes");
    }

    /* Driver code */

        // initialise N and K
        var N =


using System.IO;
using System.Threading.Tasks;
using Filtration.Common.Services;
using Filtration.ObjectModel;
using Filtration.Parser.Interface.Services;
using Filtration.Services;
using Moq;
using NUnit.Framework;

namespace Filtration.Tests.Services
{
    [TestFixture]
    public class TestItemFilterPersistenceService
    {
        [Test]
        public async Task LoadItemFilterScript_CallsTranslatorAndFileSystemService()
        {
            // Arrange
            const string testInputPath = "C:\\Test Path\\Script.Filter";
            const string testScriptString = "This is a test item filter script";
            var testItemFilterScript = new ItemFilterScript();

            var mockFileSystemService = new Mock<IFileSystemService>();
            mockFileSystemService.Setup(s => s.ReadFileAsString(testInputPath)).Returns(testScriptString).Verifiable();

            var mockItemFilterScriptTranslator = new Mock<IItemFilterScriptTranslator>();
            mockItemFilterScriptTranslator.Setup(t => t.TranslateStringToItemFilterScript(testScriptString)).Returns(testItemFilterScript).Verifiable();

            var service = new ItemFilterPersistenceService(mockFileSystemService.Object, mockItemFilterScriptTranslator.Object);

            // Act
            var script = await service.LoadItemFilterScriptAsync(testInputPath);

            // Assert
            mockFileSystemService.Verify();
            mockItemFilterScriptTranslator.Verify();
            Assert.AreEqual(testItemFilterScript, script);
        }

        [Test]
        public async Task SaveItemFilterScript_CallsTranslatorAndFileSystemService()
        {
            // Arrange
            var testFilePath = "C:\\Test\\File.txt";
            var testScript = new ItemFilterScript {FilePath = testFilePath};
            var testTranslatedScript = "Test translated script";

            var mockFileSystemService = new Mock<IFileSystemService>();
            mockFileSystemService.Setup(s => s.WriteFileFromString(testFilePath, testTranslatedScript)).Verifiable();

            var mockItemFilterScriptTranslator = new Mock<IItemFilterScriptTranslator>();
            mockItemFilterScriptTranslator.Setup(t => t.TranslateItemFilterScriptToString(testScript)).Returns(testTranslatedScript).Verifiable();

            var service = new ItemFilterPersistenceService(mockFileSystemService.Object, mockItemFilterScriptTranslator.Object);

            // Act
            await service.SaveItemFilterScriptAsync(testScript);

            // Assert
            mockFileSystemService.


/* 00228 809A4888 00000000 */  nop
/* 0022C 809A488C 2728006F */  addiu   $t0, $t9, 0x006F           ## $t0 = 0000006F
/* 00230 809A4890 A608005C */  sh      $t0, 0x005C($s0)           ## 0000005C
/* 00234 809A4894 86290024 */  lh      $t1, 0x0024($s1)           ## 00000024
/* 00238 809A4898 44895000 */  mtc1    $t1, $f10                  ## $f10 = 0.00
/* 0023C 809A489C 0C00CFBE */  jal     Math_Rand_ZeroFloat

/* 00240 809A48A0 46805320 */  cvt.s.w $f12, $f10
/* 00244 809A48A4 4600040D */  trunc.w.s $f16, $f0
/* 00248 809A48A8 862E0024 */  lh      $t6, 0x0024($s1)           ## 00000024
/* 0024C 809A48AC 3C19809A */  lui     $t9, %hi(func_809A4BE8)    ## $t9 = 809A0000
/* 00250 809A48B0 3C08809A */  lui     $t0, %hi(func_809A4EC0)    ## $t0 = 809A0000
/* 00254 809A48B4 440D8000 */  mfc1    $t5, $f16
/* 00258 809A48B8 241800FF */  addiu   $t8, $zero, 0x00FF         ## $t8 = 000000FF
/* 0025C 809A48BC 27394BE8 */  addiu   $t9, $t9, %lo(func_809A4BE8) ## $t9 = 809A4BE8
/* 00260 809A48C0 25084EC0 */  addiu   $t0, $t0, %lo(func_809A4EC0) ## $t0 = 809A4EC0
/* 00264 809A48C4 01AE7821 */  addu    $t7, $t5, $t6
/* 00268 809A48C8 A60F0050 */  sh      $t7, 0x0050($s0)           ## 00000050
/* 0026C 809A48CC A6180040 */  sh      $t8, 0x0040($s0)           ## 00000040
/* 00270 809A48D0 AE190028 */  sw      $t9, 0x0028($s0)           ## 00000028
/* 00274 809A48D4 AE080024 */  sw      $t0, 0x0024($s0)           ## 00000024
/* 00278 809A48D8 92290026 */  lbu     $t1, 0x0026($s1)           ## 00000026
/* 0027C 809A48DC 3C048016 */  lui     $a0, 0x8016                ## $a0 = 80160000
/* 00280 809A48E0 3C02809A */  lui     $v0, %hi(D_809A5100)       ## $v0 = 809A0000
/* 00284 809A48E4 A6090048 */  sh      $t1, 0x0048($s0)           ## 00000048
/* 00288 809A48E8 922A0026 */  lbu     $t2, 0x0026($s1)           ## 00000026
/* 0028C 809A48EC 27AB0034 */  addiu   $t3, $sp, 0x0034           ## $t3 = FFFFFFDC
/* 00290 809A48F0 24846FA8 */  addiu   $a0, $a0, 0x6FA8           ## $a0 = 80166FA8
/* 00294 809A48F4 11400018 */  beq     $t2, $zero, .L809A4958
/* 00298 809A48F8 24425100 */  addiu   $v0


d {len(crop_sequence_bytes)} crops in request')

        # Convert bytes back to PIL Images for processing
        crop_sequence_pil = []
        for crop_bytes in crop_sequence_bytes:
            try:
                import io
                from PIL import Image
                crop_pil = Image.open(io.BytesIO(crop_bytes))
                crop_sequence_pil.append(crop_pil)
            except Exception as e:
                print(f'[Behavior][WARNING] Failed to convert crop bytes to PIL Image: {e}')
                continue

        print(f'[Behavior] Track {track_id}: Successfully converted {len(crop_sequence_pil)} crops to PIL Images')

        # Check if we have enough frames
        if len(crop_sequence_pil) < SEQUENCE_LENGTH:
            print(f'[Behavior][ERROR] Track {track_id}: Only {len(crop_sequence_pil)} frames, need {SEQUENCE_LENGTH}')
            raise RuntimeError(f"Track {track_id}: Only {len(crop_sequence_pil)} frames, need {SEQUENCE_LENGTH}")

        # Process the crop sequence directly
        try:
            label, confidence = classify_action_from_crop_sequence(crop_sequence_pil)
            print(f'[Behavior] Successfully classified track {track_id}: {label} ({confidence:.3f})')
            return pb2.BehaviorResult(track_id=track_id, label=str(label), confidence=float(confidence))
        except Exception as e:
            print(f'[Behavior][ERROR] Failed to classify track {track_id}: {e}')
            raise RuntimeError(f"Failed to classify track {track_id}: {e}")

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=4), options=GRPC_OPTIONS)
    pb2_grpc.add_BehaviorServiceServicer_to_server(BehaviorServicer(), server)
    server.add_insecure_port('[::]:50055')
    server.start()
    print('BehaviorService started on 50055')
    try:
        while True:
            time.sleep(60)
    except KeyboardInterrupt:
        server.stop(0)

if __name__=='__main__':
    serve()


lay:none}.badge{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #dee2e6!important}.table-dark{color:inherit}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#dee2e6}.table .thead-dark th{color:inherit;border-color:#dee2e6}}
/*# sourceMappingURL=bootstrap.min.css.map *//*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
 * General
 */

img { border: 0; }

#content table {
  border: 0;
  width: 100%;
}
/*Hack to get IE to render the table at 100%*/
* html #content table { margin-left: -3px; }

#content th,
#content td {
  margin: 0;
  padding: 0;
  vertical-align: top;
}

.clearboth {
  clear: both;
}

.note, .warning, .fixme {
  border: solid black 1px;
  margin: 1em 3em;
}

.note .label {
  background: #369;
  color: white;
  font-weight: bold;
  padding: 5px 10px;
}
.note .content {
  background: #F0F0FF;
  color: black;
  line-height: 120%;
  font-size: 90%;
  padding: 5px 10px;
}
.warning .label {
  background: #C00;
  color: white;
  font-weight: bold;
  padding: 5px 10px;
}
.warning .content {
  background: #FFF0F0;
  color: black;
  line-height: 120%;
  font-size: 90%;
  padding: 5px 10px;
}
.fixme .label {
  background: #C6C600;
  color: black;
  font-weight: bold;
  padding: 5px 10px;
}
.fixme .content {
  padding: 5px 10px;
}

/**
 * Typography
 */

body {
  font-family: verdana, "Trebuchet MS", arial, helvetica, sans-serif;
  font-size: 100%;
}

#content {
  font-family: Georgia, Palatino, Times, serif;
  font-size: 95%;
}
#tabs {
  font-size: 70%;
}
#menu {
  font-size: 80%;
}
#footer {
  font-size: 70%;
}

h1, h2, h3, h4, h5, h6 {
  font-family: "Trebuchet MS", verdana, arial, helvetica, sans-serif;
  font-weight: bold;
  margin-top: 1em;
  margin-bottom: .5em;
}

h1 {
    margin-top: 0;
    margin-bottom: 1em;
  font-size: 1.4em;
  background-color: 73CAFF
}
#content h1 {
  font-size: 160%;
  margin-bottom: .5em;
}
#menu h1 {
  margin: 0;
  padding: 10px;
  background: #336699;
  color: white;
}
h2 {


ofinsReais);
    }
    if (!nullToAbsent || valorCofins != null) {
      map['VALOR_COFINS'] = Variable<double?>(valorCofins);
    }
    return map;
  }

  NfeDetalheImpostoCofinssCompanion toCompanion(bool nullToAbsent) {
    return NfeDetalheImpostoCofinssCompanion(
      id: id == null && nullToAbsent ? const Value.absent() : Value(id),
      idNfeDetalhe: idNfeDetalhe == null && nullToAbsent
          ? const Value.absent()
          : Value(idNfeDetalhe),
      cstCofins: cstCofins == null && nullToAbsent
          ? const Value.absent()
          : Value(cstCofins),
      baseCalculoCofins: baseCalculoCofins == null && nullToAbsent
          ? const Value.absent()
          : Value(baseCalculoCofins),
      aliquotaCofinsPercentual: aliquotaCofinsPercentual == null && nullToAbsent
          ? const Value.absent()
          : Value(aliquotaCofinsPercentual),
      quantidadeVendida: quantidadeVendida == null && nullToAbsent
          ? const Value.absent()
          : Value(quantidadeVendida),
      aliquotaCofinsReais: aliquotaCofinsReais == null && nullToAbsent
          ? const Value.absent()
          : Value(aliquotaCofinsReais),
      valorCofins: valorCofins == null && nullToAbsent
          ? const Value.absent()
          : Value(valorCofins),
    );
  }

  factory NfeDetalheImpostoCofins.fromJson(Map<String, dynamic> json,
      {ValueSerializer? serializer}) {
    serializer ??= driftRuntimeOptions.defaultSerializer;
    return NfeDetalheImpostoCofins(
      id: serializer.fromJson<int?>(json['id']),
      idNfeDetalhe: serializer.fromJson<int?>(json['idNfeDetalhe']),
      cstCofins: serializer.fromJson<String?>(json['cstCofins']),
      baseCalculoCofins:
          serializer.fromJson<double?>(json['baseCalculoCofins']),
      aliquotaCofinsPercentual:
          serializer.fromJson<double?>(json['aliquotaCofinsPercentual']),
      quantidadeVendida:
          serializer.fromJson<double?>(json['quantidadeVendida']),
      aliquotaCofinsReais:
          serializer.fromJson<double?>(json['aliquotaCofinsReais']),
      valorCofins: serializer.fromJson<double?>(json['valorCofins']),
    );
  }
  @override
  Map<String, dynamic> toJson({ValueSerializer? serializer}) {
    serializer ??= driftRuntimeOptions.defaultSerializer;
    return <String, dynamic>{
      'id': serializer.toJson<int?>(id),
      'idNfeDetalhe': serializer.toJson<int?>(idNfeDetalhe),
      'cstCofins': serializer.toJson<String?>(cstCofins),
      'baseCalculoCofins': serializer.toJson<double?>(baseCalculoCofins),
      'aliquotaCofinsPercentual':
          serializer.toJson<double?>(aliquotaCofinsPercentual),
      'quantidadeVendida': serializer.toJson<double?>(quantidadeVendida),
      'aliquotaCofinsReais': serializer.toJson<double?>(aliquotaCofinsReais),
      'valorCofins': serializer.toJson<double?>(valorCofins),
    };
  }

  NfeDetalheImpostoCofins copyWith(
          {int?


) format("woff2"),url(https://fonts.gstatic.com/s/opensans/v18/mem5YaGs126MiZpBA-UN8rsOXOhv.woff) format("woff")}.header-logo{display:flex;flex-flow:row;align-items:center}@media (max-width: 960px){.header-logo{justify-content:center}}.header-logo__image{height:50px;width:auto;margin-right:13px}@media (min-width: 1920px){.header-logo__image{height:100%}}.header-logo__text{font-family:'Open Sans', sans-serif;font-size:30px;font-weight:600;font-stretch:normal;font-style:normal;line-height:0.6;letter-spacing:0.4px;text-align:left;color:#1a1a1a}@media (min-width: 1920px){.header-logo__text{font-size:40px}}

.vf-modal-transition[data-v-0f226802] {
  transition: all 0.6s ease;
}
.vf-modal-leave[data-v-0f226802] {
  border-radius: 1px !important;
}
.vf-modal-transition .vf-modal-dialog[data-v-0f226802],
.vf-modal-transition .vf-modal-backdrop[data-v-0f226802] {
  transition: all 0.5s ease;
}
.vf-modal-enter .vf-modal-dialog[data-v-0f226802],
.vf-modal-leave .vf-modal-dialog[data-v-0f226802] {
  opacity: 0;
  transform: translateY(-30%);
}
.vf-modal-enter .vf-modal-backdrop[data-v-0f226802],
.vf-modal-leave .vf-modal-backdrop[data-v-0f226802] {
  opacity: 0;
}

@font-face{font-family:"Open Sans";font-style:italic;font-weight:300;src:local("Open Sans Light Italic"),local(OpenSans-LightItalic),url(https://fonts.gstatic.com/s/opensans/v18/memnYaGs126MiZpBA-UFUKWyV9hlIqc.eot?#) format("eot"),url(https://fonts.gstatic.com/s/opensans/v18/memnYaGs126MiZpBA-UFUKWyV9hrIqM.woff2) format("woff2"),url(https://fonts.gstatic.com/s/opensans/v18/memnYaGs126MiZpBA-UFUKWyV9hlIqU.woff) format("woff")}@font-face{font-family:"Open Sans";font-style:italic;font-weight:400;src:local("Open Sans Italic"),local(OpenSans-Italic),url(https://fonts.gstatic.com/s/opensans/v18/mem6YaGs126MiZpBA-UFUK0Xdck.eot?#) format("eot"),url(https://fonts.gstatic.com/s/opensans/v18/mem6YaGs126MiZpBA-UFUK0Zdc0.woff2) format("woff2"),url(https://fonts.gstatic.com/s/opensans/v18/mem6YaGs126MiZpBA-UFUK0Xdcs.woff) format("woff")}@font-face{font-family:"Open Sans";font-style:italic;font-weight:600;src:local("Open Sans SemiBold Italic"),local(OpenSans-SemiBoldItalic),url(https://fonts.gstatic.com/s/opensans/v18/memnYaGs126MiZpBA-UFUKXGUdhlIqc.eot?#) format("eot"),url(https://fonts.gstatic.com


: () async => false, // 防止返回键关闭
        child: CustomAlertDialog(
          title: Row(
            children: [
              Icon(Icons.block, color: Colors.red, size: 24),
              SizedBox(width: 8),
              Text(translate('Account Expired')),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(translate('Your account has expired. You will be automatically logged out.')),
              SizedBox(height: 16),
              CircularProgressIndicator(),
              SizedBox(height: 8),
              Text('Logging out in 3 seconds...'),
            ],
          ),
        ),
      );
    },
  );
}

Future<void> showAccountDisabledDialog(BuildContext context) async {
  return showDialog<void>(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return CustomAlertDialog(
        title: Row(
          children: [
            Icon(Icons.block, color: Colors.red, size: 24),
            SizedBox(width: 8),
            Text(translate('Account Disabled')),
          ],
        ),
        content: Text(translate('Your account has been disabled. Please contact your administrator.')),
        actions: <Widget>[
          dialogButton(
            translate('OK'),
            onPressed: () {
              Navigator.of(context).pop();
              _forceLogoutDisabled();
            },
            isOutline: false,
          ),
        ],
      );
    },
  );
}

Color _getWarningColor(ExpiryLevel level) {
  switch (level) {
    case ExpiryLevel.critical:
      return Color(0xFFE74C3C); // 红色 - 紧急警告
    case ExpiryLevel.expired:
      return Color(0xFFC0392B); // 深红 - 已过期
    default:
      return Color(0xFFFF6B35); // 橙色 - 一般警告
  }
}

String _getExpiryMessage(ExpiryWarning warning) {
  switch (warning.level) {
    case ExpiryLevel.week:
    case ExpiryLevel.days:
      return translate('account_expires_in_days').replaceAll('{}', warning.time.toString());
    case ExpiryLevel.hours:
      return translate('account_expires_in_hours').replaceAll('{}', warning.time.toString());
    case ExpiryLevel.critical:
      return translate('account_expires_in_minutes').replaceAll('{}', warning.time.toString());
    default:
      return '';
  }
}

void _showContactAdminInfo(BuildContext context) {
  gFFI.dialogManager.show((setState, close, context) {
    return CustomAlertDialog(
      title: Text(translate('Contact Administrator')),
      content: Text(translate('Please contact your system administrator to renew your account access.')),
      actions: [
        dialogButton(translate('OK'), onPressed: close, isOutline: false),
      ],
    );
  });
}

void _forceLogoutExpired() {
  // 清理访问令牌和用户信息
  _clearUserSession();

  // 记录日志
  debugPrint("Account expired, user has been logged out automatically");

  // 显示退出后的状态
  _showLoggedOutExpiredStatus();
}

void _forceLogoutDisabled() {
  // 清理访问令牌和用户信息
  _clearUserSession();

  // 记录日志
  debugPrint("Account disabled, user has been logged out automatically");
}

void _clearUserSession() {
  // 清理用户会话数据
  bind.mainSetLocalOption(key: "access_token", value: "");
  bind.mainSetLocalOption(key: "user_info", value: "");
  gFFI.userModel.reset();
  gFFI.abModel.reset();
}

void _showLoggedOutExpiredStatus() {
  gFFI.dialogManager.show((setState, close, context) {
    return CustomAlertDialog(
      title: Text(translate('Account Expired')),
      content: Text(translate('Your account access has expired. Please contact your administrator to renew your account access.')),


The validation error rate of the fast architecture tested on KITTI 2012 but trained on
Middlebury is 3.156%.

\***

Prepare files for submission to the KITTI and Middlebury evaluation server.

	$ ./main.lua kitti fast -a submit -net_fname net/net_kitti_fast_-a_train_all.t7
	kitti fast -a submit -net_fname net/net_kitti_fast_-a_train_all.t7
	  adding: 000038_10.png (deflated 0%)
	  adding: 000124_10.png (deflated 0%)
	  ...
	  adding: 000021_10.png (deflated 0%)

The output is stored in `out/submission.zip` and can be used to submit to the
[KITTI evaluation
server](http://www.cvlibs.net/datasets/kitti/user_submit.php).

\***

Experiment with different network architectures:

	$ ./main.lua kitti slow -a train_tr -l1 2 -fm 128 -l2 3 -nh2 512
	kitti slow -a train_tr -l1 2 -fm 128 -l2 3 -nh2 512
	conv(in=1, out=128, k=3)
	cudnn.ReLU
	conv(in=128, out=128, k=3)
	cudnn.ReLU
	nn.Reshape(128x256)
	nn.Linear(256 -> 512)
	cudnn.ReLU
	nn.Linear(512 -> 512)
	cudnn.ReLU
	nn.Linear(512 -> 512)
	cudnn.ReLU
	nn.Linear(512 -> 1)
	cudnn.Sigmoid
	...

\***

Measure the runtime on a particular data set:

	$ ./main.lua kitti fast -a time
	kitti fast -a time
	conv(in=1, out=64, k=3)
	cudnn.ReLU
	conv(in=64, out=64, k=3)
	cudnn.ReLU
	conv(in=64, out=64, k=3)
	cudnn.ReLU
	conv(in=64, out=64, k=3)
	nn.Normalize2
	nn.StereoJoin1
	0.73469495773315

It take 0.73 seconds to run the fast architecure on the KITTI 2012 data set. If
you care only about the time spent in the neural network, you can terminate the
stereo method early:

	$ ./main.lua kitti fast -a time -sm_terminate cnn
	kitti fast -a time -sm_terminate cnn
	conv(in=1, out=64, k=3)
	cudnn.ReLU
	conv(in=64, out=64, k=3)
	cudnn.ReLU
	conv(in=64, out=64, k=3)
	cudnn.ReLU
	conv(in=64, out=64, k=3)
	nn.Normalize2
	nn.StereoJoin1
	0.31126594543457
# Visibility-aware Multi-view Stereo Network
## Introduction

![Intro](readme_media/method2.png)

This is the official implementation for the BMVC 2020 paper [Visibility-aware Multi-view Stereo Network](https://arxiv.org/abs/2008.07928). In this paper, we explicitly infer and integrate the pixel-wise occlusion information in the MVS network via the matching uncertainty estimation. The pair-wise uncertainty map is jointly inferred with the pair-wise depth map, which is further used as weighting guidance during the multi-view cost volume fusion. As such, the adverse influence of occluded pixels is suppressed in the cost fusion. The proposed framework Vis-MVSNet significantly improves depth accuracies in the scenes with severe occlusion.
## How to Use
### Environment Setup
The code is tested in the following environment. The newer version of the packages should also be fine.
```
python==3.7.6
apex==0.1                # only for sync


-1.197-.32-.307-.785-.915-.016-1.092 1.16-.266.131-1.596.202-2.279.032-.317.574-.791.747-1.076-.111-.011-.089-.404.044-.688-.173.224-.647.249-.664.107M21.55 43.878l.228.524.23-.524-.228-.524zm3.563-3.498-1.903 1.902 1.903.869zm.334 0v2.771l1.904-.869zm2.037 1.561v-3.934l-1.966 1.966zm-2.037-4.083v1.709l1.711-1.709z"/><path fill="currentColor" d="m8.611 38.268.213 1.145c.018.087.117.15.264.248.229.158.366.442.259.572a.812.812 0 00-.02-1.288 4.3 4.3 0 01.714-.328v3.11h2.295v-4.123c.673-.398 1.097-.767 1.017-.918l-.156-1.095a.15.15 0 00-.003-.019l.003.019c0-.015.008-.032.002-.046l-.013-.024c-.15-.122-.448-.22-.846-.28l-.004 1.104v-2.049l.016-.001c.955.032 1.781.181 2.289.38v1.812h-.002v.053h.802v6.762c.217.254.462.486.748.671V36.5h.832l.02 7.863c.233.076.477.127.729.156V36.5h.83v8.021a3.7 3.7 0 00.729-.153l.021-7.868h.102a2.72 2.72 0 00.729 1.841v5.637c.296-.192.548-.435.771-.7l-.014-4.409c.246.104.51.167.787.17v2.157c0 1.858 1.593 3.364 3.554 3.364 1.963 0 3.555-1.506 3.555-3.364v-4.709h-4.799c.001-.01.003-.019.003-.029 0-1.426-1.027-2.582-2.295-2.582l-.02.002v-5.252H14.64v4.666c-.514-.184-1.344-.305-2.299-.305l-.006.001V30.5h.433v-1.733H9.621V30.5h.419v2.813c-1.023.303-1.712.754-1.64 1.139l.521 1.204-.007-.038c.052.267.485.436 1.121.482l.005-1.1c-.197 0-.39-.023-.559-.041.159-.089.348-.172.559-.249v2.694c-.874.323-1.49.684-1.429.864m16.431 1.705-1.69-1.689c.075-.083.142-.175.206-.27l1.556 1.554-.002-1.709H23.66c.063-.108.122-.219.17-.337h3.991v4.91l-2.373 1.092v.002h-.334v-.002l-2.374-1.092v-3.658c.118-.064.23-.141.336-.225v3.393l1.966-1.969m-2.561-4.825.423 1.078-.286.099.132.374h-.535l.135-.374-.287-.099.418-1.078m-.751 1.291.423 1.078-.286.1.135.373h-.536l.132-.373-.285-.1.417-1.078m-.751-1.291.423 1.078-.286.099.133.374h-.534l.133-.374-.285-.099.416-1.078m-4.79-.822h.522v-2.088h-.261v-1.045h.489v-.358h-.229v-.522h.978v.522h-.229v.358h.49v-1.141h-.262v-.522H18.7v.522h-.26v1.141h.49v-


()
                    .contains("Can’t assign value(s) for the column \"DEFAULT.TEST_ORDER.ORDER_ID\""));
        }
    }

    @Test
    public void testGetAclTCRResponse() throws IOException {
        Mockito.doReturn(false).when(accessService).hasGlobalAdminGroup(user1);
        Assert.assertEquals(0, aclTCRService.getAclTCRResponse(projectDefault, user1, true, true).size());
        AclTCRManager manager = aclTCRService.getManager(AclTCRManager.class, projectDefault);
        manager.updateAclTCR(new AclTCR(), user1, true);
        Assert.assertTrue(aclTCRService.getAclTCRResponse(projectDefault, user1, true, true).stream()
                .anyMatch(resp -> resp.getTables().stream().anyMatch(t -> "TEST_ORDER".equals(t.getTableName()))));

        AclTCR aclTCR = new AclTCR();
        AclTCR.Table table = new AclTCR.Table();
        AclTCR.ColumnRow columnRow1 = new AclTCR.ColumnRow();
        AclTCR.Column column1 = new AclTCR.Column();
        AclTCR.Row row1 = new AclTCR.Row();
        AclTCR.RealRow realRow1 = new AclTCR.RealRow();
        realRow1.addAll(Arrays.asList("100100", "100101", "100102"));
        row1.put("ORDER_ID", realRow1);
        row1.put("BUYER_ID", null);
        columnRow1.setRow(row1);
        column1.addAll(Arrays.asList("ORDER_ID", "BUYER_ID", "TEST_DATE_ENC"));
        columnRow1.setColumn(column1);
        columnRow1.setColumnSensitiveDataMask(
                Lists.newArrayList(new SensitiveDataMask("ORDER_ID", SensitiveDataMask.MaskType.AS_NULL)));
        table.put("DEFAULT.TEST_ORDER", columnRow1);
        table.put("DEFAULT.TEST_ACCOUNT", null);

        AclTCR.ColumnRow columnRow2 = new AclTCR.ColumnRow();
        AclTCR.Row row2 = new AclTCR.Row();
        AclTCR.RealRow realRow2 = new AclTCR.RealRow();
        realRow2.addAll(Arrays.asList("country_a", "country_b"));
        row2.put("COUNTRY", realRow2);
        columnRow2.setRow(row2);
        table.put("DEFAULT.TEST_COUNTRY", columnRow2);

        aclTCR.setTable(table);

        manager.updateAclTCR(aclTCR, user1, true);

        List<AclTCRResponse> responses = aclTCRService.getAclTCRResponse(projectDefault, user1, true, true);

        Assert.assertTrue(responses.stream()
                .anyMatch(resp -> resp.getTables().stream().anyMatch(t -> "TEST_ORDER".equals(t.getTableName()))));
        Assert.assertTrue(responses.stream()
                .anyMatch(resp -> resp.getTables().stream().noneMatch(t -> "TEST_SITES".equals(t.getTableName()))));

        responses = aclTCRService.getAclTCRResponse(projectDefault, user1, true, false);

        Assert.assertTrue(responses.stream().anyMatch(resp -> resp.getTables().stream()
                .anyMatch(t -> t.isAuthorized() && "TEST_ORDER".equals(t.getTableName()))));
        Assert.assertTrue(responses.stream().anyMatch(resp -> resp.getTables().stream()
                .anyMatch(t -> !t.isAuthorized() && "TEST_SITES".equals(t.getTableName()))));
        Assert.assertEquals(3, responses.stream().filter(resp -> "DEFAULT".equals(resp.getDatabaseName())).findAny()
                .get().getAuthorizedTableNum());
        Assert.assertTrue(responses.stream().anyMatch(resp -> resp.getTables().stream().anyMatch(
                t -> t.getColumns().stream().anyMatch(c -> c


m:merkurydrop

Benjamincody@yahoo.com:86753099

Benjamincompton@hotmail.com:notthatbad

Benjamincwh123@hotmail.com:xdhhnvi

Benjamindonati@hotmail.com:andycole

Benjamine_89@hotmail.com:kanontw

Benjaminemmanuelsmith@hotmail.com:vedder

Benjaminferguson@hotmail.com:felix123

Benjamingaunt@hotmail.com:cabria757

Benjaminguillen86@hotmail.com:baterya

benjaminhui@hotmail.com:mj2323

Benjaminjais@hotmail.com:ttnouvo

Benjaminkheng@hotmail.com:lovediary

benjaminlujan@yahoo.com:omarin79

Benjaminman7@hotmail.com:senisevi

Benjaminmccarthy@hotmail.com:holdenEH

Benjaminmyoung@hotmail.com:wertre

Benjaminplouvier555@hotmail.com:indiana

Benjaminpquest@yahoo.com:ques120475t

Benjaminroccomammola@hotmail.com:quovadis

benjaminroger@yahoo.com:rogbenjiifj

Benjamins101@yahoo.com:Benjam!ns101

Benjaminsean@hotmail.com:burton

Benjamintanjb@hotmail.com:bentjb

Benjamintarraf@hotmail.com:BenTarkan83

Benjaminvdw@yahoo.com:bibi994x

Benjaminvisser@hotmail.com:arend-jan

Benjaminvonmatt@hotmail.com:satan81

Benjaminw6633@hotmail.com:elderman

Benjaminwauman@hotmail.com:swasentnuf

benjamin-winter@gmxpro.de:Knopex3553

Benjaminzhou@yeah.net:62573342

Benjaminzvidzai@yahoo.co.uk:gracez

Benjammin95@hotmail.com:helicopter

Benjamonjuarez@msn.com:benjamon

Benjapintoe@hotmail.com:teoteo

Benjapol29@hotmail.com:2937527

Benjcanfield@yahoo.com:cizzle

Benjebola@hotmail.com:clue4184

Benjellounsimo@hotmail.com:hercule

Benji_192@hotmail.com:checkm8te

Benji_chai@hotmail.com:asshole

Benjicheah@hotmail.com:benjic

Benjieaclan@yahoo.com:benjie

benjin12480@hotmail.com:iobe1710

Benjitawx@hotmail.com:benjalminha

Benjitenerife@hotmail.com:100682

Benjnielsen@hotmail.com:single

benjrouse@hotmail.com:woodson

Benjsoares@hotmail.com:0055500

Benjy_morgan@hotmail.com:dongding

Benjy_zgr8@hotmail.com:noknok

Benjy172002@hotmail.com:socceroos

Benke.huygaerts@gmail.com:bhdfq770

Benkendall@hotmail.com:benjamin

Benkeny2003@hotmail.com:bk6859

Benkham00@hotmail.com:8329


ero));
            literal!(":");
            specifier!(time::fmt_S(S, Padding::Zero));
            literal!(" ");
            specifier!(time::fmt_p(p));
        }
        R => {
            specifier!(time::fmt_H(H, Padding::None));
            literal!(":");
            specifier!(time::fmt_M(M, Padding::Zero));
        }
        S { padding } => specifier!(time::fmt_S(S, padding)),
        T => {
            specifier!(time::fmt_H(H, Padding::None));
            literal!(":");
            specifier!(time::fmt_M(M, Padding::Zero));
            literal!(":");
            specifier!(time::fmt_S(S, Padding::Zero));
        }
        u => specifier!(date::fmt_u(u)),
        U { padding } => specifier!(date::fmt_U(U, padding)),
        V { padding } => specifier!(date::fmt_V(V, padding)),
        w => specifier!(date::fmt_w(w)),
        W { padding } => specifier!(date::fmt_W(W, padding)),
        y { padding } => specifier!(date::fmt_y(y, padding)),
        Y { padding } => specifier!(date::fmt_Y(Y, padding)),
        z => specifier!(offset::fmt_z(z)),
    }

    Ok(())
}

/// An enum that can store both literals and specifiers.
#[allow(variant_size_differences, single_use_lifetimes)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum FormatItem<'a> {
    /// A value that should be printed as-is.
    Literal(&'a str),
    /// A value that needs to be interpreted when formatting.
    Specifier(Specifier),
}
use crate::Cpu;
use util::*;

#[inline]
pub fn interpret(cpu: &mut Cpu, instr: u16) {
    execute(cpu, decode(instr));
}

#[inline]
pub fn decode(instr: u16) -> u32 {
    instr.bits(10, 0)
}

#[inline]
pub fn execute(cpu: &mut Cpu, offset11: u32) {
    let offset = sign_extend(offset11 << 1, 11) as u32;
    cpu.set_r(15, cpu.r(15).wrapping_add(offset));
}
//! An implementation of the [MD2][1] cryptographic hash algorithm.
//!
//! # Usage
//!
//! ```rust
//! use md2::{Md2, Digest};
//! use hex_literal::hex;
//!
//! // create a Md2 hasher instance
//! let mut hasher = Md2::new();
//!
//! // process input message
//! hasher.update(b"hello world");
//!
//! // acquire hash digest in the form of GenericArray,
//! // which in this case is equivalent to [u8; 16]
//! let result = hasher.finalize();
//! assert_eq!(result[..], hex!("d9cce882ee690a5c1ce70beff3a78c77"));
//! ```
//!
//! Also see [RustCrypto/hashes][2] readme.
//!
//! [1]: https://en.wikipedia.org/wiki/MD4
//! [2]: https://github.com/RustCrypto/hashes

#![no_std]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
    html_root_url = "https://docs.rs/md2/0.10.1"
)]
#![forbid(unsafe_code)]
#![warn(missing_docs, rust_2018_idioms)]

pub use digest::{self, Digest};

use core::fmt;
use digest::{
    block_buffer::Eager,
    consts::U16,
    core_api::{
        AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, CoreWrapper, FixedOutputCore,
        OutputSizeUser, Reset, UpdateCore,


unwrap();
/// data_set.add_var_attr_u8("air_temperature", "standard_name", String::from("air_temperature").into_bytes()).unwrap();
/// data_set.add_var_attr_u8("air_temperature", "long_name", String::from("AIR TEMPERATURE").into_bytes()).unwrap();
/// data_set.add_var_attr_u8("air_temperature", "units", String::from("Celsius").into_bytes()).unwrap();
///
/// ```
#[derive(Debug, PartialEq)]
pub struct DataSet {
    pub(crate) unlimited_dim: Option<Rc<Dimension>>,
    pub(crate) dims: Vec<Rc<Dimension>>,
    pub(crate) attrs: Vec<Attribute>,
    pub(crate) vars: Vec<Variable>,
}

impl DataSet {
    // Creates an new empty NetCDF-3 dataset.
    pub fn new() -> DataSet {
        DataSet {
            unlimited_dim: None,
            dims: vec![],
            attrs: vec![],
            vars: vec![],
        }
    }

    // ----------------------------------------------------------------
    //
    //                          Dimensions
    //
    // ----------------------------------------------------------------
    /// Appends a new *fixed size* dimension in the dataset.
    ///
    /// Returns a error if an other dimension with the same name is already defined.
    pub fn add_fixed_dim<T: std::convert::AsRef<str>>(&mut self, dim_name: T, dim_size: usize) -> Result<(), InvalidDataSet> {
        let dim_name: &str = dim_name.as_ref();
        if self.dims.iter().position(|dim| *dim.name.borrow() == dim_name).is_some() {
            return Err(InvalidDataSet::DimensionAlreadyExists(dim_name.to_string()));
        }
        let new_fixed_size_dim = Rc::new(Dimension::new_fixed_size(dim_name, dim_size)?);
        self.dims.push(new_fixed_size_dim);
        return Ok(());
    }

    /// Initializes the *unlimited size* dimension of the dataset.
    ///
    /// Returns a error if :
    ///  1. the *unlimited size* is already defined
    ///  2. if an other dimension with the same name is already defined
    pub fn set_unlimited_dim<T: std::convert::AsRef<str>>(&mut self, dim_name: T, dim_size: usize) -> Result<(), InvalidDataSet> {
        let dim_name: &str = dim_name.as_ref();
        if let Some(unlimited_dim) = &self.unlimited_dim {
            return Err(InvalidDataSet::UnlimitedDimensionAlreadyExists(unlimited_dim.name()));
        }
        if self.dims.iter().position(|dim| *dim.name.borrow() == dim_name).is_some() {
            return Err(InvalidDataSet::DimensionAlreadyExists(dim_name.to_string()));
        }
        let new_unlimited_dim = Rc::new(Dimension::new_unlimited_size(dim_name, dim_size)?);
        self.dims.push(Rc::clone(&new_unlimited_dim));
        self.unlimited_dim = Some(new_unlimited_dim);
        return Ok(());
    }

    /// Returns the number of dimensions defined in the data set.
    pub fn num_dims(&self) -> usize {
        return self.dims.len();
    }

    /// Returns :
    ///
    ///  - `true` if the dimension is defined.
    ///  - `false` otherwise.
    pub fn has_dim(&self, dim_name: &str) -> bool {
        return self.find_dim_from_name(dim_name).is_some();
    }

    /// Returns a reference to the dimension.
    ///
    /// Returns `None` if the dimension is not defined.
    pub fn get_dim(&self, dim_name: &str) -> Option<Rc<


local M = {}

function M.get(colors, opts)
	local theme = colors.theme

	return {
		GrugFarHelpHeader = { fg = theme.ui.header1 },
		GrugFarHelpHeaderKey = { fg = theme.ui.picker },
		GrugFarHelpWinHeader = { fg = theme.ui.header2 },
		GrugFarHelpWinActionPrefix = { link = "GrugFarHelpWinHeader" },
		GrugFarHelpWinActionText = { link = "GrugFarHelpHeader" },
		GrugFarHelpWinActionKey = { fg = theme.ui.picker },
		GrugFarHelpWinActionDescription = { link = "NormalFloat" },

		GrugFarInputLabel = { link = "Identifier" },
		Gru


nt, {}, children)
})
import { Socket } from "net";
import { TCPClient } from "./tcpClient";
var net = require('net');
const readline = require('readline');
const createRLInterface = () => {
    return readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
}
const clear = () => {
    const lines = process.stdout.getWindowSize()[1];
    console.log('-------\n');
    for (var i = 0; i < lines + 2; i++) {
        console.log('\r\n');
    }
    console.log('--------\n');
}

export const startClient = (port, address) => {
    const debug = false;
    const rl = createRLInterface();
    const hostConnection: Socket = new net.Socket();
    hostConnection.on('close', function () {
        console.log('Connection closed');
        rl.close();
    });

    hostConnection.connect(port, address, function () {
        console.log('Connected');
        const tcpClient = new TCPClient(
            {
                sendToClient: (msg) => {
                    clear();
                    process.stdout.write(msg)
                },
                sendToServer: (msg) => {
                    const txt = JSON.stringify(msg);
                    hostConnection.write(txt);
                }
            },
        );
        hostConnection.on("data", chunk => {
            try {
                const json = JSON.parse(chunk.toString());
                tcpClient.receiveFromServer(json)
            } catch (error) {
                if (this.debug) {
                    console.warn("couldnt parse/handle message");
                }
            }
        });
        rl.on('line', (input) => {
            tcpClient.receiveFromClient(input);
        });
        tcpClient.start()
            .then(m => console.log("authenticated", { m }, "\n"))
    });
}
export type Value = {
  id: string
  value: number
}

export type DataItem = {
  id: string
  values: [
    {
      id: string
      values: Value[]
    },
    {
      id: string
      values: Value[]
    }
  ]
}

export type LabelMap = Record<string, string>

export type TooltipMap = Record<string, Record<string, Record<string, string>>>
import _ from "lodash";
import { Node } from "./Node";
import { NodeManager } from "./NodeManager";
import { NodeCodeGenerate } from "./NodeCodeGenerate";

export class TreeMockHelper {
  private _nodeManager: NodeManager;
  private _globalId: number = 1;

  constructor() {
    this._nodeManager = new NodeManager(new NodeCodeGenerate());
  }

  /**
   * 构造树
   * @param rootLength 根节点数量
   * @param length 每个节点下数量
   * @param level 层级深度
   */
  public CreateTree(rootLength: number, length: number, level: number): Node[] {
    if (level < 1) {
      return [];
    }

    let nodes: Node[] = [];
    for (let index = 0; index < rootLength; index++) {
      let curNode = this.CreateNode(index + 1, null);
      nodes.push(curNode);

      if (level > 1) {
        nodes = nodes.concat(
          this.CreateChildrenNode(curNode, length, level - 1)
        );
      }
    }

    return nodes;
  }

  private CreateChildrenNode(
    parentNode: Node,
    length: number,
    level: number
  ): Node[] {
    let nodes: Node[] = [];

    for (let index = 0; index < length; index++) {
      let curNode = this.CreateNode(index + 1, parentNode);
      nodes.push(curNode);
      if (level > 1) {
        nodes = nodes.concat(
          this.CreateChildrenNode(curNode, length, level - 1)
        );


t of this and the
    // remainder is the misc code and data chunks.
    cds_total = FileMapInfo::shared_spaces_size();
    cds_total = align_size_up(cds_total, _reserve_alignment);
    _space_list = new VirtualSpaceList(cds_total/wordSize);
    _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);

    if (!_space_list->initialization_succeeded()) {
      vm_exit_during_initialization("Unable to dump shared archive.", NULL);
    }

#ifdef _LP64
    if (cds_total + compressed_class_space_size() > UnscaledClassSpaceMax) {
      vm_exit_during_initialization("Unable to dump shared archive.",
          err_msg("Size of archive (" SIZE_FORMAT ") + compressed class space ("
                  SIZE_FORMAT ") == total (" SIZE_FORMAT ") is larger than compressed "
                  "klass limit: " SIZE_FORMAT, cds_total, compressed_class_space_size(),
                  cds_total + compressed_class_space_size(), UnscaledClassSpaceMax));
    }

    // Set the compressed klass pointer base so that decoding of these pointers works
    // properly when creating the shared archive.
    assert(UseCompressedOops && UseCompressedClassPointers,
      "UseCompressedOops and UseCompressedClassPointers must be set");
    Universe::set_narrow_klass_base((address)_space_list->current_virtual_space()->bottom());
    if (TraceMetavirtualspaceAllocation && Verbose) {
      gclog_or_tty->print_cr("Setting_narrow_klass_base to Address: " PTR_FORMAT,
                             _space_list->current_virtual_space()->bottom());
    }

    Universe::set_narrow_klass_shift(0);
#endif

  } else {
    // If using shared space, open the file that contains the shared space
    // and map in the memory before initializing the rest of metaspace (so
    // the addresses don't conflict)
    address cds_address = NULL;
    if (UseSharedSpaces) {
      FileMapInfo* mapinfo = new FileMapInfo();
      memset(mapinfo, 0, sizeof(FileMapInfo));

      // Open the shared archive file, read and validate the header. If
      // initialization fails, shared spaces [UseSharedSpaces] are
      // disabled and the file is closed.
      // Map in spaces now also
      if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
        FileMapInfo::set_current_info(mapinfo);
        cds_total = FileMapInfo::shared_spaces_size();
        cds_address = (address)mapinfo->region_base(0);
      } else {
        assert(!mapinfo->is_open() && !UseSharedSpaces,
               "archive file not closed or shared spaces not disabled.");
      }
    }

#ifdef _LP64
    // If UseCompressedClassPointers is set then allocate the metaspace area
    // above the heap and above the CDS area (if it exists).
    if (using_class_space()) {
      if (UseSharedSpaces) {
        char* cds_end = (char*)(cds_address + cds_total);
        cds_end = (char *)align_ptr_up(cds_end, _reserve_alignment);
        allocate_metaspace_compressed_klass_ptrs(cds_end, cds_address);
      } else {
        char* base = (char*)align_ptr_up(Universe::heap()->reserved_region().end(), _reserve_alignment);
        allocate_metaspace_compressed_klass_ptrs(base, 0);
      }
    }
#endif

    // Initialize these before initializing the VirtualSpaceList
    _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
    _first_chunk_word_size = align_word_size_up


  /// Toggles the wakelock on or off.
  ///
  /// You can simply use this function to toggle the wakelock using a [bool]
  /// value (for the [enable] parameter).
  ///
  /// ```dart
  /// // This line keeps the screen on.
  /// Wakelock.toggle(enable: true);
  ///
  /// bool enableWakelock = false;
  /// // The following line disables the wakelock.
  /// Wakelock.toggle(enable: enableWakelock);
  /// ```
  ///
  /// You can await the [Future] to wait for the operation to complete.
  static Future<void> toggle({
    required bool enable,
  }) {
    return wakelockPlatformInstance.toggle(enable: enable);
  }

  /// Returns whether the wakelock is currently enabled or not.
  ///
  /// If you want to retrieve the current wakelock status, you will have to call
  /// [Wakelock.enabled] and await its result:
  ///
  /// ```dart
  /// bool wakelockEnabled = await Wakelock.enabled;
  /// ```
  static Future<bool> get enabled => wakelockPlatformInstance.enabled;
}
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:funvas/funvas.dart';
import 'package:funvas_tweets/funvas_tweets.dart';

/// Recreation of original work by Dave Whyte.
///
/// See https://twitter.com/beesandbombs/status/1376676133425590278?s=20 for
/// the inspiration.
/// All code and concepts in the code are mine - I have no idea how Dave thought
/// about this problem.
class TwentyThree extends Funvas with FunvasTweetMixin {
  @override
  String get tweet =>
      'https://twitter.com/creativemaybeno/status/1377705763402039303?s=20';

  /// The total number of boxes and tiles visible on the screen when fully
  /// zoomed out.
  ///
  /// Where a box refers to a square that splits itself up into smaller tiles
  /// during the animation and a tile being the moving part.
  ///
  /// Note that these have to be odd numbers for the logic to work.
  static const _boxCount = 15, _tileCount = 9;

  /// The stable color for all tiles.
  ///
  /// There are two color modes in my take on the animation: stable and
  /// color wheel. The stable color is shown statically during some parts
  /// of the animation. In some other parts, we lerp to a color on the color
  /// wheel (to be precise, HSL colors with changing hue).
  static const _stableColor = Color(0xffe1c699);

  /// The dimension of our animation.
  ///
  /// We use the same dimension for width and height as we are aiming for a
  /// square.
  /// Side note: the 750x750 at 50 FPS practice is also inspired by Dave
  /// Whyte :)
  static const _d = 750.0;

  /// What fraction of one box one tile takes up in one dimension.
  static const _tileFraction = 1 / 3;

  /// The loop duration in seconds.
  static const _ld = 8.0;

  @override
  void u(double t) {
    c.drawColor(const Color(0xffffffff), BlendMode.srcOver);
    s2q(_d);

    // Set a nice thumbnail.
    t += 2 + 3 / 10;

    // Our center box.
    c.translate(_d / 2, _d / 2);
    c.scale(1 +
        ((_boxCount + 1) / 2) * Curves.easeInQuad.transform((t % _ld) / _ld));
    c.rotate(-pi / 2 * ((t % _ld) / _ld));
    c.save();
    _drawBox(t, 0);
    c.restore();

    // The box extent is how many boxes we go outwards from the center.
    const boe = _boxCount ~/ 2 + 1;
    // We approach the problem in the most inefficient way, where we ignore


       const [x0, xn] = [Math.min(prev.x, curr.x), Math.max(prev.x, curr.x)];
                for (let i = 0; i < (xn - x0) + 1; i += 1) {
                    setBoard({y: prev.y, x: x0 + i }, 2);
                }
            }
            prev = curr;
        }
    }
}

function fillSand(setBoard: BoardSetter, getBoard: BoardGetter, source: Coordinates): boolean {
    const sand = { ...source };

    let cell: Cell;
    let canMove = true;
    while (canMove) {
        canMove = false;

        cell = getBoard({ x: sand.x, y: sand.y + 1 })
        if (cell === -1) {
            return false;
        }
        if (cell === 0) {
            canMove = true;
            sand.y += 1
            continue;
        }

        cell = getBoard({ x: sand.x - 1, y: sand.y + 1 })
        if (cell === -1) {
            return false;
        }
        if (cell === 0) {
            canMove = true;
            sand.x -= 1
            sand.y += 1
            continue;
        }

        cell = getBoard({ x: sand.x + 1, y: sand.y + 1 })
        if (cell === -1) {
            return false;
        }
        if (cell === 0) {
            canMove = true;
            sand.x += 1
            sand.y += 1
            continue;
        }
    }

    setBoard(sand, 3);
    return true;
}

function printBoard(board: Board): void {
    const mapper: string[] = ['.', '+', '#', 'o']
    const draw = board.reduce<string>(
        (cum, curr) => cum + curr.reduce<string>((cum2, curr2) => `${cum2}${mapper[curr2]}`, '') + '\n', '');
    console.log(draw);
}

function writeOutput(output: Output): void {
    const raw = output;
    console.log(raw);
}

main();
const getRes = (url: string): Promise<string> => {
  return new Promise(resolve => {
    const random = Math.random() * 100;
    setTimeout(() => {
      resolve(url);
    }, random);
  });
};

const multiRequest = (urls: string[], maxNum: number) => {
  return new Promise(resolve => {
    const promise = new Promise(r => (resolve = r));

    const ret: Promise<any>[] = [];
    let i = 0;

    const addTask = () => {
      if (i >= urls.length) {
        return resolve();
      }

      const task = getRes(urls[i++])
        .then(res => {
          console.log(res);
          return res;
        })
        .finally(() => {
          addTask();
        });

      ret.push(task);
    };

    while (i < maxNum) {
      addTask();
    }
    return promise.then(() => Promise.all(ret));
  });
};

multiRequest(['1', '2', '3', '4', '5', '6', '7', '8', '9'], 5);

export {};
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { SocketService } from '../socket.service';

@Component({
  selector: 'app-results-popup',
  templateUrl: './results-popup.component.html',
  styleUrls: ['./results-popup.component.css']
})
export class ResultsPopupComponent implements OnInit {
  @ViewChild("resultsText", {read: ElementRef}) resultsText: ElementRef;

  popupIsOpen : boolean;
  voteWinner : any;
  cardToSend : string;
  tiedWinners : Array<any>;
  isAtie : boolean;

  constructor(private socketService: SocketService


 the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.uber.rib.core

/** Debugging utilities when working with Routers. */
public object RouterDebugUtils {
  private const val ARM_RIGHT = "└── "
  private const val INTERSECTION = "├── "
  private const val LINE = "│   "
  private const val SPACE = "    "

  /**
   * Prints out the tree of routers from this point.
   *
   * @param router [Router] root router of a RIB tree
   * @param prefix [String] text to print before the tree
   * @param isTail [Boolean] true if is tail node; otherwise, false
   */
  @JvmStatic
  @JvmOverloads
  public fun printRouterSubtree(router: Router<*>, prefix: String = "", isTail: Boolean = true) {
    Rib.getConfiguration()
      .handleDebugMessage(prefix + (if (isTail) ARM_RIGHT else INTERSECTION) + router.tag)
    val children = router.getChildren()
    for (i in 0 until children.size - 1) {
      printRouterSubtree(children[i], prefix + if (isTail) SPACE else LINE, false)
    }
    if (children.size > 0) {
      printRouterSubtree(children[children.size - 1], prefix + if (isTail) SPACE else LINE, true)
    }
  }
}
/*
 * Copyright (c) 2018. Uber Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.uber.stylist

import com.google.common.io.Files
import com.google.common.truth.Truth.assertThat
import com.uber.stylist.Stylist.DEFAULT_THEMES_XML_FILENAME
import com.uber.stylist.api.StyleItem
import com.uber.stylist.api.StyleItemGroup
import com.uber.stylist.api.ThemeStencil
import org.junit.Test

class StylistTest {

  companion object {
    private const val THEMES_NO_THEMES = """<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources/>
"""

    private const val THEMES_NO_STYLE_GROUPS = """<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
    <style name="Theme.Test" parent="Theme.AppCompat"/>
    <style name="Theme.Test.Light" parent="Theme.AppCompat.Light"/>
    <style name="Theme.Test.Dialog" parent="Theme.AppCompat.Dialog"/>
    <style name="Theme.Test.Light.Dialog" parent="Theme.AppCompat.Light.Dialog"/>
</resources>
"""

    private const val THEMES_WITH_STYLE_GROUP = """<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
    <style name="Theme.Test" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <style name="Theme.Test.Light" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item