#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import NewType, Dict, Union
import string, random, base64
from app.core.security import (
    CustomOAuth2PasswordRequestForm,
    verify_password,
    create_jwt_token,
    decode_jwt_token
)
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.exceptions import CustomException
from aioredis import Redis
from app.utils.tools import get_random_character, generate_captcha
from datetime import timedelta
from app.core.config import settings
from app.crud.system import UserCRUD
from app.models.system import UserModel
from app.schemas.system import JWTPayload, JWTOut, Auth
from datetime import datetime
from fastapi import status

CaptchaKey = NewType('CaptchaKey', str)
CaptchaBase64 = NewType('CaptchaBase64', str)

class LoginService:
    """
    登录模块服务层
    """

    @classmethod
    async def authenticate_user(
            cls,
            login_form: CustomOAuth2PasswordRequestForm,
            session: AsyncSession,
            redis: Redis
    ) -> UserModel:
        if settings.CAPTCHA_ENABLE:
            await CaptchaService.check_captcha(key=login_form.captcha_key, captcha=login_form.captcha, redis=redis)

        auth = Auth(session=session)

        user = await UserCRUD(auth).get_by_username(login_form.username)
        if not verify_password(login_form.password, user.password):
            raise CustomException(
                msg="密码错误",
                code=status.HTTP_401_UNAUTHORIZED
            )

        if not user.available:
            raise CustomException(
                msg="用户已被停用",
                code=status.HTTP_403_FORBIDDEN
            )

        user = await UserCRUD(auth).update_last_login(user.id)
        return user

    @classmethod
    async def create_token(cls, username: str) -> JWTOut:
        expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = create_jwt_token(payload=JWTPayload(
            sub=username,
            is_refresh=False,
            exp=datetime.utcnow() + expires
        ))
        refresh_token = create_jwt_token(payload=JWTPayload(
            sub=username,
            is_refresh=True,
            exp=datetime.utcnow() + timedelta(minutes=settings.REFRESH_TOKEN_EXPIRE_MINUTES)
        ))
        return JWTOut(access_token=access_token, refresh_token=refresh_token, expires_in=expires.total_seconds())

    @classmethod
    async def refresh_token(cls, refresh_token: str) -> JWTOut:
        token_payload = decode_jwt_token(refresh_token)
        if not token_payload.is_refresh:
            raise CustomException(
                msg="非法凭证",
                code=status.HTTP_403_FORBIDDEN,
                status_code=status.HTTP_403_FORBIDDEN
            )

        username = token_payload.sub
        return await cls.create_token(username)

class CaptchaService:
    """
    验证码模块服务层
    """

    @classmethod
    async def get_captcha(cls, redis: Redis) -> Dict[str, Union[CaptchaKey, CaptchaBase64]]:
        if not settings.CAPTCHA_ENABLE:
            raise CustomException(msg="未开启验证码服务", code=status.HTTP_404_NOT_FOUND)

        total_strings = string.digits + string.ascii_lowercase
        random_strings = random.sample(list(total_strings), 4)
        captcha_string = "".join(random_strings)

        captcha = generate_captcha(captcha_string)
        captcha_bytes = captcha.getvalue()
        captcha_base64 = base64.b64encode(captcha_bytes).decode()

        captcha_key = get_random_character()

        r_client = redis.client()
        await r_client.setex(
            f"captcha:{captcha_key}",
            timedelta(seconds=settings.CAPTCHA_EXPIRE_SECONDS),
            captcha_string
        )
        await r_client.close()

        return {
            "key": CaptchaKey(captcha_key),
            "img_base": CaptchaBase64(f"data:image/png;base64,{captcha_base64}")
        }

    @classmethod
    async def check_captcha(cls, key: str, captcha: str, redis: Redis) -> bool:
        if not captcha:
            raise CustomException(msg="验证码不能为空")

        r_client = redis.client()
        captcha_value = await r_client.get(f"captcha:{key}")
        if not captcha_value:
            raise CustomException(msg="验证码已过期", code=status.HTTP_410_GONE)

        if captcha != str(captcha_value):
            raise CustomException(msg="验证码错误")

        await r_client.delete(f"captcha:{key}")
        await r_client.close()

        return True


 (GrammarAST)_t;
			match(_t,RULE);
			_t = _t.getFirstChild();
			id = (GrammarAST)_t;
			match(_t,ID);
			_t = _t.getNextSibling();
			r=id.getText();

			currentRuleName = r;
			factory.currentRule = grammar.getLocallyDefinedRule(r);

			{
			if (_t==null) _t=ASTNULL;
			switch ( _t.getType()) {
			case FRAGMENT:
			case LITERAL_protected:
			case LITERAL_public:
			case LITERAL_private:
			{
				modifier(_t);
				_t = _retTree;
				break;
			}
			case ARG:
			{
				break;
			}
			default:
			{
				throw new NoViableAltException(_t);
			}
			}
			}
			{
			GrammarAST tmp17_AST_in = (GrammarAST)_t;
			match(_t,ARG);
			_t = _t.getNextSibling();
			{
			if (_t==null) _t=ASTNULL;
			switch ( _t.getType()) {
			case ARG_ACTION:
			{
				GrammarAST tmp18_AST_in = (GrammarAST)_t;
				match(_t,ARG_ACTION);
				_t = _t.getNextSibling();
				break;
			}
			case RET:
			{
				break;
			}
			default:
			{
				throw new NoViableAltException(_t);
			}
			}
			}
			}
			{
			GrammarAST tmp19_AST_in = (GrammarAST)_t;
			match(_t,RET);
			_t = _t.getNextSibling();
			{
			if (_t==null) _t=ASTNULL;
			switch ( _t.getType()) {
			case ARG_ACTION:
			{
				GrammarAST tmp20_AST_in = (GrammarAST)_t;
				match(_t,ARG_ACTION);
				_t = _t.getNextSibling();
				break;
			}
			case OPTIONS:
			case BLOCK:
			case SCOPE:
			case AMPERSAND:
			{
				break;
			}
			default:
			{
				throw new NoViableAltException(_t);
			}
			}
			}
			}
			{
			if (_t==null) _t=ASTNULL;
			switch ( _t.getType()) {
			case OPTIONS:
			{
				GrammarAST tmp21_AST_in = (GrammarAST)_t;
				match(_t,OPTIONS);
				_t = _t.getNextSibling();
				break;
			}
			case BLOCK:
			case SCOPE:
			case AMPERSAND:
			{
				break;
			}
			default:
			{
				throw new NoViableAltException(_t);
			}
			}
			}
			{
			if (_t==null) _t=ASTNULL;
			switch ( _t.getType()) {
			case SCOPE:
			{
				ruleScopeSpec(_t);
				_t = _retTree;
				break;
			}
			case BLOCK:
			case AMPERSAND:
			{
				break;
			}
			default:
			{
				throw new NoViableAltException(_t);
			}
			}
			}
			{
			_loop34:
			do {
				if (_t==null) _t=ASTNULL;
				if ((_t.getType()==AMPERSAND)) {
					GrammarAST tmp22_AST_in = (GrammarAST)_t;
					match(_t,AMPERSAND);
					_t = _t.getNextSibling();
				}
				else {
					break _loop34;
				}

			} while (true);
			}
			GrammarAST blk = (GrammarAST)_t;
			b=block(_t);
			_t = _retTree;
			{
			if (_t==null) _t=ASTNULL;
			switch ( _t.getType()) {
			case LITERAL_catch:
			case LITERAL_finally:


能需要更积极地协调护理并寻找替代资源。

- **家庭动态**：兄弟姐妹可能受到影响，既因为基因倾向，也因为家庭动态变化。然而，许多有特殊需求兄弟姐妹的孩子发展出了非凡的同理心和理解差异的能力。

- **自我倡导的必要性**：随着儿童成长，帮助他们理解自己的大脑工作方式至关重要，这样他们可以为自己倡导并发展适合自己思维方式的生活策略。

---

通过将支持重点放在功能障碍而非标签上，采用多学科方法，并优先考虑父母培训和个性化干预，我们可以显著改善有自闭症、ADHD和焦虑的儿童的生活质量和长期结果。记住，每个孩子都是独特的，了解个体孩子比了解诊断本身更重要。# 心血管疾病风险评估与预防：让apoB成为临床决策的核心指标

原始文件：#185 - Allan Sniderman, M.D.： Cardiovascular disease and why we should change the way we assess risk - Peter Attia (3_20_2025 9：58：31 PM).md

原文链接：https://peterattiamd.com/allansniderman/

<YouTube videoId="W1geXgNEG_0" />

## 确定行动指南

1. **将apoB检测纳入常规心血管风险评估**
   - 使用apoB而非仅LDL-C评估心血管疾病风险，apoB测量的是致动脉粥样硬化颗粒的总数量
   - 确保同时测量Lp(a)以全面评估风险，特别是对于有家族史的患者
   - 在高甘油三酯患者中，apoB测量对识别III型高脂蛋白血症至关重要（此类患者有较少但富含胆固醇的极动脉粥样硬化性颗粒）

2. **采用长期风险评估模型而非10年风险预测**
   - 对40岁以下患者，评估30年风险而非10年风险，因为10年风险模型会低估年轻人的实际长期风险
   - 了解早期干预的累积效益—35岁开始治疗比55岁开始可预防更多心血管事件
   - 关注因果风险因素（如apoB水平）而非仅依�


.info("创建歌曲嵌入和长度的字典映射。")

# 加载 style 嵌入
logging.info(f"加载 style 嵌入数据 from '{style_embeddings_file}'。")
with open(style_embeddings_file, 'rb') as f:
    style_embeddings = pickle.load(f)
logging.info("成功加载 style 嵌入数据。")

# 用户配置
logging.info("从 user_features.csv 加载用户信息。")
if os.path.exists(user_features_file):
    user_features_df = pd.read_csv(user_features_file)
    logging.info(f"成功加载用户特征数据，共有 {len(user_features_df)} 个用户。")
    # 打印列名以确认
    print("Columns in user_features_df:", user_features_df.columns.tolist())
    # 打印前几行数据以进一步确认
    print("First few rows in user_features_df:")
    print(user_features_df.head())
else:
    logging.error(f"用户特征文件 '{user_features_file}' 不存在。")
    raise FileNotFoundError(f"用户特征文件 '{user_features_file}' 不存在。")

# 获取新用户ID列表
new_user_ids = user_features_df['user_id'].tolist()

# 检查是否存在重复的 user_id
if os.path.exists(user_listen_data_file):
    existing_listen_data = pd.read_csv(user_listen_data_file)
    existing_user_ids = existing_listen_data['user_id'].unique().tolist()
    duplicate_user_ids = set(new_user_ids) & set(existing_user_ids)
    if duplicate_user_ids:
        logging.error(f"用户ID {duplicate_user_ids} 已存在于现有数据中。")
        raise ValueError(f"用户ID {duplicate_user_ids} 已存在于现有数据中。")
    logging.info("未发现重复的用户ID，可以继续生成数据。")
else:
    logging.info("未找到现有的用户数据，所有用户ID均为新用户。")

# 提取用户特征
style_column_name = 'style'  # 根据实际列名修改
if style_column_name not in user_features_df.columns:
    logging.error(f"用户特征文件中缺少 '{style_column_name}' 列。")
    raise KeyError(f"用户特征文件中缺少 '{style_column_name}' 列。")
user_style = dict(zip(new_user_ids, user_features_df[style_column_name].astype(str).str.strip().str.upper()))
genders = dict(zip(new_user_ids, user_features_df['gender']))
locations = dict(zip(new_user_ids, user_features_df['location']))
logging.info("提取用户的 style 类型、性别和位置。")

# 计算所有 style 嵌入的平均值，作为默认嵌入
default_embedding = np.mean(list(style_embeddings.values()), axis=0)
default_embedding = default_embedding / np.linalg.norm(default_embedding)

# 生成用户偏好向量
logging.info("生成用户偏好向量。")
user_preferences = {}
for idx, user_id in enumerate(new_user_ids):
    style_type = user_style[user_id].strip().upper()  # 去除空格并转换为大写
    # 检查 style 类型是否在 style_embeddings 中
    if style_type in style_embeddings:
        base_pref = style_embeddings[style_type]
        logging.info(f"用户 {user_id} 的 style 类型 '{style_type}' 找到对应的嵌入。")
    else:
        logging.warning(f"用户 {user_id} 的 style 类型 '{style_type}' 不在 style 嵌入中，使用默认嵌入。")
        base_pref = default_embedding
    # 添加随机噪声
    random_noise = np.random.normal(0, 0.05, size=base_pref.shape)
    user_pref = base_pref + random_noise
    user_pref = user_pref / np.linalg.norm(user_pref)
    user_preferences[user_id] = user_pref
    # 打印前几个用户的偏好向量用于验证
    if idx < 5:
        logging.debug(f"用户 {user_id} 的偏好向量: {user_pref}")
        print(f"用户 {user_id} 的偏好向量: {user_pref}")
logging.info("用户偏好向量生成完成。")

# 将歌曲嵌入转换为 PyTorch 张量，并移动到设备上，指定数据类型为 float32
for song_id in song_embedding_dict:
    song_embedding_dict[song_id] = torch.tensor(
        song_embedding_dict[song_id],
        device=device,
        dtype=torch.float32
    )

# 初始化交互记录列表
interaction_records = []

# 生成用户交互数据
logging.info("开始生成用户交互数据。")
start_date = datetime.now() - timedelta(days=30)
base_share_prob = 0.2
base_comment_prob = 0.1

similarity_list = []
like_list = []

for user_id in tqdm(new_user_ids, desc="Generating interactions", unit="user"):
    user_pref = user_preferences[user_id]
    # 将用户偏好转换为 PyTorch 张量，并移动到设备上，指定数据类型为 float32
    user_pref_tensor = torch.tensor(user_pref, device=device, dtype=torch.float32)
    active_hour = random.choice(range(24))
    for _ in range(100):
        song_id = random.choice(song_ids)
        song_row = song_df[song_df['song_id'] == song_id].iloc[0]
        song_name = song_row['song_name']
        artist = song_row['artist']
        song_length = song_length_dict[song_id]
        song_embedding_tensor = song_embedding_dict[song_id]

        # 确保 song_embedding_tensor 为 float32 类型
        song_embedding_tensor = song_embedding_tensor.float()

        # 归一化和计算相似度
        song_embedding_norm = song_embedding_tensor / torch.norm(song_embedding_tensor)
        user_pref_tensor_norm = user_pref_tensor / torch.norm(user_pref_tensor)

        # 相似度计算
        similarity = torch.dot(user_pref_tensor_norm, song_embedding_norm).item() + np.random.normal(0, 0.4)
        like_probability = 1 / (1 + np.exp(-6 * (similarity - 0.4)))

        # 调试日志
        logging.debug(f"用户 {user_


operator, b)
            }
        };

        stack.push(Formatted(result));
        Ok(())
    }
}

impl Boolean {
    // It is important for the tokens to be ordered by their parsing priority (if
    // some operator was a prefix of another operator, the prefix must come later)
    const SYMBOLS: [Symbol<'static, Boolean>; 18] = [
        ("(", false, Token::LBrace),
        (")", false, Token::RBrace),
        ("|", false, Token::Operator(Boolean::Or)),
        ("∨", false, Token::Operator(Boolean::Or)),
        ("or", true, Token::Operator(Boolean::Or)),
        ("OR", true, Token::Operator(Boolean::Or)),
        ("&", false, Token::Operator(Boolean::And)),
        ("∧", false, Token::Operator(Boolean::And)),
        ("and", true, Token::Operator(Boolean::And)),
        ("AND", true, Token::Operator(Boolean::And)),
        ("!", false, Token::Operator(Boolean::Not)),
        ("¬", false, Token::Operator(Boolean::Not)),
        ("not", true, Token::Operator(Boolean::Not)),
        ("NOT", true, Token::Operator(Boolean::Not)),
        ("^", false, Token::Operator(Boolean::Xor)),
        ("⩛", false, Token::Operator(Boolean::Xor)),
        ("xor", true, Token::Operator(Boolean::Xor)),
        ("XOR", true, Token::Operator(Boolean::Xor)),
    ];

    pub fn tokenize(s: &str) -> Tokens<'_, Boolean> {
        Tokens::new(s, &Self::SYMBOLS)
    }

    pub fn parse<'a>(s: &'a str) -> Result<Expression<Boolean>, Token<'a, Boolean>> {
        Self::tokenize(s).collect()
    }
}

// Finally the table printing

fn print_truth_table(s: &str) -> Result<(), std::borrow::Cow<'_, str>> {
    let expression = Boolean::parse(s).map_err(|e| format!("Parsing failed at token {:?}", e))?;

    let formatted = expression
        .formatted()
        .map_err(|_| "Malformed expression detected.")?;

    let var_count = expression.symbols().len();
    if var_count > 64 {
        return Err("Too many variables to list.".into());
    }

    let column_widths = {
        // Print header and compute the widths of columns
        let mut widths = Vec::with_capacity(var_count);

        for symbol in expression.symbols() {
            print!("{}  ", symbol);
            widths.push(symbol.chars().count() + 2); // Include spacing
        }

        println!("{}", formatted);
        let width = widths.iter().sum::<usize>() + formatted.chars().count();
        (0..width).for_each(|_| print!("-"));
        println!();

        widths
    };

    // Choose the bit extraction order for the more traditional table ordering
    let var_value = |input, index| (input >> (var_count - 1 - index)) & 1 ^ 1;
    // Use counter to enumerate all bit combinations
    for var_values in 0u64..(1 << var_count) {
        for (var_index, width) in column_widths.iter().enumerate() {
            let value = var_value(var_values, var_index);
            print!("{:<width$}", value, width = width);
        }

        match expression.evaluate(|var_index| var_value(var_values, var_index) == 1) {
            Ok(result) => println!("{}", if result { "1" } else { "0" }),
            Err(e) => println!("{:?}", e),
        }
    }

    println!();
    Ok(())
}

fn main() {
    loop {
        let input = {
            p


ation = {
            source: target.constructor,
            target: targetModel,
            property: key,
            params: params,
            type: type
        };
        updateRelation(relation.source, relation);
        Database.addRelation(relation);
    };
}

function setDefaultParams(params: HasOneOptions | HasManyOptions, key: string) {
    params = params || {};
    if (!params['as']) {
        params['as'] = key;
    }
    return params;
}

export function getModelRelations(target: any): ModelRelation[] {
    return Reflect.getMetadata(relationMetaKey, target) || [];
}

function saveModelRelations(target: any, relations: ModelRelation[]) {
    return Reflect.defineMetadata(relationMetaKey, relations, target);
}

function updateRelation(target: any, relation: ModelRelation) {
    let relations = getModelRelations(target);
    let destRelation = relations.find(x => x.property === relation.property);
    if (destRelation) {
        Object.assign(destRelation, relation);
    } else {
        relations.push(relation);
    }
    saveModelRelations(target, relations);
}

export function Eager(target: DataModel, key: string) {
    let relation = {
        property: key,
        eager: true
    };
    updateRelation(target.constructor, relation);
}

export function BelongsToMany(targetModel: typeof DataModel, options: BelongsToManyOptions) {
    return hasAssociation('belongsToMany', targetModel, options);
}/**
 * Game canvas
 *
 * Entry page of the game.
 */

export abstract class SoundHelper {

    static backgroundMusic: Phaser.Sound.BaseSound | null = null;

    static playBackgroundMusic(music: Phaser.Sound.BaseSound | undefined): void {
        if (!music) {
            return; // cannot play null
        }

        if (this.backgroundMusic && this.backgroundMusic.isPlaying) {
            if (this.backgroundMusic.key == music.key) {
                return; // music with same key (same music) already playing
            }
            this.backgroundMusic.stop();
        }

        music.play('', { loop: true })
        this.backgroundMusic = music;
    }
}

let reviews: number[] = [4, 1, 7.5, 8, 5.6, 6.2, 9.6, 0.4];
for(let i=0; i<reviews.length; i++) {
    // console.log(reviews[i]);
}

let sportsOne: string[] = ["Golf", "Cricket", "Baseball", "Swimming"];
for(let i=0; i<sportsOne.length; i++) {
    console.log(sportsOne[i]);
}

console.log("-----------------------------------------")

// simplfied for loop
for(let sport of sportsOne) {
    if(sport === "Cricket") {
        console.log(`${sport} <<-- my Favourite`);
    }
    else{
        console.log(sport);
    }
}import {JsonObject, JsonProperty} from "json2typescript";

@JsonObject
export class City {

    // This property has no @JsonProperty.
    // It will only be mapped if our JSON object contains a key named "id".
    // If there is no such element, no exception is thrown.
    // There will be no type checking at all.
    id: number = undefined; // <- assign a value or undefined to enable the mapper!

    // This maps the value of the JSON key "name" to the class property "name".
    // If the JSON value is not of type string (or missing), there will be an exception.
    @JsonProperty("name", String)
    name: string = undefined;

    // This maps the JSON key "founded" to the private class property "_founded".
    // Note the use of public getter and setter.
    // If the JSON value is


I0RsdIZE4zOZxb6OrcWNU28Edh8CSMXwTrzX4OBiKlEF8LXhou7AFvbp/Xy+IX8LvkR3P4mPs9r2AlIiLX8JkcRYEcBBa6JrMoKYC8CigOw8X9kLjA1NTvNxCOQ+VGiJTB5AiMeuDd4gFSboL5uwc0xkpERBan4TbIpiBYDJVbIFoF5nqPNTMVpqq2TbVYeWkYbgWrUCXzS8FKREQWp9Gz0HcAsuPT4WrrVLj62MI7091/lVshXAq5Sbj0Pgy1fsLuQ5FPTsFKREQWJ5uDkTPQd2iq5SpUBBUfDVcGInGovGMqVHkZ6D86NS7Lm/tAZZGP8gGtwKWFroiIiMgvzXow0gGOHyo2Q7BwKkSd3wUTQxCIQsWWqbFV1psKVEOn1VIlvzb/HyPwdT309pvmAAAAAElFTkSuQmCC"/>

(in that case, we chose to also provide the user to traverse explicitely from Diagnosis to Error to Error Code, but sometimes you want to completely hide some entities)

<h2 style="mso-pagination:widow-orphan lines-together;page-break-after:avoid;line-


tokenResponse.toHttpParameters()["presentation_submission"]!!.first()
        val decoded = Json.parseToJsonElement(debugPresentingPresentationSubmission).jsonObject
        val encoded = prettyPrintJson.encodeToString(decoded)
        println(encoded)

        println("Submitting...")
        val resp = http.submitForm(siopSession.authorizationRequest!!.responseUri!!,
            parameters {
                tokenResponse.toHttpParameters().forEach { entry ->
                    println("submitForm param: ${entry.key} -> ${entry.value}")
                    println("first val is: ${entry.value.first()}")
                    appendAll(entry.key, entry.value)
                }
            })
        assertEquals(expected = HttpStatusCode.OK, actual = resp.status)
    }

    //@Test
    suspend fun testSphereonLaunchpadVerificationRequest() {
        /*
        https://wallet.example.com?
            client_id=https%3A%2F%2Fclient.example.org%2Fcb
            &request_uri=https%3A%2F%2Fclient.example.org%2F567545564
         */

        /*
        openid-vc://?request_uri=https%3A%2F%2Fssi.sphereon.com%2Fagent%2Fsiop%2Fdefinitions%2Fsphereon%2Fauth-requests%2F9727e922-e8a3-4b79-a29e-a167062b8ac4

        'request_uri':	https://ssi.sphereon.com/agent/siop/definitions/sphereon/auth-requests/9727e922-e8a3-4b79-a29e-a167062b8ac4

        eyJhbGciOiJFUzI1NiIsImtpZCI6ImRpZDpqd2s6ZXlKaGJHY2lPaUpGVXpJMU5pSXNJblZ6WlNJNkluTnBaeUlzSW10MGVTSTZJa1ZESWl3aVkzSjJJam9pVUMweU5UWWlMQ0o0SWpvaVZFY3lTREo0TW1SWFdFNHpkVU54V25CeFJqRjVjMEZRVVZaRVNrVk9YMGd0UTAxMFltZHFZaTFPWnlJc0lua2lPaUk1VFRoT2VHUXdVRTR5TWswNWJGQkVlR1J3UkhCdlZFeDZNVFYzWm5sYVNuTTJXbWhMU1ZWS016TTRJbjAjMCIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2OTYyNTI3NTEsImV4cCI6MTY5NjI1Mjg3MSwicmVzcG9uc2VfdHlwZSI6Imlk


import streamlit as st

st.set_page_config(page_title="HealthWise", page_icon="💬", layout="wide")

st.write("# Welcome to HealthWise! 👋")

st.markdown(
    """
    HealthWise is an innovative multi-agent system designed to revolutionize public health management.
    Harnessing real-time symptom reporting and advanced analytics, HealthWise empowers individuals and health authorities to act swiftly against the spread of infectious diseases.
    """
)

st.markdown("### How It Works:")

st.markdown(
    """
    🌐 **Track Symptoms Effortlessly**
    Share your health concerns through an intuitive interface and receive instant guidance tailored to your needs.\n
    🚀 **Real-time Data Reporting**
    Contribute to the global health monitoring system by reporting symptoms in real time.\n
    📊 **Analyze Health Trends**
    HealthWise processes data from diverse locations, identifying patterns and potential hotspots before they escalate.\n
    🏥 **Support Healthcare Systems**
    Equip medical professionals with real-time insights for informed decision-making and timely responses.\n
    """
)

st.markdown(
    """
    ## Our Mission
    Join us in safeguarding community health and creating a safer, smarter future with HealthWise.
    Your health. Our mission. 🌍
    """
)


32a, %g1, %o0
	ta	T_SEND_THRD_INTR
	.word 0xf22c4000  ! 1007: STB_R	stb	%r25, [%r17 + %r0]
	.word 0xfc2c61a8  ! 1011: STB_I	stb	%r30, [%r17 + 0x01a8]
	.word 0xf425e0f8  ! 1012: STW_I	stw	%r26, [%r23 + 0x00f8]
	.word 0xbb353001  ! 1013: SRLX_I	srlx	%r20, 0x0001, %r29
iob_intr_3_85:
!$EV trig_pc_d(3,expr(@VA(.MAIN.iob_intr_3_85), 16, 16)) -> intp(3, 0, b)
iob_intr_3_86:
!$EV trig_pc_d(3,expr(@VA(.MAIN.iob_intr_3_86), 16, 16)) -> intp(3, 0, 9)
	.word 0xf2250000  ! 1021: STW_R	stw	%r25, [%r20 + %r0]
iob_intr_3_87:
!$EV trig_pc_d(3,expr(@VA(.MAIN.iob_intr_3_87), 16, 16)) -> intp(3, 0, 10)
cpu_intr_3_81:
	setx	0x26001b, %g1, %o0
	ta	T_SEND_THRD_INTR
	.word 0xf8a4a04b  ! 1027: STWA_I	stwa	%r28, [%r18 + 0x004b] %asi
iob_intr_3_88:
!$EV trig_pc_d(3,expr(@VA(.MAIN.iob_intr_3_88), 16, 16)) -> intp(3, 0, 16)
	setx	data_start_1, %g1, %r16
	ta	T_CHANGE_HPRIV
	mov	0x38, %g1
	stxa	%r21, [%g1] 0x58
	.word 0x81982810  ! 1033: WRHPR_HPSTATE_I	wrhpr	%r0, 0x0810, %hpstate
cpu_intr_3_82:
	setx	0x260310, %g1, %o0
	ta	T_SEND_THRD_INTR
	ta	T_CHANGE_TO_TL1
	setx	data_start_7, %g1, %r19
	ta	T_CHANGE_HPRIV
	mov	0x38, %g1
	stxa	%r17, [%g1] 0x58
	.word 0x81982852  ! 1036: WRHPR_HPSTATE_I	wrhpr	%r0, 0x0852, %hpstate
cpu_intr_3_83:
	setx	0x270137, %g1, %o0
	ta	T_SEND_THRD_INTR
T3_asi_reg_rd_51:
	mov	0x1, %r14
	.word 0xf2db8400  ! 1038: LDXA_R	ldxa	[%r14, %r0] 0x20, %r25
	ta	T_CHANGE_HPRIV
	mov	0, %g1
	stxa	%g0, [%g1] 0x60
	flush
	ta	T_CHANGE_NONHPRIV
	.word 0xf02c21fc  ! 1041: STB_I	stb	%r24, [%r16 + 0x01fc]
iob_intr_3_89:
!$EV trig_pc_d(3,expr(@VA(.MAIN.iob_intr_3_89), 16, 16)) -> intp(3, 0, 21)
	.word 0xf024e1f


#include <stdio.h>

#define maxc (prs >> 16)
#define maxr (prs & 0xff00) >> 8
#define find (col > 1)
#define endb || (prs & 16) && X(0) || chpa || (eols, 0)
#define lnst doln ? 0 : (init, 0) || (prs & 128) && X(0)
#define L    endb) || 0 || (find ? 0 : (rrr++, rrc = 0)) || (lnst
#define X(p) (dfc++ && ((prs & 48) != 32 || rrc < maxc) && ++ccl && \
             (find ? (bat = bit, bit = but, but = p, ccl == col && \
             (ret = bat + bit + but) + 1) : (las = las * 2 + \
             (((main(ccl + 1, cro - 1) + main(ccl + 1, cro) + \
             main(ccl + 1, cro + 1) - p) | p) == 3), occ |= las & 1, \
             printf(" %c", "_O"[las & 1]), ccl == 2 && (sta |= (las & 3) << 6),\
             0)))
#define _    || (find || rrc++, 0) || X(0)
#define O    || (find || rrc++, 0) || X(1)
#define chpa (find && col > ccl && ((ret = bit + but) + 1))
#define eols (!find && (cro == 1 ? (sta |= occ << 3) : cro == 2 && \
             (sta |= occ << 2), sta |= (las & 3) << 4))
#define init (find ? (ret = bit = but = 0) : (ocp = occ, las = occ = 0, \
             printf("\nL")), dfc = (prs & 192) != 64, ccl = 0)
#define doln !(dfl++ && (((prs & 3) != 2) || rrr < maxr) && \
             (++cro == row || !find))
#define recu (col =- col, (ccl = find ? rcf : rcl), cro = rro, 0 _ || \
             (rrc >= maxc ? 0 : (find ? rcf = ccl : (rcl = ccl), \
             main(-col, row))))
#define addl (lnst || (rro = cro, find ? rcf = ccl : (rrc = 0, rcl = ccl), \
             0) || main(-col, row) || (ccl = rcl + 1, 0) endb)
#define outp (find || printf("\n\nGEN %d STAT %ld\nEND\n", ++gen, \
             (long)ccl << 16 | cro << 8 | (sta | occ | ocp << 1) ^ 0x66))
#define GEN  endb) || (prs & 1) && addl || (outp, 0)), ret)); } int gen =
#define STAT ;long prs =
#define END  ;
#define LIFE int bat, bit, but, las, gen, ret, rcl, rcf, rro, rrc, rrr, \
             occ, ocp, sta, dfc; long prs; int main(int col, char *argv[]) { \
	     int row = (int)argv; int dfl = ((prs & 12) != 4), ccl = 0, cro = 0; return \
             col == 1 && printf("LIFE\n"), (col < 0 ? recu : \
             (((ret = 0) || (prs & 8) && addl || 0 && (0

#include "life.d"


CreateLevel3Table (uintptr nBaseAddress)
{
	TARMV8MMU_LEVEL3_DESCRIPTOR *pTable = (TARMV8MMU_LEVEL3_DESCRIPTOR *) palloc ();
	assert (pTable != 0);

	for (unsigned nPage = 0; nPage < ARMV8MMU_TABLE_ENTRIES; nPage++)	// 8192 entries a 64KB
	{
		TARMV8MMU_LEVEL3_PAGE_DESCRIPTOR *pDesc = &pTable[nPage].Page;

		pDesc->Value11	     = 3;
		pDesc->AttrIndx	     = ATTRINDX_NORMAL;
		pDesc->NS	     = 0;
		pDesc->AP	     = ATTRIB_AP_RW_EL1;
		pDesc->SH	     = ATTRIB_SH_INNER_SHAREABLE;
		pDesc->AF	     = 1;
		pDesc->nG	     = 0;
		pDesc->Reserved0_1   = 0;
		pDesc->OutputAddress = ARMV8MMUL3PAGEADDR (nBaseAddress);
		pDesc->Reserved0_2   = 0;
		pDesc->Continous     = 0;
		pDesc->PXN	     = 0;
		pDesc->UXN	     = 1;
		pDesc->Ignored	     = 0;

		extern u8 _etext;
		if (nBaseAddress >= (u64) &_etext)
		{
			pDesc->PXN = 1;

#if RASPPI >= 4
			if (   (   nBaseAddress >= m_nMemSize
			        && nBaseAddress < MEM_HIGHMEM_START)
			    || nBaseAddress > MEM_HIGHMEM_END)
#else
			if (nBaseAddress >= m_nMemSize)
#endif
			{
				pDesc->AttrIndx = ATTRINDX_DEVICE;
				pDesc->SH	= ATTRIB_SH_OUTER_SHAREABLE;
			}
			else if (   nBaseAddress >= MEM_COHERENT_REGION
				 && nBaseAddress <  MEM_HEAP_START)
			{
				pDesc->AttrIndx = ATTRINDX_COHERENT;
				pDesc->SH	= ATTRIB_SH_OUTER_SHAREABLE;
			}
		}

		nBaseAddress += ARMV8MMU_LEVEL3_PAGE_SIZE;
	}

	return pTable;
}
//
// i2ssoundbasedevice.cpp
//
// Supports:
//	BCM283x/BCM2711 I2S output
//	two 24-bit audio channels
//	sample rate up to 192 KHz
//	tested with PCM5102A DAC only
//
// References:
//	https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=8496
//
// Circle - A C++ bare metal environment for Raspberry Pi
// Copyright (C) 2016-2020  R. Stange <rsta2@o2online.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with


org')) 'https://$domain/lnurlp/$username',
        if (domain.contains('btclake.com')) 'https://$domain/.well-known/lnurl/$username',
      ].where((url) => url != null).cast<String>().toList();

      _debugLog('[INVOICE_SERVICE] 🌍 Resolving ${isWeb ? "WEB" : "MOBILE"}: $lightningAddress ($domain)');

      Map<String, dynamic>? metadata;
      String? workingUrl;

      for (final url in urls) {
        try {
          _debugLog('[INVOICE_SERVICE] Trying resolution: $url');
          _debugLog('[INVOICE_SERVICE] Platform: ${isAndroid ? "Android" : "Web/Desktop"}');

          // Create specific client for external request
          final externalDio = Dio();
          externalDio.options.connectTimeout = isAndroid
              ? const Duration(seconds: 20)
              : const Duration(seconds: 15);
          externalDio.options.receiveTimeout = isAndroid
              ? const Duration(seconds: 20)
              : const Duration(seconds: 15);
          externalDio.options.headers['User-Agent'] = AppInfoService.getUserAgent();
          externalDio.options.headers['Accept'] = 'application/json';

          _configureProxyForDio(externalDio);

          if (isAndroid) {
            externalDio.options.headers['Cache-Control'] = 'no-cache';
            externalDio.options.followRedirects = true;
            externalDio.options.maxRedirects = 3;
          }

          final response = await externalDio.get(url);

          if (response.statusCode == 200 && response.data is Map) {
            final data = response.data as Map<String, dynamic>;
            if (data.containsKey('callback') && data['tag'] == 'payRequest') {
              metadata = data;
              workingUrl = url;
              _debugLog('[INVOICE_SERVICE] ✅ Resolution successful with: $url');
              externalDio.close();
              break;
            } else {
              _debugLog('[INVOICE_SERVICE] ❌ Response is not valid LNURL-pay: $data');
            }
          }
          externalDio.close();
        } catch (e) {
          _debugLog('[INVOICE_SERVICE] ❌ Error with $url: ${e.toString()}');
          if (e.toString().contains('CORS') || e.toString().contains('blocked')) {
            _debugLog('[INVOICE_SERVICE] 🚫 CORS error detected - external server blocks web requests');
          }
          continue;
        }
      }

      if (metadata == null) {
        throw Exception('Could not resolve Lightning Address: $lightningAddress.\n\nVerify that:\n1. The address is valid\n2. The server supports Lightning Address\n3. You have internet connection');
      }

      // Validate amount
      final minSendable = metadata['minSendable'] as int;
      final maxSendable = metadata['maxSendable'] as int;
      final amountMsat = amountSats * 1000;

      if (amountMsat < minSendable) {
        throw Exception('Minimum amount: ${minSendable ~/ 1000} sats');
      }
      if (amountMsat > maxSendable) {
        throw Exception('Maximum amount: ${maxSendable ~/ 1000} sats');
      }

      // Generate invoice using callback
      final callbackUrl = metadata['callback'] as String;
      final params = {'amount': amountMsat.toString()};
      if (comment != null && comment.isNotEmpty) {
        params['comment'] = comment;
      }

      _debugLog('[INVOICE_SERVICE] Generating invoice from callback: $callbackUrl');

      // Use external client for callback as well
      final callbackDio = Dio();
      call


                  if (tab.TabType == MyCommon.TabUsageType.Mentions)
                                    excludedReply = true;
                                break;
                        }
                    }

                    post.FilterHit = filterHit;
                    post.IsMark = mark;
                    post.IsExcludeReply = excludedReply;

                    // 移動されなかったらRecentに追加
                    if (!moved)
                        homeTab.AddPostQueue(post);

                    // 除外ルール適用のないReplyならReplyタブに追加
                    if (post.IsReply && !excludedReply)
                        replyTab.AddPostQueue(post);

                    // Fav済み発言だったらFavoritesタブに追加
                    if (post.IsFav)
                        favTab.AddPostQueue(post);

                    adddedCount++;
                }

                return adddedCount;
            }
        }

        public void AddPost(PostClass item)
        {
            Debug.Assert(!item.IsDm, "DM は TabClass.AddPostToInnerStorage を使用する");

            lock (this.lockObj)
            {
                if (this.IsGlobalMuted(item))
                    return;

                if (this.Posts.TryGetValue(item.StatusId, out var status))
                {
                    if (item.IsFav)
                    {
                        if (item.RetweetedId == null)
                        {
                            status.IsFav = true;
                        }
                        else
                        {
                            item.IsFav = false;
                        }
                    }
                    else
                    {
                        return;        // 追加済みなら何もしない
                    }
                }
                else
                {
                    if (item.IsFav && item.RetweetedId != null) item.IsFav = false;

                    // 既に持っている公式RTは捨てる
                    if (item.RetweetedId != null && SettingManager.Instance.Common.HideDuplicatedRetweets)
                    {
                        var retweetCount = this.UpdateRetweetCount(item);

                        if (retweetCount > 1 && !item.IsMe)
                            return;
                    }

                    this.Posts.TryAdd(item.StatusId, item);
                }
                if (item.IsFav && this.retweetsCount.ContainsKey(item.StatusId))
                {
                    return;    // Fav済みのRetweet元発言は追加しない
                }
                this.addQueue.Enqueue(item.StatusId);
            }
        }

        public bool IsGlobalMuted(PostClass post)
        {
            var muteTab = this.MuteTab;
            if (muteTab != null && muteTab.AddFiltered(post) == MyCommon.HITRESULT.Move)
                return true;

            return false;
        }

        private int UpdateRetweetCount(PostClass retweetPost)
        {
            if (retweetPost.RetweetedId == null)
                throw new InvalidOperationException();

            var retweetedId = retweetPost.RetweetedId;

            return this.retweetsCount.AddOrUpdate(retweetedId, 1, (k, v) => v >= 10 ? 1 : v + 1);
        }

        public bool AddQuoteTweet(PostClass item)
        {
            lock (this.lockObj)
            {
                if (this.IsGlobalMuted(item))
                    return false;

                this.quotes[item.StatusId] = item;
                return true;
            }
        }

        /// <summary>
        /// 全てのタブを横断して既読状態を変更します
        /// </summary>
        /// <param name="statusId">変更するツイートのID</param>
        /// <param name="read">既読状態</param>
        /// <returns>既読状態に変化があれば true、変化がなければ false</returns>
        public bool SetReadAllTab(PostId statusId, bool read)
        {
            lock (this.lockObj)
            {
                foreach (var tab in this.Tabs)
                {
                    if (!tab.Contains(statusId))
                        continue;

                    tab.SetReadState(statusId, read);
                }

                // TabInformations自身が保持しているツイートであ


// ComponentDescriptionMetadata.cs
//
// Circuit Diagram http://www.circuit-diagram.org/
//
// Copyright (C) 2012  Sam Fisher
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CircuitDiagram.TypeDescription
{
    public class ComponentDescriptionMetadata
    {
        public Guid GUID { get; set; }
        public string Version { get; set; }
        public string Author { get; set; }
        public string AdditionalInformation { get; set; }
        pu


, writing into out. in must be non-nil.
func (in *ClusterBackup) DeepCopyInto(out *ClusterBackup) {
	*out = *in
	if in.Enabled != nil {
		in, out := &in.Enabled, &out.Enabled
		*out = new(bool)
		**out = **in
	}
	if in.StartingDeadlineMinutes != nil {
		in, out := &in.StartingDeadlineMinutes, &out.StartingDeadlineMinutes
		*out = new(int64)
		**out = **in
	}
	if in.PITREnabled != nil {
		in, out := &in.PITREnabled, &out.PITREnabled
		*out = new(bool)
		**out = **in
	}
	if in.IncrementalBackupEnabled != nil {
		in, out := &in.IncrementalBackupEnabled, &out.IncrementalBackupEnabled
		*out = new(bool)
		**out = **in
	}
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBackup.
func (in *ClusterBackup) DeepCopy() *ClusterBackup {
	if in == nil {
		return nil
	}
	out := new(ClusterBackup)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterComponentConfig) DeepCopyInto(out *ClusterComponentConfig) {
	*out = *in
	if in.Name != nil {
		in, out := &in.Name, &out.Name
		*out = new(string)
		**out = **in
	}
	if in.Variables != nil {
		in, out := &in.Variables, &out.Variables
		*out = make(map[string]string, len(*in))
		for key, val := range *in {
			(*out)[key] = val
		}
	}
	in.ClusterComponentConfigSource.DeepCopyInto(&out.ClusterComponentConfigSource)
	if in.Reconfigure != nil {
		in, out := &in.Reconfigure, &out.Reconfigure
		*out = new(Action)
		(*in).DeepCopyInto(*out)
	}
	if in.ExternalManaged != nil {
		in, out := &in.ExternalManaged, &out.ExternalManaged
		*out = new(bool)
		**out = **in
	}
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterComponentConfig.
func (in *ClusterComponentConfig) DeepCopy() *ClusterComponentConfig {
	if in == nil {
		return nil
	}
	out := new(ClusterComponentConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterComponentConfigSource) DeepCopyInto(out *ClusterComponentConfigSource) {
	*out = *in
	if in.ConfigMap != nil {
		in, out := &in.ConfigMap, &out.ConfigMap
		*out = new(corev1.ConfigMapVolumeSource)
		(*in).DeepCopyInto(*out)
	}
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterComponentConfigSource.
func (in *ClusterComponentConfigSource) DeepCopy() *ClusterComponentConfigSource {
	if in == nil {
		return nil
	}
	out := new(ClusterComponentConfigSource)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ClusterComponentService) DeepCopyInto(out *ClusterComponen


WithBounce() {
    byte[] secretKey =
        Utils.hexToSignedBytes("F182111193F30D79D517F2339A1BA7C25FDF6C52142F0F2C1D960A1F1D65E1E4");
    TweetNaclFast.Signature.KeyPair keyPair = TweetNaclFast.Signature.keyPair_fromSeed(secretKey);

    log.info("pubKey: {}", Utils.bytesToHex(keyPair.getPublicKey()));
    log.info("secKey: {}", Utils.bytesToHex(keyPair.getSecretKey()));

    WalletV3R2 contract = WalletV3R2.builder().wc(0).keyPair(keyPair).walletId(42).build();

    log.info("rawAddress {}", contract.getAddress().toRaw());

    WalletV3Config config =
        WalletV3Config.builder()
            .destination(
                Address.of("0:258e549638a6980ae5d3c76382afd3f4f32e34482dafc3751e3358589c8de00d"))
            .walletId(42)
            .seqno(1L)
            .amount(Utils.toNano(1))
            .bounce(true)
            .validUntil(1753376922)
            .build();

    Message msg = contract.prepareExternalMsg(config);

    log.info("extmsg {}", msg.toCell().print());
    // external message for serialization
    assertThat(msg.toCell().bitStringToHex())
        .isEqualTo(
            "88005A537F40E3918C5F467316CC35085CC1E09971522BF67CE93DEF8D882687C2D805623D1FDA58DD3880E03FFC5DF6DC6456A79E16F68BC7CAA1E74CFE1C12D4DB291B812D01C801932189992F16D78BBCFC6DCFE34DD2A9A431D301381BCCCBE86000000153441344D0000000081C_");
    // external message in BoC format
    assertThat(Utils.bytesToHex(msg.toCell().toBoc(true)).toUpperCase())
        .isEqualTo(
            "B5EE9C724101020100A90001DF88005A537F40E3918C5F467316CC35085CC1E09971522BF67CE93DEF8D882687C2D805623D1FDA58DD3880E03FFC5DF6DC6456A79E16F68BC7CAA1E74CFE1C12D4DB291B812D01C801932189992F16D78BBCFC6DCFE34DD2A9A431D301381BCCCBE86000000153441344D0000000081C010068620012C72A4B1C534C0572E9E3B1C157E9FA79971A2416D7E1BA8F19AC2C4E46F006A1DCD6500000000000000000000000000000676B3B92");
  }

  /**
   * >fift -s wallet-v3.fif new-wallet
   * 0:258e549638a6980ae5d3c76382afd3f4f32e34482dafc3751e3358589c8de00d 42 1 1 -n -t 1000
   */
  @Test
  public void testCreateTransferMessageWalletV3R2NoBounce() {
    byte[] secretKey =
        Utils.hexToSignedBytes("F182111193F30D79D517F2339A1BA7C25FDF6C52142F0F2C1D960A1F1D65E1E4");
    TweetNaclFast.Signature.KeyPair keyPair = TweetNaclFast.Signature.keyPair_fromSeed(secretKey);

    WalletV3R2 contract = WalletV3R2.builder().walletId(42).wc(0).keyPair(keyPair).build();

    WalletV3Config config =
        WalletV3Config.builder()


 TRY(False, MPI_UNSIGNED_SHORT, "UNSIGNED_SHORT");
    TRY(False, MPI_INT, "INT");
    TRY(False, MPI_UNSIGNED, "UNSIGNED");
    TRY(False, MPI_LONG, "LONG");
    TRY(False, MPI_UNSIGNED_LONG, "UNSIGNED_LONG");
    TRY(False, MPI_FLOAT, "FLOAT");
    TRY(False, MPI_DOUBLE, "DOUBLE");
    TRY(False, MPI_LONG_DOUBLE, "LONG_DOUBLE");
    TRY(False, MPI_CHARACTER, "CHARACTER");

    // Same deal as above
    // TRY(False, MPI_LOGICAL, "LOGICAL");
    // TRY(False, MPI_INTEGER, "INTEGER");
    // TRY(False, MPI_REAL, "REAL");
    // TRY(False, MPI_DOUBLE_PRECISION, "DOUBLE_PRECISION");

    TRY(False, MPI_COMPLEX, "COMPLEX");
    TRY(False, MPI_DOUBLE_COMPLEX, "DOUBLE_COMPLEX");
#if defined(MPI_INTEGER1)
    TRY(False, MPI_INTEGER1, "INTEGER1");
#endif
#if defined(MPI_INTEGER2)
    TRY(False, MPI_INTEGER2, "INTEGER2");
#endif
#if defined(MPI_INTEGER4)
    TRY(False, MPI_INTEGER4, "INTEGER4");
#endif
#if defined(MPI_INTEGER8)
    TRY(False, MPI_INTEGER8, "INTEGER8");
#endif
    TRY(False, MPI_LONG_LONG, "LONG_LONG");
    TRY(False, MPI_UNSIGNED_LONG_LONG, "UNSIGNED_LONG_LONG");
#if defined(MPI_REAL4)
    TRY(False, MPI_REAL4, "REAL4");
#endif
#if defined(MPI_REAL8)
    TRY(False, MPI_REAL8, "REAL8");
#endif
#if defined(MPI_REAL16)
    TRY(False, MPI_REAL16, "REAL16");
#endif

#undef TRY

    }

    MPI_Finalize();
    return 0;
}


  : AxisArgName == NAME_IS_CONCAT_DIM ? "concat_dim" : "<invalid>";
    OP_REQUIRES_OK(c, c->input(axis_attribute_name, &concat_dim_tensor));
    OP_REQUIRES(c, IsLegacyScalar(concat_dim_tensor->shape()),
                errors::InvalidArgument(
                    axis_attribute_name,
                    " tensor should be a scalar integer, but got shape ",
                    concat_dim_tensor->shape().DebugString()));
    const int32 concat_dim =
        internal::SubtleMustCopy(concat_dim_tensor->scalar<int32>()());
    OpInputList values;
    OP_REQUIRES_OK(c, c->input_list("values", &values));
    const int N = values.size();
    const int input_dims = values[0].dims();
    const TensorShape& input_shape = values[0].shape();

    int32 axis = concat_dim < 0 ? concat_dim + input_dims : concat_dim;
    OP_REQUIRES(c, (0 <= axis && axis < input_dims) ||
                       (allow_legacy_scalars() && concat_dim == 0),
                errors::InvalidArgument(
                    "ConcatOp : Expected concatenating dimensions in the range "
                    "[",
                    -input_dims, ", ", input_dims, "), but got ", concat_dim));
    // Note that we reduce the concat of n-dimensional tensors into a two
    // dimensional concat. Assuming the dimensions of any input/output
    // tensor are {x0, x1,...,xn-1, y0, y1,...,ym-1}, where the concat is along
    // the dimension indicated with size y0, we flatten it to {x, y}, where y =
    // Prod_i(yi) and x = ((n > 0) ? Prod_i(xi) : 1).
    ConstMatrixVector inputs_flat;
    inputs_flat.reserve(N);
    int64 inputs_flat_dim0 = 1;
    for (int d = 0; d < axis; ++d) {
      inputs_flat_dim0 *= input_shape.dim_size(d);
    }
    int64 output_concat_dim = 0;
    const bool input_is_scalar = IsLegacyScalar(input_shape);
    for (int i = 0; i < N; ++i) {
      const auto in = values[i];
      const bool in_is_scalar = IsLegacyScalar(in.shape());
      OP_REQUIRES(
          c, in.dims() == input_dims || (input_is_scalar && in_is_scalar),
          errors::InvalidArgument(
              "ConcatOp : Ranks of all input tensors should match: shape[0] = ",
              input_shape.DebugString(), " vs. shape[", i, "] = ",
              in.shape().DebugString()));
      for (int j = 0; j < input_dims; ++j) {
        if (j == axis) {
          continue;
        }
        OP_REQUIRES(
            c, in.dim_size(j) == input_shape.dim_size(j),
            errors::InvalidArgument(
                "ConcatOp : Dimensions of inputs should match: shape[0] = ",
                input_shape.DebugString(), " vs. shape[", i, "] = ",
                in.shape().DebugString()));
      }
      if (in.NumElements() > 0) {
        int64 inputs_flat_dim1 = in.NumElements() / inputs_flat_dim0;
        inputs_flat.emplace_back(new typename TTypes<T, 2>::ConstMatrix(
            in.shaped<T, 2>({inputs_flat_dim0, inputs_flat_dim1})));
      }
      // TODO(irving): Remove check once !allow_legacy_scalars().
      output_concat_dim += in.dims() > 0 ? in.dim_size(axis) : 1;
    }

    TensorShape output_shape(input_shape);
    // TODO(irving): Remove rank 0 case once !allow_legacy_scalars().
    if (output_shape.dims() == 0) {
      output_shape.AddDim(output_concat_dim);
    } else {
      output_shape.set_dim(axis, output_concat_dim);


.description(ARTIFACT_DOWNLOADING_COUNT_DESC)
            .register(meterRegistry)

        Gauge.builder(ASYNC_TASK_ACTIVE_COUNT, threadPoolTaskExecutor.threadPoolExecutor) { it.activeCount.toDouble() }
            .description(ASYNC_TASK_ACTIVE_COUNT_DESC)
            .register(meterRegistry)

        Gauge.builder(ASYNC_TASK_QUEUE_SIZE, threadPoolTaskExecutor.threadPoolExecutor) { it.queue.size.toDouble() }
            .description(ASYNC_TASK_QUEUE_SIZE_DESC)
            .register(meterRegistry)
    }

    private fun ensureDownloadAndUploadFinish() {
        logger.info("start to wait download and upload finish")
        while (downloadingCount.get() > 0 || uploadingCount.get() > 0) {
            logger.info("downloading count: ${downloadingCount.get()}, uploading count: ${uploadingCount.get()}")
            Thread.sleep(60 * 1000)
        }
        logger.info("all download and upload task is finish")
    }

    companion object {
        private val logger = LoggerFactory.getLogger(ArtifactMetrics::class.java)
        private lateinit var tagProvider: ArtifactTransferTagProvider
        lateinit var meterRegistry: MeterRegistry
        private lateinit var lruMeterFilter: LruMeterFilter
        private lateinit var properties: ArtifactMetricsProperties
        private const val MAX_ATIME = 30.0
        private const val BYTES = "bytes"
        private const val DAY = "day"

        /**
         * 获取已上传文件大小摘要
         * 用于上传计算文件分布
         * */
        fun getUploadedDistributionSummary(): DistributionSummary {
            return DistributionSummary.builder(ARTIFACT_UPLOADED_SIZE)
                .description(ARTIFACT_UPLOADED_SIZE_DESC)
                .baseUnit(BYTES)
                .publishPercentileHistogram()
                .maximumExpectedValue(properties.maxLe)
                .register(meterRegistry)
        }

        /**
         * 获取已下载文件摘要
         * 用于计算下载文件分布
         * */
        fun getDownloadedDistributionSummary(): DistributionSummary {
            return DistributionSummary.builder(ARTIFACT_DOWNLOADED_SIZE)
                .description(ARTIFACT_DOWNLOADED_SIZE_DESC)
                .baseUnit(BYTES)
                .publishPercentileHistogram()
                .maximumExpectedValue(properties.maxLe)
                .register(meterRegistry)
        }

        /**
         * 获取访问时间metric
         * 用于计算文件系统的文件访问时间分布
         * */
        fun getAccessTimeDistributionSummary(): DistributionSummary {
            return DistributionSummary.builder(ARTIFACT_ACCESS_TIME)
                .description(ARTIFACT_ACCESS_TIME_DESC)
                .baseUnit(DAY)
                .publishPercentileHistogram()
                .maximumExpectedValue(MAX_ATIME)
                .register(meterRegistry)
        }

        /**
         * 获取实时上传计数器
         * 用于计算上传实时流量
         * */
        fun getUploadingCounters(receiver: ArtifactDataReceiver): List<Counter> {
            val limitUploadingCounter = Counter.builder(ARTIFACT_LIMIT_UPLOADING_SIZE)
                .description(ARTIFACT_LIMIT_UPLOADING_SIZE_DESC)
                .tags(tagProvider.getTags(receiver, true))
                .baseUnit(BYTES)
                .register(meterRegistry)
                .apply { lruMeterFilter.access(this.id) }
            val uploadingCounter = Counter.builder(ARTIFACT_UPL


RELOCATABLE
.INSRT B;B DEF

%"printf":
	.+1
	OP2 S,21
	OP2 VA,17
	OP2 C,0
	OP B1
	OP2 IVA,14
	OP2 VA,3
	OP B1
L1:
L2:
	OP2 S,21
	OP2 VA,16
	OP2 X,%"char"
	OP N2
	OP2 A,2
	OP2 VA,17
	OP U7
	OP N3
	OP B1
	OP2 C,45
	OP B5
	OP2 F,L3
	OP2 IA,16
	OP2 C,0
	OP B4
	OP2 F,L4
	OP N11
L4:
	OP2 IX,%"putchar"
	OP N2
	OP2 A,16
	OP N3
	OP2 T,L2
L3:
	OP2 IVA,15
	OP2 VA,14
	OP U7
	OP U3
	OP B1
	OP2 IVA,16
	OP2 X,%"char"
	OP N2
	OP2 A,2
	OP2 VA,17
	OP U7
	OP N3
	OP B1
	OP2 Z,L5
L6=144
L7:
L10=157
L11:
	OP2 IX,%"printn"
	OP N2
	OP2 A,15
	OP2 A,16
	OP2 C,157
	OP B4
	OP2 F,L1


#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int
main(int argc, char **argv) {

    if(argc < 2) {
    fprintf(stderr, "Please enter a number of the Fibonacci series to compute.\n");
    return 1;
    }

    uint32_t v = atoi(argv[1]);

    mpz_t a, b, c, tmp1, tmp2, new_a, new_b;

    mpz_init(a);
    mpz_init(b);
    mpz_init(c);
    mpz_init(tmp1);
    mpz_init(tmp2);
    mpz_init(new_a);
    mpz_init(new_b);

    mpz_init_set_ui(a, 1);
    mpz_init_set_ui(b, 0);
    mpz_init_set_ui(c, 1);

    int bits = 31;
    while (bits > 0 && !((v >> bits) & 1)) {
        bits--;
    }
    while (bits >= 0) {

        if((v >> bits) & 1) {
            mpz_add(tmp1, a, c);
            mpz_mul(new_a, tmp1, b);

            mpz_mul(tmp1, b, b);
            mpz_mul(tmp2, c, c);
            mpz_add(new_b, tmp1, tmp2);
        } else {
            mpz_mul(tmp1, a, a);
            mpz_mul(tmp2, b, b);
            mpz_add(new_a, tmp1, tmp2);

            mpz_add(tmp1, a, c);
            mpz_mul(new_b, tmp1, b);
        }

        mpz_set(a, new_a);
        mpz_set(b, new_b);
        mpz_add(c, a, b);
        bits--;
    }

    mpz_out_str(stdout, 10, b);
    printf("\n");

    return 0;
}


';   /* output data */
			this.error = 0;          /* error code */
			this.checksum_function = null; /* crc32(for gzip) or adler32(for zlib) */
	};

    /**
	 * TODO
	 * @constructor
	 */
	ZLIB.gz_header = function() {
		this.text = 0;      /* true if compressed data believed to be text */
	    this.time = 0;      /* modification time */
		this.xflags = 0;    /* extra flags (not used when writing a gzip file) */
		this.os = 0xff;     /* operating system */
		this.extra = null;  /* extra field string or null if none */
		this.extra_len = 0; /* this.extra.length (only when reading header) */
		this.extra_max = 0; /* space at extra (only when reading header) */
		this.name = null;   /* file name string or null if none */
		this.name_max = 0;  /* space at name (only when reading header) */
		this.comment = null; /* comment string or null if none */
		this.comm_max = 0;  /* space at comment (only when reading header) */
		this.hcrc = 0;      /* true if there was or will be a header crc */
		this.done = 0;      /* true when done reading gzip header (not used
							   when writing a gzip file) */
	};

	ZLIB.common_initialized = true;
} // common definitions
/* zlib-inflate.js -- JavaScript implementation for the zlib inflate.
  Version: 0.2.0
  LastModified: Apr 12 2012
  Copyright (C) 2012 Masanao Izumo <iz@onicos.co.jp>

  This library is one of the JavaScript zlib implementation.
  Some API's are modified from the original.
  Only inflate API is implemented.

  The original copyright notice (zlib 1.2.6):

  Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

  Jean-loup Gailly        Mark Adler
  jloup@gzip.org          madler@alumni.caltech.edu

  The data format used by the zlib library is described by RFCs (Request for
  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
*/

/*
                       API documentation
==============================================================================
Usage: z_stream = ZLIB.inflateInit([windowBits]);

     Create the stream object for decompression.
     See zlib.h for windowBits information.

==============================================================================
Usage: decoded_string = z_stream.inflate(encoded_string [, {OPTIONS...}]);

OPTIONS:
    next_in: decode start offset for encoded_string.

    avail_in: // TODO document.  See zlib.h for the information.

    avail_out: // TODO document.  See zlib.h for the information.

    flush: // TODO document.  See zlib.h for the information.

Ex: decoded_string = z


 == 1) | (row['PPAPHIF'] == 2)) | ((row['PSPIF'] == 1) | (row['PSPIF'] == 2)) | ((row['CORTIF'] == 1) | (row['CORTIF'] == 2))) & (row['NACCUDSD'] == 4):
        flag = 1
        row['FTD'] = 1
    else:
        row['FTD'] = 0

    # NPH
    if ((row['HYCEPHIF'] == 1) | (row['HYCEPHIF'] == 2)) & (row['NACCUDSD'] == 4):
        flag = 1
        row['NPH'] = 1
    else:
        row['NPH'] = 0

    # Infectious (HIV included), metabolic, substance abuse / alcohol, medications, systemic disease, delirium (Systemic and External Factors)
    if (((row['OTHCOGIF'] == 1) | (row['OTHCOGIF'] == 2)) | ((row['HIVIF'] == 1) | (row['HIVIF'] == 2)) | ((row['ALCDEMIF'] == 1) | (row['ALCDEMIF'] == 2)) | ((row['IMPSUBIF'] == 1) | (row['IMPSUBIF'] == 2)) | ((row['DYSILLIF'] == 1) | (row['DYSILLIF'] == 2)) | ((row['MEDSIF'] == 1) | (row['MEDSIF'] == 2)) | ((row['DELIRIF'] == 1) | (row['DELIRIF'] == 2))) & (row['NACCUDSD'] == 4):
        flag = 1
        row['SEF'] = 1
    else:
        row['SEF'] = 0

    # Psychiatric including schizophrenia, depression, bipolar, anxiety, PTSD
    if (((row['DEPIF'] == 1) | (row['DEPIF'] == 2)) | ((row['BIPOLDIF'] == 1) | (row['BIPOLDIF'] == 2)) | ((row['SCHIZOIF'] == 1) | (row['SCHIZOIF'] == 2)) | ((row['ANXIETIF'] == 1) | (row['ANXIETIF'] == 2)) | ((row['PTSDDXIF'] == 1) | (row['PTSDDXIF'] == 2)) | ((row['OTHPSYIF'] == 1) | (row['OTHPSYIF'] == 2))) & (row['NACCUDSD'] == 4):
        flag = 1
        row['PSY'] = 1
    else:
        row['PSY'] = 0

    # TBI
    if ((row['BRNINJIF'] == 1) | (row['BRNINJIF'] == 2)) & (row['NACCUDSD'] == 4):
        flag = 1
        row['TBI'] = 1
    else:
        row['TBI'] = 0

    # OTHER
    if  (row['NACCUDSD'] == 4) & ((flag == 0) | ((row['MSAIF'] == 1) | (row['MSAIF'] == 2)) | ((row['ESSTREIF'] == 1) | (row['ESSTREIF'] == 2)) | ((row['DOWNSIF'] == 1) | (row['DOWNSIF'] == 2)) | ((row['HUNTIF'] == 1) | (row['HUNTIF'] == 2)) | ((row['EPILEPIF'] == 1) | (row['EPILEPIF'] == 2)) | ((row['NEOPIF'] == 1) | (row['NEOPIF'] == 2)) | ((row['DEMUNIF'] == 1) | (row['DEMUNIF'] == 2)) | ((row['COGOTHIF'] == 1) | (row['COGOTHIF'] == 2)) | ((row['COGOTH2F'] == 1) | (row['COGOTH2F'] == 2)) | ((row['COGOTH3F'] == 1) | (row['COGOTH3F'] == 2))):
        row['ODE'] = 1
    else:
        row['ODE'] = 0

    return row

mri_data_path = '/your_path/NACC/UDS_with_NP_and_Genetics_plus_FTLD_and_LBD_modules/investigator_scan_mriqc_nacc67.csv'
ftlblbd_data_path = '/your_path/NACC/UDS_with_NP_and_Genetics_plus_FTLD_and_LBD_modules/investigator_ftldlbd_nacc67.csv'
# Merge the MRI and FTLBLDB csv files
mri_data = pd.read_csv(mri_data_path)
ftlblbd_data = pd.read_csv(ftlblbd_data_path)
# merged_data = pd.merge(ftlblbd_data, mri_data, on=["NACCID", "NACCVNUM", "NACCNMRI", "NACCMRSA", "NACCADC"], how='left')
merged_data = ftlblbd_data
# Convert the features and labels to the required format
merged_data_var_converted = features_conversion(merged_data)
merged_data_converted = merged_data_var_converted.apply(labels_conversion, axis=1)
merged_data_converted.to_csv('Preprocessed_NACC_DATA.csv', index=False)


vent, rds_cm_event_str(event->event));
		break;
	}

out:
	if (conn)
		mutex_unlock(&conn->c_cm_lock);

	rdsdebug("id %p event %u (%s) handling ret %d\n", cm_id, event->event,
		 rds_cm_event_str(event->event), ret);

	return ret;
}

static int rds_rdma_listen_init(void)
{
	struct sockaddr_in sin;
	struct rdma_cm_id *cm_id;
	int ret;

	cm_id = rdma_create_id(rds_rdma_cm_event_handler, NULL, RDMA_PS_TCP,
			       IB_QPT_RC);
	if (IS_ERR(cm_id)) {
		ret = PTR_ERR(cm_id);
		printk(KERN_ERR "RDS/RDMA: failed to setup listener, "
		       "rdma_create_id() returned %d\n", ret);
		return ret;
	}

	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = (__force u32)htonl(INADDR_ANY);
	sin.sin_port = (__force u16)htons(RDS_PORT);

	/*
	 * XXX I bet this binds the cm_id to a device.  If we want to support
	 * fail-over we'll have to take this into consideration.
	 */
	ret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin);
	if (ret) {
		printk(KERN_ERR "RDS/RDMA: failed to setup listener, "
		       "rdma_bind_addr() returned %d\n", ret);
		goto out;
	}

	ret = rdma_listen(cm_id, 128);
	if (ret) {
		printk(KERN_ERR "RDS/RDMA: failed to setup listener, "
		       "rdma_listen() returned %d\n", ret);
		goto out;
	}

	rdsdebug("cm %p listening on port %u\n", cm_id, RDS_PORT);

	rds_rdma_listen_id = cm_id;
	cm_id = NULL;
out:
	if (cm_id)
		rdma_destroy_id(cm_id);
	return ret;
}

static void rds_rdma_listen_stop(void)
{
	if (rds_rdma_listen_id) {
		rdsdebug("cm %p\n", rds_rdma_listen_id);
		rdma_destroy_id(rds_rdma_listen_id);
		rds_rdma_listen_id = NULL;
	}
}

static int rds_rdma_init(void)
{
	int ret;

	ret = rds_rdma_listen_init();
	if (ret)
		goto out;

	ret = rds_iw_init();
	if (ret)
		goto err_iw_init;

	ret = rds_ib_init();
	if (ret)
		goto err_ib_init;

	goto out;

err_ib_init:
	rds_iw_exit();
err_iw_init:
	rds_rdma_listen_stop();
out:
	return ret;
}
module_init(rds_rdma_init);

static void rds_rdma_exit(void)
{
	/* stop listening first to ensure no new connections are attempted */
	rds_rdma_listen_stop();
	rds_ib_exit();
	rds_iw_exit();
}
module_exit(rds_rdma_exit);

MODULE_AUTHOR("Oracle Corporation <rds-devel@oss.oracle.com>");
MODULE_DESCRIPTION("RDS: IB/iWARP transport");
MODULE_LICENSE("Dual BSD/GPL");


er and size in bytes.
	inline uint64_t hash64(const void* buffer, size_t buffer_size)
	{
		fnv1a_64 hashfn = fnv1a_64();
		hashfn.update(buffer, buffer_size);
		return hashfn.digest();
	}

	////////////////////////////////////////////////////////////////////////////////
	// Returns the 64 bit hash of the provided element.
	template<typename ElementType>
	inline uint64_t hash64(const ElementType& element) { return hash64(&element, sizeof(ElementType)); }

	////////////////////////////////////////////////////////////////////////////////
	// Returns the 64 bit hash of the provided string.
	// The null terminator not included in the hash.
	inline uint64_t hash64(const char* str)
	{
		const size_t buffer_size = str != nullptr ? std::strlen(str) : 0;
		return hash64(str, buffer_size);
	}

	////////////////////////////////////////////////////////////////////////////////
	// Combines two hashes into a new one.
	inline uint32_t hash_combine(uint32_t hash_a, uint32_t hash_b) { return (hash_a ^ hash_b) * 16777619U; }
	inline uint64_t hash_combine(uint64_t hash_a, uint64_t hash_b) { return (hash_a ^ hash_b) * 1099511628211ULL; }

	ACL_IMPL_VERSION_NAMESPACE_END
}

ACL_IMPL_FILE_PRAGMA_POP


alid {
  box-shadow: none;
}

/*
Add the correct vertical alignment in Chrome and Firefox.
*/

progress {
  vertical-align: baseline;
}

/*
Correct the cursor style of increment and decrement buttons in Safari.
*/

::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
  height: auto;
}

/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/

[type='search'] {
  -webkit-appearance: textfield; /* 1 */
  outline-offset: -2px; /* 2 */
}

/*
Remove the inner padding in Chrome and Safari on macOS.
*/

::-webkit-search-decoration {
  -webkit-appearance: none;
}

/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/

::-webkit-file-upload-button {
  -webkit-appearance: button; /* 1 */
  font: inherit; /* 2 */
}

/*
Add the correct display in Chrome and Safari.
*/

summary {
  display: list-item;
}

/*
Removes the default spacing and border for appropriate elements.
*/

blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
  margin: 0;
}

fieldset {
  margin: 0;
  padding: 0;
}

legend {
  padding: 0;
}

ol,
ul,
menu {
  list-style: none;
  margin: 0;
  padding: 0;
}

/*
Prevent resizing textareas horizontally by default.
*/

textarea {
  resize: vertical;
}

/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/

input::placeholder,
textarea::placeholder {
  opacity: 1; /* 1 */
  color: #9ca3af; /* 2 */
}

/*
Set the default cursor for buttons.
*/

button,
[role='button'] {
  cursor: pointer;
}

/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
  cursor: default;
}

/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
   This can trigger a poorly considered lint error in some tools but is included by design.
*/

img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
  display: block; /* 1 */
  vertical-align: middle; /* 2 */
}

/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/

img,
video {
  max-width: 100%;
  height: auto;
}

/* Make elements with the HTML hidden attribute stay hidden by default */
[hidden] {
  display: none;
}
/* fade */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease-in-out;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* fade-slide */
.fade-slide-leave-active,
.fade-slide-enter-active {
  transition: all 0.3s;
}
.fade-slide-enter-from {
  opacity: 0;
  transform: translateX(-30


### 备注

Gecko 内核的浏览器会在源代码中标签内部有空白符的地方插入一个文本结点到文档中。因此，使用诸如 [`Node.firstChild`](/zh-CN/docs/Web/API/Node/firstChild) 和 [`Node.previousSibling`](/zh-CN/docs/Web/API/Node/previousSibling) 之类的方法可能会引用到一个空白符文本节点，而不是使用者所预期得到的节点。

详情请参见 [DOM 中的空白符](/zh-CN/docs/Web/CSS/CSS_text/Whitespace) 和[W3C DOM 3 FAQ: 为什么一些文本节点是空的](https://www.w3.org/DOM/faq.html#emptytext).

获取后一个兄弟节点，请使用[Node.nextSibling](/zh-CN/docs/Web/API/Node/nextSibling).

### 规范

[DOM Level 1 Core: previousSibling](https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#attribute-previousSibling)

[DOM Level 2 Core: previousSibling](https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-640FB3C8)
---
title: Node：removeChild() 方法
slug: Web/API/Node/removeChild
l10n:
  sourceCommit: aa8fa82a902746b0bd97839180fc2b5397088140
---

{{APIRef("DOM")}}

{{domxref("Node")}} 接口的 **`removeChild()`** 方法会从 DOM 中移除一个子节点，并返回移除的节点。

> [!NOTE]
> 只要对被移除的子节点保持引用，它仍然存在于内存中，但不再是 DOM 的一部分。在以后的代码中仍可重复使用。
>
> 如果不存储 `removeChild()` 的返回值，也不保留其他引用，该节点将在短时间内在内存中[自动删除](/zh-CN/docs/Web/JavaScript/Guide/Memory_management)。

与 {{domxref("Node.cloneNode()")}} 不同，返回值保留了与其关联的 `EventListener` 对象。

## 语法

```js-nolint
removeChild(child)
```

### 参数

- `child`
  - : {{domxref("Node")}}，即要从 DOM 中删除的子节点。

### 异常

- `NotFoundError` {{domxref("DOMException")}}
  - : 如果 `child` 不是该节点的子节点，则抛出此异常。
- {{jsxref("TypeError")}}
  - : 如果 `child` 为 `null`，则抛出此异常。

## 示例

### 简单的示例

给定以下 HTML：

```html
<div id="parent">
  <div id="child"></div>
</div>
```

在已知其父节点时移除指定元素：

```js
const parent = document.getElementById("parent");
const child = document.getElementById("child");
const throwawayNode = parent.removeChild(child);
```

在不需要指定其父节点的情况下移除指定元素：

```js
const node = document.getElementById("child");
if (node.parentNode) {
  node.parentNode.removeChild(node);
}
```

从元素中移除所有子元素：

```js
const element = document.getElementById("idOfParent");
while (element.firstChild) {
  element.removeChild(element.firstChild);
}
```

### 引发 TypeError

```html
<!--HTML 代码示例-->
<div id="parent"></div>
```

```js
const parent = document.getElementById("parent");
const child = document.getElementById("child");

// 抛出未捕获的 TypeError
const garbage = parent.removeChild(child);
```

### 引发 NotFound


use ::error::Result;
use ::plugin;
use mio;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::mpsc::channel;
use std::thread;

// NOCOM(#sirver): when a client disconnects and we still try to call one of it's rpcs, we never
// get an error back - this will effectively interrupt the rpc call stack.
// NOCOM(#sirver): document everything.

pub struct Server {
    unix_domain_socket_name: PathBuf,
    tcp_addresses: Vec<String>,
    commands: swiboe::SenderTo,
    ipc_bridge_commands: mio::Sender<ipc_bridge::Command>,
    swiboe_thread: Option<thread::JoinHandle<()>>,
    event_loop_thread: Option<thread::JoinHandle<()>>,
    buffer_plugin: Option<plugin::buffer::Plugin>,
    list_files_plugin: Option<plugin::list_files::Plugin>,
    log_plugin: Option<plugin::log::Plugin>,
}

impl Server {
    pub fn launch(unix_domain_socket_name: &Path, tcp_addresses: &[&str]) -> Result<Self> {
        let (tx, rx) = channel();

        let mut event_loop = mio::EventLoop::new().expect("Could not create an event loop.");

        let mut server = Server {
            unix_domain_socket_name: unix_domain_socket_name.to_path_buf(),
            tcp_addresses: tcp_addresses.iter().map(|slice| slice.to_string()).collect(),
            commands: tx.clone(),
            ipc_bridge_commands: event_loop.channel(),
            buffer_plugin: None,
            list_files_plugin: None,
            log_plugin: None,
            swiboe_thread: None,
            event_loop_thread: None,
        };

        server.swiboe_thread = Some(swiboe::spawn(event_loop.channel(), tx.clone(), rx));

        let mut ipc_bridge = ipc_bridge::IpcBridge::new(
            &mut event_loop, &server.unix_domain_socket_name, &server.tcp_addresses,
            server.commands.clone());

        server.event_loop_thread = Some(thread::spawn(move || {
            event_loop.run(&mut ipc_bridge).expect("Could not start event_loop.");
        }));

        server.buffer_plugin = Some(try!(plugin::buffer::Plugin::new(
                    try!(client::Client::connect_unix(&server.unix_domain_socket_name)))));
        server.list_files_plugin = Some(try!(plugin::list_files::Plugin::new(
                    try!(client::Client::connect_unix(&server.unix_domain_socket_name)))));
        server.log_plugin = Some(try!(plugin::log::Plugin::new(
                    try!(client::Client::connect_unix(&server.unix_domain_socket_name)))));
        Ok(server)
    }

    pub fn shutdown(&mut self) {
        // Any of the threads might have already panicked. So we ignore send errors.
        let _ = self.ipc_bridge_commands.send(ipc_bridge::Command::Quit);
        self.wait_for_event_loop_thread_to_shut_down();
        let _ = self.commands.send(swiboe::Command::Quit);
        self.wait_for_swiboe_thread_to_shut_down();

        self.wait_for_shutdown();
    }

    fn wait_for_event_loop_thread_to_shut_down(&mut self)


ck-colr.ttf");
  cbdt = hb_test_open_font_file ("fonts/chromacheck-cbdt.ttf");
  sbix = hb_test_open_font_file ("fonts/chromacheck-sbix.ttf");
  svg = hb_test_open_font_file ("fonts/chromacheck-svg.ttf");
  empty = hb_face_get_empty ();
  hb_test_add (test_hb_ot_color_palette_get_count);
  hb_test_add (test_hb_ot_color_palette_get_name_id_empty);
  hb_test_add (test_hb_ot_color_palette_get_name_id_v0);
  hb_test_add (test_hb_ot_color_palette_get_name_id_v1);
  hb_test_add (test_hb_ot_color_palette_get_flags_empty);
  hb_test_add (test_hb_ot_color_palette_get_flags_v0);
  hb_test_add (test_hb_ot_color_palette_get_flags_v1);
  hb_test_add (test_hb_ot_color_palette_get_colors_empty);
  hb_test_add (test_hb_ot_color_palette_get_colors_v0);
  hb_test_add (test_hb_ot_color_palette_get_colors_v1);
  hb_test_add (test_hb_ot_color_palette_color_get_name_id);
  hb_test_add (test_hb_ot_color_glyph_get_layers);
  hb_test_add (test_hb_ot_color_has_data);
  hb_test_add (test_hb_ot_color_png);
  hb_test_add (test_hb_ot_color_svg);
  status = hb_test_run();
  hb_face_destroy (cpal_v0);
  hb_face_destroy (cpal_v1);
  hb_face_destroy (cpal);
  hb_face_destroy (cbdt);
  hb_face_destroy (sbix);
  hb_face_destroy (svg);
  return status;
}


SPACE=0 HSPACE=0>

be connected to the Internet

via proxy servers using Nestscape Communicator browser
by leFaF

25 November 1998 ~ 12 December 1998
 Nice present for frequent browsers... Read,

understand, use, enjoy!
Unfortunately IeFaF was a little sloppy, here you'll find

some later adjustment :-(

"-=J M F=-" <lefaf@hotmail.com>

Dear fravia+,

Since the first time I started to explore the dedalous of what you call

your fortress, I was baffle on how you manage to crystalise and give

away such a huge amount of information. Although knowing nothing about

reverse engineering, searching nor anonymity, nevertheless I became a

regular (avid) visitor; slowly learning -mostly by osmosis.

As I saw bright stars rising through various essays, I never thought I

could be able one day to propose my little brick to your edifice :)

Perhaps, this day has arrived. Thanks to you.

Kind regards and be well. leFaF's "Configuring Netscape to use proxy"

Here follow my "comments" on your seasonal feelings.
When I saw the very nice drawing on fravia+'s autumnal page, I was wondering

where I could be on the picture.
On the shore waving goodbye to the boat and its captain, well, no.

Under the sea swimming round and around big fishes, yet , no.

One of the personage, aboard the lean drakkar sailing away, this time

again, no.
And they were sailing away...
At this point, I started to realise that I had been just a spectator

entertained by what he and other freely gave away.

All of a sudden I felt like a peeping-tom.

A taker, not a giver.
And they were sailing away...
What can I do: I do not want to be left, I hate to be under, I cannot

be aboard... What is left?
Although obvious since the beginning, the answer finally came bright

and clear: give, share, participate.
All of a sudden I felt free, free as a bird...
I was flying away.

           Configuring Netscape Communicator to surf anonymously

But hey, wait, why should I surf anonymously and, by the way, what is

a proxy?

A scary answer can be found here.

To put is strait, when you are in the comfort of your computer room, all

alone with your machine, nobody knows what you are doing, right.

Wrong!

You splatter information about yourself all over the world. It's kind

of walking naked in a crowded boulevard with your ID card hanging on your

neck...

Oh!

On the Wild Web, there are nasty things like


sudadera_nike);import { Arr } from '@ephox/katamari';
import Attr from 'ephox/sugar/api/properties/Attr';
import Element from 'ephox/sugar/api/node/Element';
import InsertAll from 'ephox/sugar/api/dom/InsertAll';
import Traverse from 'ephox/sugar/api/search/Traverse';
import { UnitTest, assert } from '@ephox/bedrock';
import { document, window } from '@ephox/dom-globals';

UnitTest.test('TraverseTest', function() {
  var node = function (name) {
    var div = Element.fromTag('div');
    Attr.set(div, 'name', name);
    return div;
  };

  var textNode = function (text) {
    var el = Element.fromText(text);
    return el;
  };

  var grandparent = node('grandparent');
  var uncle = node('uncle');
  var mother = node('mother');

  var youngest = node('youngest');
  var middle = node('middle');
  var oldest = node('oldest');

  InsertAll.append(grandparent, [ uncle, mother ]);
  InsertAll.append(mother, [ youngest, middle, oldest ]);

  var checkNone = function (subject) {
    assert.eq(true, Traverse.findIndex(subject).isNone(), 'Expected "' + Attr.get(subject, 'name') + '" not to have a parent.');
  };

  var checkIndex = function (expected, subject) {
    var name = Attr.get(subject, 'name');
    var actual = Traverse.findIndex(subject);
    assert.eq(true, actual.isSome(), 'Expected "' + name + '" to have a parent.');
    assert.eq(expected, actual.getOrDie(), 'Expected index of "' + name + '" was: ' + expected + '. Was ' + actual.getOrDie());
  };

  Arr.each([ grandparent ], checkNone);
  checkIndex(0, uncle);
  checkIndex(1, mother);
  checkIndex(0, youngest);
  checkIndex(1, middle);
  checkIndex(2, oldest);

  var checkSiblings = function (expected, subject, direction) {
    var actual = direction(subject);

    var getName = function (e) { return Attr.get(e, 'name'); };

    assert.eq(
      Arr.map(expected, getName),
      Arr.map(actual, getName)
    );
  };

  var aunt = node('aunt');
  var c1 = node('c1');
  var c2 = node('c2');
  var c3 = node('c3');
  var c4 = node('c4');
  var c5 = node('c5');
  var c6 = node('c6');
  InsertAll.append(aunt, [ c1, c2, c3, c4, c5, c6 ]);

  checkSiblings([ c1, c2 ],     c3, Traverse.prevSiblings);
  checkSiblings([ c4, c5, c6 ], c3, Traverse.nextSiblings);

  checkSiblings([ c1 ],         c2, Traverse.prevSiblings);
  checkSiblings([ c6 ],         c5, Traverse.nextSiblings);

  var el = Element.fromTag('div');
  assert.eq(true, Traverse.owner(el).dom() === document);
  assert.eq(true, Traverse.defaultView(el).dom() === window);

  var n = node('n');
  var c1 = node('c1');
  var c2 = node('c2');
  var t1 = textNode('t1');
  var t2 = textNode('t2');
  var t3 = textNode('t3');
  InsertAll.append(n, [ c1, t1, c2, t2, t3 ]);
  assert.eq(0, Traverse.childNodesCount(c1));
  assert.eq(0, Traverse.childNodesCount(t1));
  assert.eq(5, Traverse.childNodesCount(n));
  assert.eq(false, Traverse.hasChildNodes(t1));
  assert.eq(true, Traverse.hasChildNodes(n));
});

import useUpdatedRef from './useUpdatedRef';
import { useEffect } from 'react';

/**
 * Attach a


ermission =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (!isGranted && denied <= 2) {
                denied++
                requestPermission()
            }
        }

    fun requestPermission(){
        // Only request on Android 13+ (API 33+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                requestNotificationPermission.launch(android.Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }

    var isKeyboardVisible = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        requestPermission()

        if (intent.hasExtra("awake_intent")){
            moveTaskToBack(true)
        }

    }

    var wasKeyboardOpen = false
    override fun onPause() {
        super.onPause()
        wasKeyboardOpen = isKeyboardVisible
    }

    override fun onResume() {
        super.onResume()

        val rootView = findViewById<View>(android.R.id.content)
        rootView.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            rootView.getWindowVisibleDisplayFrame(rect)
            val screenHeight = rootView.rootView.height
            val keypadHeight = screenHeight - rect.bottom
            val isVisible = keypadHeight > screenHeight * 0.15

            isKeyboardVisible = isVisible
        }

        if (wasKeyboardOpen && !isKeyboardVisible){
            terminalView.get()?.let {
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(it, InputMethodManager.SHOW_IMPLICIT)
            }
        }
    }
}package com.rohitss.aacmvi.util

import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

/**
 * A lifecycle-aware observable that sends only new updates after subscription, used for events like
 * Toast and Snackbar messages; in our case ViewEffect.
 *

 * This avoids a common problem with events: on configuration change (like rotation) an update
 * can be emitted if the observer is active. This LiveData only calls the observable if there's an
 * explicit call to setValue() or call().
 *

 *
 * Note: ONLY ONE OBSERVER IS GOING TO BE NOTIFIED OF CHANGES AND THERE IS NO GUARANTEE WHICH ONE.
 *
 * @see google-architecture-samples
 *
 */

class SingleLiveEvent<T> : MutableLiveData<T>() {
    private val pending = AtomicBoolean(false)

    @MainThread
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, { t ->
            if (pending.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }

    @MainThread
    override fun setValue(t: T?) {
        pending.set(true)
        super.setValue(t)
    }
}package com.rohitss.mvr.mainscreen

import android.app.Application
import androidx.lifecycle.viewModelScope
import com.rohitss.aacmvi.common.AacMviViewModel
import com.rohitss.mvr.LCE
import com.rohitss.mvr.repository.NewsItem
import com.rohitss.mvr.repository.NewsRepository
import kotlinx.coroutines.launch

class MainActVM(application: Application) :
    AacMviViewModel<MainViewState, MainViewEffect, MainViewEvent>(application)


) {
	resetCache()
	lock.Lock()
	defer lock.Unlock()
	var err error

	// Populate trie cache, if not initialized yet.
	if t == nil {
		t, err = trie.NewTrie(params.BeaconConfig().DepositContractTreeDepth)
		if err != nil {
			return nil, nil, errors.Wrap(err, "failed to create new trie")
		}
	}

	// If more deposits requested than cached, generate more.
	if numDeposits > uint64(len(cachedDeposits)) {
		numExisting := uint64(len(cachedDeposits))
		numRequired := numDeposits - uint64(len(cachedDeposits))
		// Fetch the required number of keys.
		secretKeys, publicKeys, err := interop.DeterministicallyGenerateKeys(numExisting, numRequired+1)
		if err != nil {
			return nil, nil, errors.Wrap(err, "could not create deterministic keys: ")
		}
		privKeys = append(privKeys, secretKeys[:len(secretKeys)-1]...)

		// Create the new deposits and add them to the trie. Always use the first validator to create deposit
		for i := uint64(0); i < numRequired; i++ {
			withdrawalCreds := hash.Hash(publicKeys[1].Marshal())
			withdrawalCreds[0] = params.BeaconConfig().BLSWithdrawalPrefixByte

			depositMessage := &ethpb.DepositMessage{
				PublicKey:             publicKeys[1].Marshal(),
				Amount:                params.BeaconConfig().MaxEffectiveBalance,
				WithdrawalCredentials: withdrawalCreds[:],
			}

			domain, err := signing.ComputeDomain(params.BeaconConfig().DomainDeposit, nil, nil)
			if err != nil {
				return nil, nil, errors.Wrap(err, "could not compute domain")
			}
			root, err := depositMessage.HashTreeRoot()
			if err != nil {
				return nil, nil, errors.Wrap(err, "could not get signing root of deposit data")
			}
			sigRoot, err := (&ethpb.SigningData{ObjectRoot: root[:], Domain: domain}).HashTreeRoot()
			if err != nil {
				return nil, nil, errors.Wrap(err, "could not get signing root of deposit data and domain")
			}
			// Always use the same validator to sign
			depositData := &ethpb.Deposit_Data{
				PublicKey:             depositMessage.PublicKey,
				Amount:                depositMessage.Amount,
				WithdrawalCredentials: depositMessage.WithdrawalCredentials,
				Signature:             secretKeys[1].Sign(sigRoot[:]).Marshal(),
			}
			deposit := &ethpb.Deposit{
				Data: depositData,
			}
			cachedDeposits = append(cachedDeposits, deposit)

			hashedDeposit, err := deposit.Data.HashTreeRoot()
			if err != nil {
				return nil, nil, errors.Wrap(err, "could not tree hash deposit data")
			}

			if err = t.Insert(hashedDeposit[:], int(numExisting+i)); err != nil {
				return nil, nil, err
			}
		}
	}

	// lint:ignore uintcast -- test code
	depositTrie, _, err := DeterministicDepositTrie(int(numDeposits))
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to create deposit trie")
	}
	requestedDeposits := cachedDeposits[:numDeposits]
	for i := range requestedDeposits {
		proof, err := depositTrie.MerkleProof(i)
		if err != nil {


多个，则请求指令格式应为 `VerbNouns`，如 `GetUsers`、`DeleteUsers`。

### 公共参数
**所有的公共参数均放在请求头中**，对于非 Web 标准的请求头名，则以 `X-` 作为其前缀，如 `X-User-Id`。

### API Version
API Version 可以放在 **URL Path** 中（如 `/v1`），也可以作为 **公共参数** 放在 **请求头** 中（请求头名为 `X-Version` 或 `X-Api-Version`）。

### 认证信息
**认证信息被视为公共参数，因此，则放在请求头中。** 为了兼容 Web 标准，则将认证信息放在请求头 `Authorization` 中，参数值格式为 `AuthMethod AuthInfoValue`。其中，`AutMethod`表示认证方法（如 `Basic`、`Token`、`OAuth2`、`HMAC-SHA256` 等），`AuthInfoValue` 表示完成认证所需要的信息。

对于类似 API 网关的代理，认证通过后，当转发给后端服务时，则可将解析出来的认证信息（如：登录者ID、登录者名字、登录者的角色类型等）放在请求头中（请求头名分别为 `X-Operator-Id`、`X-Operator-Name`、`X-Operator-Role-Type`等），然后再转发给后端服务；这样，后端服务在接收到请求时，则可以直接从请求头中取出相关的用户信息。

## 应答
### 状态码
无论应答是成功还是失败，状态码均返回 200。

### 应答Body
**请求的应答结果放在 Body 中**，应答头 `Content-Type` 说明 Body 数据的格式，建议使用 JSON 格式。

```json
{
    "RequestId": "string",
    "Data": object,
    "Error": {
        "Code": "string",
        "Message": "string"
    }
}
```

字段名     |  类型  | 说明
----------|---------|---------
RequestId | string | 服务器返回给请求者的唯一请求ID（可以使用 `UUID`），当前发生错误时，请求者可以提供该ID以便快速排查具体的错误原因。对于长时间操作，可以先返回应答，并进行异步处理；而请求者则可以根据此ID查询处理结果。
Data      | object | 当处理成功时，返回给请求者的具体应答结果，它可以是任何值，不过建议以 JSON 表示。**如果请求处理失败或没有答应结果，则可被忽略或为 `null`**。
Error     | object | **如果存在，则表示请求处理失败**，其中的参数字段信息则表示失败的原因，参见下表。

字段名   |  类型  |  说明
--------|--------|---------
Code    | string | **表示错误码，也即是错误的类型**，如 `InvalidParameter`、`AuthFailure`，根据错误类型，可以快速区分不同的错误。它也可以支持子类型，与主类型以英文点进行分隔，如 `AuthFailure.TokenFailure`、`AuthFailure.InvalidCookie`。
Message | string | **表示具体的错误信息，可以在浏览器中显示给用户**。该字段可以缺失或为空；如果缺失或为空，则可根据 `Code` 字段的错误类型来显示预定义的通用错误信息。注：如果无法识别子类型，则可按主类型表示的错误信息显示。

#### 应答成功样例
##### 没有应答数据
```json
{
    "RequestId": "9162ED80-4DD4-4ACC-B7CD-6DE85


"Monocromo + Spesso"

-- Text aligns.
obj = L.TEXT_ALIGNS
obj[1] = "Sinistra"
obj[2] = "Centro"
obj[3] = "Destra"

------------------------------
-- Sound info
------------------------------

obj = L.SOUNDS
obj["MSBT Low Mana"]	= "MSBT Mana Basso"
obj["MSBT Low Health"]	= "MSBT Vita bassa"
obj["MSBT Cooldown"]	= "MSBT Cooldown"

------------------------------
-- Animation style info
------------------------------

-- Animation styles
obj = L.ANIMATION_STYLE_DATA
obj["Angled"]		= "Angolare"
obj["Horizontal"]	= "Orizzontale"
obj["Parabola"]		= "Parabola"
obj["Strai


et': IMovie[]
  'load_popular_movies/set/loading': undefined
  'load_popular_movies/set/failed': undefined
  'load_popular_movies/next_page': IMovie[]
}

const initialState: PopularMovieState = {
  popularMovies: {
    movies: [],
    page: 1,
    loading: false,
    failed: false,
  },
}

export const popularMovies: StoreonModule<PopularMovieState, PopularMovieEvents> = (store) => {
  store.on('@init', () => initialState)
  store.on('load_popular_movies/set', (state, movies) => {
    return {
      ...state,
      popularMovies: {
        movies,
        page: 2,
        loading: false,
        failed: false,
      },
    }
  })
  store.on('load_popular_movies/set/loading', (state) => ({
    ...state,
    popularMovies: {
      movies: state.popularMovies.movies,
      page: state.popularMovies.page,
      loading: true,
      failed: false,
    },
  }))
  store.on('load_popular_movies/set/failed', (state) => ({
    ...state,
    popularMovies: {
      movies: state.popularMovies.movies,
      page: state.popularMovies.page,
      loading: false,
      failed: true,
    },
  }))
  store.on('load_popular_movies/next_page', (state, nextMovies) => ({
    ...state,
    popularMovies: {
      movies: [...state.popularMovies.movies, ...nextMovies],
      page: state.popularMovies.page + 1,
      loading: false,
      failed: false,
    },
  }))
}

export const usePopularMovies = () =>
  useStoreon<PopularMovieState, PopularMovieEvents>('popularMovies')
import { BehaviorSubject, Observable } from 'rxjs'
import axios from 'axios'
import to from 'await-to-js'

import { UserLogin, UserDetails } from '../../common/types'
import { useObservable } from 'rxjs-hooks'
import { AUTH_PATH, LOGIN_PATH, LOGOUT_PATH } from '../../common/config'

export interface AuthServiceInterface {
  login: (userLogin: UserLogin) => Promise<false|UserDetails>;
  logout: () => Promise<boolean>;
  useCurrentUser: () => UserDetails|null;
  complete: () => void;
}

export class AuthService {
  private currentUserSubject = new BehaviorSubject<UserDetails | null>(null);
  private currentUser$: Observable<UserDetails | null>;

  constructor () {
    this.currentUser$ = this.currentUserSubject
    this.attemptAuthentication()
  }

  complete () {
    this.currentUserSubject.complete()
  }

  private async attemptAuthentication () {
    const [, response] = await to(axios.get<UserDetails>(AUTH_PATH))
    console.log('attempting auth')
    if (!response) {
      return
    }
    this.currentUserSubject.next(response.data as UserDetails)
  }

  async login (userLogin: UserLogin): Promise<UserDetails|false> {
    console.log('logging in')
    const [err, res] = await to(axios.post(LOGIN_PATH, userLogin))
    if (err) {
      this.currentUserSubject.next(null)
      return false
    }
    const { data } = res
    this.currentUserSubject.next(data)
    return data
  }

  logout = async () => {
    const res = await axios.post(LOGOUT_PATH)
    this.currentUserSubject.next(null)
    return res.status === 200
  }

  useCurrentUser () {
    return useObservable(() => this.currentUser$, this.currentUserSubject.value)
  }
}
/**
 * 组织类型
 */
export enum OrgTypeDic {
    /** 集团 */
    Group = 1,
    /** 公司 */
    Corp = 20,
    /** 政府单位 */


subList(node1Index + 1, positions.size)
                .indexOfFirst { it.equalsInOsm(insertIntoWay.pos2) }
            if (node2Index == -1) throw ConflictException("Node in way at insert position has been moved or deleted")
            // index 0 because of subList starting at node1Index + 1
            if (node2Index != 0) throw ConflictException("Other nodes have been inserted into the way")

            val nodeIds = way.nodeIds.toMutableList()
            nodeIds.add(node1Index + 1, newNode.id)

            editedWays.add(way.copy(nodeIds = nodeIds, timestampEdited = nowAsEpochMilliseconds()))
        }

        return MapDataChanges(creations = listOf(newNode), modifications = editedWays)
    }

    override fun createReverted(idProvider: ElementIdProvider) =
        RevertCreateNodeAction(createNode(idProvider), insertIntoWays.map { it.wayId })

    private fun createNode(idProvider: ElementIdProvider) =
        Node(idProvider.nextNodeId(), position, tags, 1, nowAsEpochMilliseconds())
}

/** Inserting the node into the given [wayId] in between the nodes at the given positions
 *  [pos1] and [pos2].
 *  Not the node ids but the positions are given for better conflict checking - if any of the two
 *  nodes have been moved, that's a conflict. */
@Serializable
data class InsertIntoWayAt(val wayId: Long, val pos1: LatLon, val pos2: LatLon)

fun String.serbianCyrillicToLatin() =
    asSequence().joinToString("") { serbianCyrillicToLatin[it] ?: it.toString() }

private val serbianCyrillicToLatin = mapOf(
    'А' to "A",  'а' to "a",
    'Б' to "B",  'б' to "b",
    'В' to "V",  'в' to "v",
    'Г' to "G",  'г' to "g",
    'Д' to "D",  'д' to "d",
    'Ђ' to "Đ",  'ђ' to "đ",
    'Е' to "E",  'е' to "e",
    'Ж' to "Ž",  'ж' to "ž",
    'З' to "Z",  'з' to "z",
    'И' to "I",  'и' to "i",
    'Ј' to "J",  'ј' to "j",
    'К' to "K",  'к' to "k",
    'Л' to "L",  'л' to "l",
    'Љ' to "Lj", 'љ' to "lj",
    'М' to "M",  'м' to "m",
    'Н' to "N",  'н' to "n",
    'Њ' to "Nj", 'њ' to "nj",
    'О' to "O",  'о' to "o",
    'П' to "P",  'п' to "p",
    'Р' to "R",  'р' to "r",
    'С' to "S",  'с' to "s",
    'Т' to "T",  'т' to "t",
    'Ћ' to "Ć",  'ћ' to "ć",
    'У' to "U",  'у' to "u",
    'Ф' to "F",  'ф' to "f",
    'Х' to "H",  'х' to "h",
    'Ц' to "C",  'ц' to "c",
    'Ч' to "Č",  'ч' to "č",
    'Џ' to "Dž", 'џ' to "dž",
    'Ш' to "Š",  'ш' to "š",
)
import com.esotericsoftware.yamlbeans.YamlConfig
import com.esotericsoftware.yamlbeans.YamlReader
import com.esotericsoftware.yamlbeans.YamlWriter
import kotlinx.serialization.json.Json
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import java.io.File
import java.io.StringWriter
import java.net.URL

/** generate [country code].yml files from [property].yml files, for example
 *  popularSports.yml:
 *  DE: [soccer, tennis]
 *
 *  becomes
 *
 *  DE.yml:
 *  popularSports: [soccer, tennis]  */
open class GenerateMetadataByCountryTask : DefaultTask() {

    @get:Input lateinit var sourceDir: String
    @get:Input lateinit var targetDir: String

    @Ta


.Module
import net.minusmc.minusbounce.features.module.ModuleCategory
import net.minusmc.minusbounce.features.module.ModuleInfo
import net.minusmc.minusbounce.features.module.modules.combat.KillAura
import net.minusmc.minusbounce.utils.MovementUtils
import net.minusmc.minusbounce.utils.RotationUtils
import net.minusmc.minusbounce.utils.render.ColorUtils
import net.minusmc.minusbounce.utils.render.RenderUtils
import net.minusmc.minusbounce.value.BoolValue
import net.minusmc.minusbounce.value.FloatValue
import net.minusmc.minusbounce.value.IntegerValue
import net.minusmc.minusbounce.value.ListValue
import org.lwjgl.opengl.GL11
import java.awt.Color
import kotlin.math.cos
import kotlin.math.sin

@ModuleInfo(name = "TargetStrafe", spacedName = "Target Strafe", description = "Strafe around your target. (Require Fly or Speed to be enabled)", category = ModuleCategory.MOVEMENT)
class TargetStrafe : Module() {
    val radius = FloatValue("Radius", 2.0f, 0.1f, 4.0f, "m")
    private val render = BoolValue("Render", true)
    private val alwaysRender = BoolValue("Always-Render", true) { render.get() }
    private val modeValue = ListValue("KeyMode", arrayOf("Jump", "None"), "None")
    private val safewalk = BoolValue("SafeWalk", true)
    private val thirdPerson = BoolValue("ThirdPerson", true)
    private val colorType = ListValue("Color", arrayOf("Custom", "Dynamic", "Rainbow", "Rainbow2", "Sky", "Fade"), "Custom")
    private val redValue = IntegerValue("Red", 255, 0, 255)
    private val greenValue = IntegerValue("Green", 255, 0, 255)
    private val blueValue = IntegerValue("Blue", 255, 0, 255)
    private val saturationValue = FloatValue("Saturation", 0.7F, 0F, 1F)
    private val brightnessValue = FloatValue("Brightness", 1F, 0F, 1F)
    private val accuracyValue = IntegerValue("Accuracy", 0, 0, 59)
    private val thicknessValue = FloatValue("Thickness", 1F, 0.1F, 5F)
    private val outLine = BoolValue("Outline", true)
    private val expMode = BoolValue("ExperimentalSpeed", false)
    private lateinit var killAura: KillAura
    private lateinit var speed: Speed
    private lateinit var fly: Fly

    var direction = 1
    private var lastView = 0
    private var hasChangedThirdPerson = true

    private var hasModifiedMovement = false

    override fun onInitialize() {
        speed = MinusBounce.moduleManager.getModule(Speed::class.java) as Speed
        fly = MinusBounce.moduleManager.getModule(Fly::class.java) as Fly
        killAura = MinusBounce.moduleManager.getModule(KillAura::class.java) as KillAura
    }

    override fun onEnable() {
        hasChangedThirdPerson = true
        lastView = mc.gameSettings.thirdPersonView
    }

    @EventTarget
    fun onMotion(event: MotionEvent) {
        if (thirdPerson.get()) { // smart change back lol
            if (canStrafe) {
                if (hasChangedThirdPerson) lastView = mc.gameSettings.thirdPersonView
                mc.gameSettings.thirdPersonView = 1
                hasChangedThirdPerson = false
            } else if (!hasChangedThirdPerson) {
                mc.gameSettings.thirdPersonView = lastView
                hasChangedThirdPerson = true
            }
        }

        if (event.eventState == EventState.PRE) {
            if (mc.thePlayer.isCollidedHorizontally)
                this.direction = -this.direction

            if (mc.gameSettings.keyBindLeft.pressed)


eMinusAmount);

        switch (f.name.toLowerCase()) {
          case GRAYSCALE:
            // Formula from: https://www.w3.org/TR/filter-effects-1/#grayscaleEquivalent
            matrix5 = _multiplyMatrix5(matrix5, <double>[
              (0.2126 + 0.7874 * oneMinusAmount),
              (0.7152 - 0.7152 * oneMinusAmount),
              (0.0722 - 0.0722 * oneMinusAmount),
              0,
              0,
              (0.2126 - 0.2126 * oneMinusAmount),
              (0.7152 + 0.2848 * oneMinusAmount),
              (0.0722 - 0.0722 * oneMinusAmount),
              0,
              0,
              (0.2126 - 0.2126 * oneMinusAmount),
              (0.7152 - 0.7152 * oneMinusAmount),
              (0.0722 + 0.9278 * oneMinusAmount),
              0,
              0,
              0,
              0,
              0,
              1,
              0,
              0,
              0,
              0,
              0,
              1
            ]);
            break;
          case SEPIA:
            // Formula from: https://www.w3.org/TR/filter-effects-1/#sepiaEquivalent
            matrix5 = _multiplyMatrix5(matrix5, <double>[
              (0.393 + 0.607 * oneMinusAmount),
              (0.769 - 0.769 * oneMinusAmount),
              (0.189 - 0.189 * oneMinusAmount),
              0,
              0,
              (0.349 - 0.349 * oneMinusAmount),
              (0.686 + 0.314 * oneMinusAmount),
              (0.168 - 0.168 * oneMinusAmount),
              0,
              0,
              (0.272 - 0.272 * oneMinusAmount),
              (0.534 - 0.534 * oneMinusAmount),
              (0.131 + 0.869 * oneMinusAmount),
              0,
              0,
              0,
              0,
              0,
              1,
              0,
              0,
              0,
              0,
              0,
              1
            ]);
            break;
        }
      }
    }

    // Each line is R|G|B|A|1, the last line not works.
    // See https://www.w3.org/TR/filter-effects-1/#funcdef-filter-grayscale
    return matrix5 != null ? ColorFilter.matrix(matrix5.sublist(0, 20)) : null;
  }

  // Get the image filter.
  ImageFilter? _parseImageFilters(List<CSSFunctionalNotation> functions) {
    if (functions.isNotEmpty) {
      for (int i = 0; i < functions.length; i++) {
        CSSFunctionalNotation f = functions[i];
        switch (f.name.toLowerCase()) {
          case BLUR:
            CSSLengthValue length = CSSLength.parseLength(f.args.first, this, FILTER);
            double amount = length.computedValue;
            ImageFilter imageFilter = ImageFilter