) {
				// No self-edges.
				continue
			}
			edgeInA := a.Edge(u.A.ID(), v.A.ID()) != nil
			edgeInB := b.Edge(u.B.ID(), v.B.ID()) != nil
			if (edgeInA && edgeInB) || (!edgeInA && !edgeInB) {
				dst.SetEdge(dst.NewEdge(u, v))
			}
		}
	}
}

func BenchmarkProduct(b *testing.B) {
	for seed, bench := range []struct {
		name    string
		product func(dst graph.Builder, a, b graph.Graph)
		len     []int
	}{
		{"Cartesian", Cartesian, []int{50, 100}},
		{"Cartesian naive", naiveCartesian, []int{50, 100}},
		{"CoNormal", CoNormal, []int{50}},
		{"CoNormal naive", naiveCoNormal, []int{50}},
		{"Lexicographical", Lexicographical, []int{50}},
		{"Lexicographical naive", naiveLexicographical, []int{50}},
		{"Modular", Modular, []int{50}},
		{"Modular naive", naiveModular, []int{50}},
		{"Strong", Strong, []int{50}},
		{"Strong naive", naiveStrong, []int{50}},
		{"Tensor", Tensor, []int{50}},
		{"Tensor naive", naiveTensor, []int{50}},
	} {
		for _, p := range []float64{0.05, 0.25, 0.5, 0.75, 0.95} {
			for _, n := range bench.len {
				src := rand.NewPCG(uint64(seed), uint64(seed))
				b.Run(fmt.Sprintf("%s %d-%.2f", bench.name, n, p), func(b *testing.B) {
					g1 := gnp(n, p, src)
					g2 := gnp(n, p, src)
					b.ResetTimer()
					for i := 0; i < b.N; i++ {
						dst := simple.NewDirectedGraph()
						bench.product(dst, g1, g2)
					}
				})
			}
		}
	}
}

func gnp(n int, p float64, src rand.Source) *simple.UndirectedGraph {
	g := simple.NewUndirectedGraph()
	err := gen.Gnp(g, n, p, src)
	if err != nil {
		panic(fmt.Sprintf("gnp: bad test: %v", err))
	}
	return g
}
// Copyright ©2014 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package topo

import (
	"reflect"
	"slices"
	"testing"

	"gonum.org/v1/gonum/graph"
	"gonum.org/v1/gonum/graph/simple"
	"gonum.org/v1/gonum/internal/order"
)

type interval struct{ start, end int }

var tarjanTests = []struct {
	g []intset

	ambiguousOrder []interval
	want           [][]int64

	sortedLength      int
	unorderableLength int
	sortable          bool
}{
	{
		g: []intset{
			0: linksTo(1),
			1: linksTo(2, 7),
			2: linksTo(3, 6),
			3: linksTo(4),
			4: linksTo(2, 5),
			6: linksTo(3, 5),
			7: linksTo(0, 6),
		},

		want: [][]int64{
			{5},
			{2, 3, 4, 6},
			{0, 1, 7},
		},

		sortedLength:      1,
		unorderableLength: 2,
		sortable:          false,
	},
	{
		g: []intset{
			0: linksTo(1, 2


train_model = train_combined[TRANSFORMED_TARGET_COL]\\n\\n    # Handle cases where training data becomes empty after processing (e.g., very early folds)\\n    if X_train_model.empty or y_train_model.empty:\\n        print(\\"Warning: Training data is empty after preprocessing. Returning fallback predictions (all zeros).\\")\\n        predictions_df = pd.DataFrame(index=test_x.index, columns=[f'quantile_{q}' for q in QUANTILES])\\n        for q_col in [f'quantile_{q}' for q in QUANTILES]:\\n            predictions_df[q_col] = 0\\n        return predictions_df\\n\\n\\n    # Handle categorical features for LightGBM and XGBoost. Only 'location' is truly categorical.\\n    all_location_categories = pd.unique(pd.concat([X_train_model[LOCATION_COL], test_x_processed[LOCATION_COL]]))\\n\\n    # Prepare X_train for LightGBM (categorical Dtype)\\n    X_train_lgbm = X_train_model.copy()\\n    # Ensure all location strings are explicitly treated as categories, including potentially unseen ones in test_x\\n    X_train_lgbm[LOCATION_COL] = X_train_lgbm[LOCATION_COL].astype(pd.CategoricalDtype(categories=all_location_categories))\\n\\n    # Prepare X_train for XGBoost (integer encoding)\\n    # Create mapping from original location string to a unique integer ID\\n    location_to_int = {loc: i for i, loc in enumerate(all_location_categories)}\\n\\n    # Define the integer for unknown locations (if any, though should be rare with current method)\\n    # This ensures all mapped location IDs are non-negative.\\n    unknown_location_int = len(all_location_categories)\\n\\n    X_train_xgb = X_train_model.copy()\\n    # Map location strings to integers. If any location is not in \`all_location_categories\`, map to \`unknown_location_int\`.\\n    X_train_xgb[LOCATION_COL] = X_train_xgb[LOCATION_COL].map(location_to_int).fillna(unknown_location_int).astype(int)\\n\\n\\n    # Store the final column order from training data to ensure consistency during prediction\\n    # This refers to the original X_train_model columns, before type conversions for specific models\\n    X_train_model_cols = X_train_model.columns.tolist()\\n\\n    # Identify categorical feature column names for LightGBM (only LOCATION_COL)\\n    categorical_feature_names = [col for col in CATEGORICAL_FEATURES_LIST if col in X_train_model_cols]\\n\\n    # --- 4. Model Training (Ensemble of LightGBM and XGBoost models) ---\\n    models = {q: {} for q in QUANTILES}\\n\\n    for q in QUANTILES:\\n        if 'lgbm' in ensemble_model_types and n_lgbm_ensemble_members > 0:\\n            models[q]['lgbm'] = []\\n            for i in range(n_lgbm_ensemble_members):\\n                lgbm_model_params_i = lgbm_params.copy()\\n                lgbm_model_params_i['alpha'] = q # Set quantile for LGBM\\n                lgbm_model_params_i['random_state'] = lgbm_params['random_state'] + i # Vary seed for ensemble members\\n\\n                lgbm_model = LGBMRegressor(**lgbm_model_params_i)\\n                lgbm_model.fit(X_train_lgbm, y_train_model,\\n                               categorical_feature=categorical_feature_names)\\n                models[q]['lgbm'].append(lgbm_model)\\n\\n        if 'xgb' in ensemble


Source+Code+Pro');

/*!
 * Bootstrap v2.3.2
 *
 * Copyright 2013 Twitter, Inc
 * Licensed under the Apache License v2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Designed and built with all the love in the world by @mdo and @fat.
 */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}a:hover,a:active{outline:0}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}#map_canvas img,.google-maps img{max-width:none}button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle}button,input{*overflow:visible;line-height:normal}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20p


Ends (...ends: string[]) {
		this.end.push(...ends);
		return this;
	}

	public clone () {
		return new Match(/* this.match */)
			.setStart(...this.start)
			.setEnd(...this.end);
	}
}
namespace SegundoParcial{

    export class Animal {
        public _ETipo:ETipoMascotas;
        public _cantPatas:number;
        public _edad:number;

        constructor(edad: number, ETipo: ETipoMascotas, cantPatas: number) {
            this._ETipo = ETipo;
            this._cantPatas = cantPatas;
            this._edad = edad;
        }

        get ETipo(): ETipoMascotas {
            return this._ETipo;
        }

        get CantPatas() :number {
            return this._cantPatas;
        }

        set CantPatas(cantPatas :number) {
            this._cantPatas = cantPatas;
        }

        get Edad() :number {
            return this._edad;
        }

        set Edad(edad :number) {
            this._edad = edad;
        }

    }
} //namespace// Type definitions for jquery.dynatable v0.3.1
// Project: https://github.com/fanderzon/dynatable#readme
// Definitions by: François Massart <https://github.com/francoismassart>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3

/// <reference types="jquery" />

interface JQuery {
    /**
    */
    dynatable: JQueryDynatable.Dynatable;
}

/** Static members of jQuery (those on $ and jQuery themselves) */
interface JQueryStatic {
    /**
     * Global dynatable plugin setting defaults
     *
     * @param options The configuration options to be set globally
     */
    dynatableSetup(options: JQueryDynatable.Options): void;
}

declare namespace JQueryDynatable {
    interface Features {
        /**
         * Enable the pagination feature
         *
         * @default true
         */
        paginate?: boolean | undefined;
        /**
         * Enable the sorting feature
         *
         * @default true
         */
        sort?: boolean | undefined;
        /**
         * Enable the pushState feature
         * Used to update the page URL parameters and cache the query result for the browser's forward- and back-buttons
         *
         * @default true
         */
        pushState?: boolean | undefined;
        /**
         * Enable the search feature
         *
         * @default true
         */
        search?: boolean | undefined;
        /**
         * Enable the recordCount feature
         * When pagination is enabled, dynatable will also show the currently displayed records and the total number of records
         *
         * @default true
         */
        recordCount?: boolean | undefined;
        /**
         * Enable the perPageSelect feature
         * The perPageSelect will insert a form control filled with the options from `perPageOptions`
         *
         * @default true
         */
        perPageSelect?: boolean | undefined;
    }
    interface Column {
        index: number;
        label: string;
        /**
         * Determined by the `data-dynatable-column` or using the `defaultColumnIdStyle`
         *
         * @example
         * // Using the `defaultColumnIdStyle` of `camelCase`
         * // `<th>Favorite Music</th>` would be translated into the id `favoriteMusic`
         */
        id: string;
        /**
         * Function that returns the cell data to be written inside the cell
         *
         * @param record A data object representing the current line of data
         * @return The data for the current cell
         *
         * @example
         * function exampleAttributeWriter(record) {
         *     return record[this.id];
         * };
         */
        attributeWriter: (record: any) => any;
        /**
         * Function that interprets the cell html data in order to convert i


  (super.noSuchMethod(
        Invocation.method(
          #call,
          [params],
        ),
        returnValue: _i5.Future<_i3.Either<String, bool>>.value(
            _FakeEither_1<String, bool>(
          this,
          Invocation.method(
            #call,
            [params],
          ),
        )),
      ) as _i5.Future<_i3.Either<String, bool>>);
}

/// A class which mocks [UpdateUserUseCase].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockUpdateUserUseCase extends _i1.Mock implements _i8.UpdateUserUseCase {
  MockUpdateUserUseCase() {
    _i1.throwOnMissingStub(this);
  }

  @override
  _i2.UserRepository get userRepository => (super.noSuchMethod(
        Invocation.getter(#userRepository),
        returnValue: _FakeUserRepository_0(
          this,
          Invocation.getter(#userRepository),
        ),
      ) as _i2.UserRepository);

  @override
  _i5.Future<_i3.Either<String, bool>> call(_i8.UpdateUserParams? params) =>
      (super.noSuchMethod(
        Invocation.method(
          #call,
          [params],
        ),
        returnValue: _i5.Future<_i3.Either<String, bool>>.value(
            _FakeEither_1<String, bool>(
          this,
          Invocation.method(
            #call,
            [params],
          ),
        )),
      ) as _i5.Future<_i3.Either<String, bool>>);
}

/// A class which mocks [DeleteUserUseCase].
///
/// See the documentation for Mockito's code generation for more information.
// ignore: must_be_immutable
class MockDeleteUserUseCase extends _i1.Mock implements _i9.DeleteUserUseCase {
  MockDeleteUserUseCase() {
    _i1.throwOnMissingStub(this);
  }

  @override
  _i2.UserRepository get userRepository => (super.noSuchMethod(
        Invocation.getter(#userRepository),
        returnValue: _FakeUserRepository_0(
          this,
          Invocation.getter(#userRepository),
        ),
      ) as _i2.UserRepository);

  @override
  _i5.Future<_i3.Either<String, bool>> call(_i9.DeleteUserParams? params) =>
      (super.noSuchMethod(
        Invocation.method(
          #call,
          [params],
        ),
        returnValue: _i5.Future<_i3.Either<String, bool>>.value(
            _FakeEither_1<String, bool>(
          this,
          Invocation.method(
            #call,
            [params],
          ),
        )),
      ) as _i5.Future<_i3.Either<String, bool>>);
}
// Mocks generated by Mockito 5.4.3 from annotations
// in clean_architecture_getx/test/features/todo/data/repositories/todo_repository_impl_test.dart.
// Do not manually edit this file.

// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;

import 'package:clean_architecture_getx/features/todo/data/datasources/todo_remote_data_source.dart'
    as _i2;
import 'package:clean_architecture_getx/features/todo/data/models/todo.dart'
    as _i4;
import 'package:clean_architecture_getx/features/todo/domain/entities/todo_entity.dart'
    as _i5;
import 'package:mockito/mockito.dart' as _i1;

// ignore_for_file: type=lint
// ignore_for_file: avoid_red


nd(le_bytes[0], offset + 1)
    offsets = list(filter(lambda x: validate(m, x, le_bytes, num_lines), offsets))

    # Replace with `new_le_bytes`
    for offset in offsets:
        for i in range(num_lines // 2):
            m[offset + i * 16 : offset + i * 16 + 16] = new_le_bytes[i]

def process(path):
    if os.getenv("DG_PRINT_REG_REUSE", None):
        print(f"Processing {path}")
    output = run_cuobjdump(path)
    segments = extract_ffma(output)
    with open(path, "r+b") as f:
        mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE)
        for segment in segments:
            modify_segment(mm, *segment)
        mm.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Interleave FFMA reg reuse")
    parser.add_argument("--so", help="Path to the SO file")
    args = parser.parse_args()

    process(args.so)


uct"

@Component
class StreamsListener {
    @Bean
    fun streams(builder: StreamsBuilder): KStream<String, String> {
        val inputStream = builder.stream<String, String>(INPUT_TOPIC_NAME)
        inputStream
            .map { _, v -> KeyValue(JsonUtils.getProductId(v), JsonUtils.getAmount(v)) }
            .groupByKey(Grouped.with(Serdes.Long(), Serdes.Long()))
            .windowedBy(TimeWindows.of(Duration.ofMinutes(1)))
            .reduce { value1, value2 -> value1 + value2 }
            .toStream()
            .map { key, value -> KeyValue(key.key(), value) }
            .mapValues(JsonUtils::getSendingJson)
            .selectKey { _, _ -> null }
            .to(OUTPUT_TOPIC_NAME, Produced.with(null, Serdes.String()))

        return inputStream
    }
}package common.factory

import common.extension.getBeanName
import common.extension.isBean
import common.extension.isEnum
import common.extension.isInterface
import mu.KotlinLogging
import java.io.File
import java.net.URLDecoder
import kotlin.reflect.KClass
import kotlin.reflect.full.primaryConstructor

object BeanRegistry {
    private val log = KotlinLogging.logger {}

    fun init(basePackage: String) {
        val targets = scanClasses(basePackage)

        val classMap = targets
            .filter { !it.isEnum() }
            .filter { it.isBean() }
            .filter { !it.isInterface() }
            .associateBy { it.getBeanName() }

        classMap.keys.forEach { name ->
            getOrCreate(name, classMap)
        }
    }

    private fun scanClasses(basePackageName: String): List<KClass<*>> {
        val path = basePackageName.replace('.', '/')

        val classLoader = Thread.currentThread().contextClassLoader

        val resource = classLoader.getResource(path) ?: return emptyList()
        val file = File(URLDecoder.decode(resource.file, "UTF-8"))

        return file.walkTopDown()
            .filter { it.isFile && it.extension == "class" }
            .map {
                val extractPath = it.path.split("$basePackageName/")[1]
                    .split("/")

                val packageName = extractPath.subList(0, extractPath.size - 1)
                    .joinToString(separator = ".")

                val className = "${basePackageName}.${packageName}.${it.nameWithoutExtension}"

                log.info("Scanning class: $className")

                Class.forName(className).kotlin
            }
            .toList()
    }

    private fun getOrCreate(name: String, classMap: Map<String, KClass<*>>): Any {
        Beans.find<Any>(name)?.let {
            return it
        }

        val clazz = classMap[name] ?: throw IllegalArgumentException("No class found for bean: $name")

        if (clazz.constructors.size > 1) {
            throw IllegalArgumentException("Multiple constructors found for bean: $clazz")
        }

        val constructor = clazz.primaryConstructor!!

        val params = constructor.parameters.map {
            val dependencyName = it.type.toString().split(".").last()
            getOrCreate(dependencyName, classMap)
        }.map {
            if (it is Bean<*>) {
                return@map it.originInstance()
            }

            return it
        }.toTypedArray()

        val instance = constructor.call(*params)
        Beans.push(name, Bean(instance, clazz))

        log.info("Registered bean: $name")
        return instance
    }
}

plugins {
    id("com.android.library")
    kotlin("android")
    kotlin("kapt")
    id("kotlin-parcelize")
    id("dagger.hilt.android.plugin")


from llama_index.packs.timescale_vector_autoretrieval.base import (
    TimescaleVectorAutoretrievalPack,
)

__all__ = ["TimescaleVectorAutoretrievalPack"]


              time.sleep(0.1)  # do the sleep to prevent amazon query drop

        def run_onboard(worker):
            worker.persona_generator = persona_generator
            world = PersonaProfileWorld(opt, worker)
            world.parley()
            world.shutdown()

        mturk_manager.set_onboard_function(onboard_function=run_onboard)

        def check_worker_eligibility(worker):
            return True

        def assign_worker_roles(workers):
            for index, worker in enumerate(workers):
                worker.id = mturk_agent_ids[index % len(mturk_agent_ids)]

        def run_conversation(mturk_manager, opt, workers):
            agents = workers[0]
            conv_idx = mturk_manager.conversation_index
            world = Convai2EvalWorld(
                opt=opt,
                agents=[agents],
                range_turn=[int(s) for s in opt['range_turn'].split(',')],
                max_turn=opt['max_turns'],
                max_resp_time=opt['max_resp_time'],
                model_agent_opt=shared_bot_params,
                world_tag='conversation t_{}'.format(conv_idx),
                agent_timeout_shutdown=opt['ag_shutdown_time'],
            )
            world.reset_random()
            while not world.episode_done():
                world.parley()
            world.save_data()

            world.shutdown()

        mturk_manager.start_task(
            eligibility_function=check_worker_eligibility,
            assign_role_function=assign_worker_roles,
            task_function=run_conversation,
        )

    except BaseException:
        raise
    finally:
        mturk_manager.expire_all_unassigned_hits()
        mturk_manager.shutdown()

if __name__ == '__main__':
    main()


       t7,       0
    move          ra,       t6

    vsrari_h_x8 vr0, vr1, vr2, vr3, vr4, vr5, vr6, vr7, \
                vr8, vr9, vr10, vr11, vr12, vr13, vr14, vr15, 1

    LSX_TRANSPOSE8x8_H vr8, vr9, vr10, vr11, vr12, vr13, vr14, vr15, \
                       vr8, vr9, vr10, vr11, vr12, vr13, vr14, vr15, \
                       vr0, vr1, vr2, vr3, vr4, vr5, vr6, vr7
.endif

816:
    ble       t5,    a3,  816816f
.irp i, vr8, vr9, vr10, vr11, vr12, vr13, vr14, vr15
    vxor.v    \i,  \i,  \i
.endr

816816:
    vld_x8 a2, 0, 32, vr0, vr1, vr2, vr3, vr4, vr5, vr6, vr7
    vxor.v        vr23,     vr23,     vr23
.irp i, 0, 32, 64, 96, 128, 160, 192, 224
    vst           vr23,     a2,       \i
.endr

    li.w          t0,       2896
    vreplgr2vr.w  vr23,     t0
.irp i, vr0, vr1, vr2, vr3, vr4, vr5, vr6, vr7
    rect2_lsx     \i,       vr23,     \i
.endr

.ifc \txfm1, identity_

.else
    move          t6,       ra
    jirl          ra,       t7,       0
    move          ra,       t6

.irp i, vr0, vr1, vr2, vr3, vr4, vr5, vr6, vr7
    vsrari.h      \i,       \i,       1
.endr
.endif

    LSX_TRANSPOSE8x8_H vr0, vr1, vr2, vr3, vr4, vr5, vr6, vr7, \
                       vr0, vr1, vr2, vr3, vr4, vr5, vr6, vr7, \
                       vr16, vr17, vr18, vr19, vr20, vr21, vr22, vr23

    move          t6,       ra
    jirl          ra,       t8,       0
    move          ra,       t6

    vor.v   vr0, vr0, vr0
    vsrari_h_x8 vr8, vr9, vr10, vr11, vr12, vr13, vr14, vr15, \
                vr16, vr17, vr18, vr19, vr20, vr21, vr22, vr23, 4
    vsrari_h_x8 vr0, vr1, vr2, vr3, vr4, vr5, vr6, vr7, \
                vr8, vr9, vr10, vr11, vr12, vr13, vr14, vr15, 4

    VLD_DST_ADD_W8_x4 vr8, vr9, vr10, vr11, vr12, vr13, vr14, vr15, \
                      vr16, vr17, vr18, vr19, vr20, vr21, vr22, vr23
endfuncl
.endm

def_base_8x16 identity_
def_base_8x16

.macro DST_ADD_W16 in0, in1, in2, in3, in4, in5, in6, in7, in8, in9,


.com/536495251/LibrarySystem/assets/93455516/c3e2ee8d-9b47-42a5-963a-b2f6f52acd46)

进入系统用户首先登录，输入账号密码并选择管理员登录或读者登录。系统对其身份进行验证，若账号或密码错误则重新登录；若账号和密码正确则进入相应模块进行操作。操作完成后退出系统。

管理员流程图（读者流程图类似）
![image](https://github.com/536495251/LibrarySystem/assets/93455516/2a509be6-9990-4fa6-a47f-0f02f2558e7b)

管理员登录，账号和密码输入正确后，进入管理员操作界面，管理员可在主页、管理图书、管理用户、处理反馈、退出登录,5个模块内进行操作，在主页可以进行借阅管理和归还管理两个操作。
在管理图书模块可以对图书进行添加、下架、修改、查询操作。在管理用户模块可以对用户进行修改用户权限、查询用户、删除用户等操作。
在处理反馈模块可对读者发送的消息进行操作。
最后退出系统。

传统协同过滤推荐算法流程图：
![image](https://github.com/536495251/LibrarySystem/assets/93455516/3b877a4e-58b8-4a3b-989d-cad13d32a845)

协同过滤推荐算法设计：
用户-物品评分关系模型
设计存储用户和物品评分数据的数据库结构，以支持快速检索和更新，设计表示用户-物品评分关系表
 ![image](https://github.com/536495251/LibrarySystem/assets/93455516/4673272c-bd20-4511-83b5-2490ba0cfd30)

算法实现
实现基于用户的协同过滤算法，包括相似度计算、推荐生成等核心步骤。
通过皮尔逊相关系数计算相似度
 ![image](https://github.com/536495251/LibrarySystem/assets/93455516/33798308-8df6-4a93-8107-241132c27e00)

皮尔逊相关系数计算的是两个用户-物品评分向量的相关系数；例如a(6,0,0,8,9);b(0,0,9,9,5)
表示有a，b用户对所有物品（示例数据中为5个物品）的评分向量，计算


 = true // will not copy lines until ); is found
			}
			if strings.Index(line, "`include \"mem_ports.inc\"") >= 0 || // manually added
				strings.Index(line, "`include \"jtframe_game_ports.inc\"") >= 0 /* in main JTFRAME include */ {
				make_inc = true
				break
			}
			if strings.Index(line, "`include \"jtframe_game_ports.inc\"") >= 0 {
				make_inc = true
				break
			}
		}
		f.Close()
		if found {
			ioutil.WriteFile(outpath, bout.Bytes(), 0644)
		}
	}
	if make_inc || args.Make_inc {
		//outpath = filepath.Join(os.Getenv("CORES"), args.Core, "hdl/mem_ports.inc")
		outpath = args.get_path("mem_ports.inc",false)
		ioutil.WriteFile(outpath, buffer.Bytes(), 0644)
	}
	if !found && !make_inc {
		log.Println("jtframe mem: the game file was not updated. jtframe_mem_ports line not found. Declare /* jtframe_mem_ports */ right before the end of the port list in the game module or include mem_ports.inc in the port list.")
	}
	return nil
}

func make_dump2bin( corename string, cfg *MemConfig ) (e error) {
	if len( cfg.Ioctl.Buses )==0 { return }
	tpath := filepath.Join(os.Getenv("JTFRAME"), "src", "jtframe", "mem", "dump2bin.sh")
	t, e := template.New("dump2bin.sh").Funcs(funcMap).Funcs(sprig.FuncMap()).ParseFiles(tpath); if e!=nil { return e }
	var buffer bytes.Buffer
	if e = t.Execute(&buffer, cfg); e!=nil { return e }
	// Dump the file
	outpath := filepath.Join(os.Getenv("CORES"), corename, "ver","game" )
	os.MkdirAll(outpath, 0777) // derivative cores may not have a permanent hdl folder
	outpath = filepath.Join( outpath, "dump2bin.sh" )
	e = ioutil.WriteFile(outpath, buffer.Bytes(), 0755); if e!=nil { return e }
	if Verbose {
		fmt.Printf("%s created\n",outpath)
	}
	return nil
}

func bankOffset( cfg *MemConfig, corename string) (e error) {
	mra_cfg, e := mra.ParseTomlFile( corename )
	if e!=nil { return e }
	if len(mra_cfg.Header.Offset.Regions)==0 { return nil }
	cfg.Balut = 1
	cfg.Lutsh = mra_cfg.Header.Offset.Bits
	return nil
}

func (cfg *MemConfig)check_banks() error {
	// Check that the arguments make sense
	if len(cfg.SDRAM.Banks) > 4 || len(cfg.SDRAM.Banks) == 0 {
		log.Fatalf("jtframe mem: the number of banks must be between 1 and 4 but %d were found.", len(cfg.SDRAM.Banks))
	}
	bad := false
	if cfg.Balut==0 {
		for bank_count:=1; bank_count<4; bank_count++ {
			if len(cfg.SDRAM.Banks)>bank_count  {
				bank_str := fmt.Sprintf("JTFRAME_BA%d",bank_count)
				bad = bad || report_bad_int( bank_str+"_START")
				wen_macro := bank_str+"_WEN"
				for _,bank_bus := range cfg.SDRAM.Banks[bank_count].Buses {
					if bank_bus.Rw {
						if !macros.IsSet(wen_macro) {
							fmt.Printf("Missing %s. Defi


urs. It is an error because integers cannot
			represent infinity and not-a-number, and also the integer
			overflow rules are unsuitable to resolve this situation.

Example

				<tscript>
					var r = Real.inf();
					var s = "1e1000";
					# print(Integer(r));  # error: r is infinite
					# print(Integer(s));  # error: s parsed as Real
					                      # overflows to infinity
				</tscript>

		`,
					children: [],
				},
				{
					id: "am-14",
					content: `

			This error occurs when a string is converted to an integer
			and the string value does not represent a number.

Example

				<tscript>
					print(Integer("42"));        # prints 42
					# print(Integer(""));        # error
					# print(Integer("hello"));   # error
				</tscript>

		`,
					children: [],
				},
				{
					id: "am-15",
					content: `

			This error occurs when a value is divided by zero with the
			integer division operator \/\/ or
			with the modulo operator %. As an
			exception, integer division by zero applied to type
			Real results in an
			infinite value or not-a-number (NaN).
			In contrast to this behavior, the real division operator
			/ does not emit an error and
			always produces an infinite result or not-a-number.

Example

				<tscript>
					print(3 / 0);      # prints Infinity
					# print(3 \/\/ 0);   # error
					# print(3 % 0);    # error
				</tscript>

			This error usually occurs when dividing by a variable or by
			the result of a complex expression the value of which was not
			foreseen by the programmer to be zero. Example:
			<tscript>
				var a = math.pi();
				var b = a - 2 * math.atan(1e100);  # numerically evaluates to zero
				# var c = math.e() % b;            # error
			</tscript>

		`,
					children: [],
				},
				{
					id: "am-16",
					content: `

			Values are said to be ordered if they can be compared with operators
			<, <=,
			>, and >=.
			The rules for ordering values are found
			here.
			For example, arrays can be ordered, while dictionaries cannot.

Example

				<tscript>
					print(1 < 2);               # prints true
					print("hello" > "world");   # prints false
					print([] < [42]);           # prints true
					# print({} < {a: 7});       # error: dictionaries are not ordered
				</tscript>

			This error occurs frequently if one of the operands of the comparison
			is of a type the programmer did not expect. E.g., a function like
			String.find usually returns a
			number, but in occasional error conditions it returns null. Therefore
			a statement like
			<tscript>
				var s = "hello";


 server error|Usually **reachable**; warn to recheck provider reliability|
|TLS handshake error|Host contacted but cert/bundle mismatch|**Reachable**; warn about TLS setup|
|`ConnectException` / timeout|No route / refused / blocked|**Failure** (cannot connect)|

> The exact policy can be tuned. A common rule: treat **anything but genuine connect/timeout failures** as “reachable”, then layer a **resource‑existence** rule to reject 404 for required endpoints.

---

### Spring Boot implementation patterns

#### RestTemplate (blocking)

```java
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
f.setConnectTimeout(3000);
f.setReadTimeout(5000);
RestTemplate rt = new RestTemplate(f);
```

- Pros: simple, ubiquitous.

- Cons: legacy, fewer advanced features; prefer WebClient for new work.

#### WebClient (reactive)

```java
HttpClient http = HttpClient.create()
  .compress(true)
  .responseTimeout(Duration.ofSeconds(5))
  .secure(); // TLS by default for https

WebClient wc = WebClient.builder()
  .clientConnector(new ReactorClientHttpConnector(http))
  .build();
```

- Configure **connect timeout** via `ChannelOption.CONNECT_TIMEOUT_MILLIS` if needed on the `HttpClient` bootstrap.

- Easy to cap **max redirects** and inspect each redirect target.

#### Timeouts (separate knobs)

- **Connect timeout**: time to establish TCP/TLS. Small (2–5s).

- **Read timeout**: waiting for the first/next byte. Slightly larger.

- **Overall cap**: consider circuit breaker or deadline budget.

#### Exception → message mapping

- `UnknownHostException` → DNS issue: “domain not found.”

- `ConnectException` → refused/blocked: “connection refused / cannot reach.”

- `SocketTimeoutException` → slow/unresponsive.

- TLS errors → cert mismatch/expired/unsupported cipher.

---

### DNS & IP checks (practical notes)

- Use `InetAddress.getAllByName(host)` to enumerate addresses and screen them with `isLoopbackAddress()`, `isSiteLocalAddress()`, and explicit CIDR checks for precision.

- Beware CDNs that return **multiple** IPs; screen **all** of them.

- Re‑check after each **redirect** to prevent an allowed domain chaining to a private IP.

---

### Configuration surface (example)

```yaml
security:
  endpoint-validation:
    enforce-https: true
    reject-private-network: true
    connect-timeout-ms: 3000
    read-timeout-ms: 5000
    follow-redirects: 3
```

- Keep a **domain allow‑list** if only a fixed set of IdPs is permissible.

- Log **who** changed what (audit) and store last validation outcome.

---

### Hardening options (beyond the basics)

- **Public‑suffix / eTLD+1** pinning (e.g., only `*.company.com`).

- **Pin CA / certificate** for critical partners.

- **Outbound egress control** at network layer (firewall/proxy), not just app code.

- Deny **non‑routable/bogon** ranges (RFC 6890) in addition to private ranges.

- Require **`application/json`** or a specific content type for discovery endpoints.

---

```java
@RequiredArgsConstructor
@Slf4j
public class SsoConnectivityChecker {

    private final SsoProperties props;

    /**
     * Validate the given URL is HTTPS, not private/loopback, and reachable.     */    public void validateHttpsReachable(String url, String fieldName) {
        try {
            if (url == null || url.isEmpty()) {
                throw new UdpBizException(fieldName + " cannot be empty");
            }

            URI uri = new URI(url.trim());

            // Only enforce HTTPS when enabled
            if (props.isEnforceHttps() && !"https".equalsIgnoreCase(uri.getScheme())) {
                throw new UdpBizException(fieldName + " must use HTTPS");
            }

            String host = uri.getHost();
            if (host == null || host.isEmpty


 $param3 игра в $param4',
      one: '#$count място (топ $param2%) с $param3 игра в $param4',
    );
    return '$_temp0';
  }

  @override
  String activityCompetedInNbSwissTournaments(int count) {
    String _temp0 = intl.Intl.pluralLogic(
      count,
      locale: localeName,
      other: 'Участва в $count турнира по швейцарската система',
      one: 'Участва в $count турнир по швейцарската система',
    );
    return '$_temp0';
  }

  @override
  String activityJoinedNbTeams(int count) {
    String _temp0 = intl.Intl.pluralLogic(
      count,
      locale: localeName,
      other: 'Присъедини се в $count отбори',
      one: 'Присъедини се в $count отбор',
    );
    return '$_temp0';
  }

  @override
  String get arenaArena => 'Арена';

  @override
  String get arenaArenaTournaments => 'Арена турнири';

  @override
  String get arenaIsItRated => 'С рейтинг ли е?';

  @override
  String get arenaWillBeNotified => 'Ще бъдете уведомени когато турнирът започне, така че е безопасно да се играе в друг раздел докато чакате.';

  @override
  String get arenaIsRated => 'Този турнир ще се отрази на вашия рейтинг.';

  @override
  String get arenaIsNotRated => 'Този турнир *не* е с рейтинг *няма* да промени рейтинга Ви.';

  @override
  String get arenaSomeRated => 'Някои от турнирите могат да се отразят на Вашия рейтинг.';

  @override
  String get arenaHowAreScoresCalculated => 'Как се изчисляват резултатите?';

  @override
  String get arenaHowAreScoresCalculatedAnswer => 'Всяка победа носи 2 точки, реми - 1 точка, а загуба - 0 точки.\nПри две последователни победи ще започнете поредица от удвояване на точките, означена с икона на пламъче.\nСледващите игри ще продължат да дават двойно повече точки до първата партия, в която не успеете да спечелите.\nТова означава, че всяка победа от поредицата ще води 4 точки, ремито - 2, а загубата ще остане 0.\n\nНапример две победи, последвани от равенство, ще носят 6 точки: 2 + 2 + (2 x 1)';

  @override
  String get arenaBerserk => 'Берсерк арена';

  @override
  String get arenaBerserkAnswer => 'Когато играч натисне Берсерк бутона в началото на играта ще загуби половината от времето си, но победата ще му донесе една допълнителна точка.\n\nБерсерк също така изключва


{
				sendDebug('makeGMonlyMImenu: invalid tokenID passed');
				sendError('Internal MagicMaster error');
				return;
			}

			var config = getSetPlayerConfig( senderId ),
				sectType = (config.sections !== false ? 'hide' : 'show'),
				alphaLists = _.isUndefined(config.alphaLists) ? true : config.alphaLists,
				qty, mi,
				potions = getMagicList(fields.MagicItemDB,miTypeLists,'potion',senderId,'',false,'',!!alphaLists),
				scrolls = getMagicList(fields.MagicItemDB,miTypeLists,'scroll',senderId,'',false,'',!!alphaLists),
				rods = getMagicList(fields.MagicItemDB,miTypeLists,'rod',senderId,'',false,'',!!alphaLists),
				weapons = getMagicList(fields.MagicItemDB,miTypeLists,'weapon',senderId,'',false,'',!!alphaLists),
				ammo = getMagicList(fields.MagicItemDB,miTypeLists,'ammo',senderId,'',false,'',!!alphaLists),
				armour = getMagicList(fields.MagicItemDB,miTypeLists,'armour',senderId,'',false,'',!!alphaLists),
				rings = getMagicList(fields.MagicItemDB,miTypeLists,'ring',senderId,'',false,'',!!alphaLists),
				misc = getMagicList(fields.MagicItemDB,miTypeLists,'miscellaneous',senderId,'',false,'',!!alphaLists),
				equip = getMagicList(fields.MagicItemDB,miTypeLists,['equipment','light'],senderId,'',false,'',!!alphaLists),
				treasure = getMagicList(fields.MagicItemDB,miTypeLists,'treasure',senderId,'',false,'',!!alphaLists),
				coins = getMagicList(fields.MagicItemDB,miTypeLists,'coin',senderId,'',false,'',false),
				gems = getMagicList(fields.MagicItemDB,miTypeLists,'gem',senderId,'',false,'',!!alphaLists),
				services = getMagicList(fields.MagicItemDB,miTypeLists,'services',senderId,'',false,'',!!alphaLists),
				dmitems = getMagicList(fields.MagicItemDB,miTypeLists,'dmitem',senderId,'',false,'',false),
				content = '&{template:'+fields.menuTemplate+'}{{name=Edit '+charCS.get('name')+'\'s Magic Item Bag}}'
						+ (msg && msg.length ? '{{ ='+msg+'}}' : '')
						+ '{{Section=**1. Choose something to store** *show '+(alphaLists ? 'complete' : 'alphabetic')+' list*\n';

			content += '[Potion](!magic --button GM-MItoStore|'+tokenID+'|'+MIrowref+'|?{Which Potion?|'+potions+'})'
					+  '[Scroll](!magic --button GM-MItoStore|'+tokenID+'|'+MIrowref+'|?{Which Scroll?|'+scrolls+'})'
					+  '[Rods, Staves, Wands](!magic --button GM-MItoStore|'+tokenID+'|'+MIrowref+'|?{Which Rod, Staff or Wand?|'+rods+'})'
					+  '[Weapon](!magic --button GM-MItoStore|'+tokenID+'|'+MIrowref+'|?{Which Weapon?|'+weapons+'})'
					+  '[Ammo](!magic --button GM-MItoStore|'+tokenID+'|'+MIrowref+'|?{Which Ammo?|'+ammo+'})'
					+  '[Armour](!magic --button GM-MItoStore|'+tokenID+'|'+MIrowref+'|?{Which piece of Armour?|'+a


times (1 + \mathrm{N})

$$

其中各项的取值范围为：

$$
\begin{aligned}
\mathrm{S} \in & { 0, 1}, \quad \mathrm{E} \in { 1, 2, \dots, 254 } \newline
(1 + \mathrm{N}) = & (1 + \sum{i=1}^{23} b{23-i} 2^{-i}) \subset [1, 2 - 2^{-23}]
\end{aligned}

$$

观察上图，给定一个示例数据 $\mathrm{S} = 0$ ， $\mathrm{E} = 124$ ，$\mathrm{N} = 2^{-2} + 2^{-3} = 0.375$ ，则有：

$$
\text { val } = (-1)^0 \times 2^{124 - 127} \times (1 + 0.375) = 0.171875

$$

现在我们可以回答最初的问题：float 的表示方式包含指数位，导致其取值范围远大于 int 。根据以上计算，float 可表示的最大正数为 $2^{254 - 127} \times (2 - 2^{-23}) \approx 3.4 \times 10^{38}$ ，切换符号位便可得到最小负数。

尽管浮点数 float 扩展了取值范围，但其副作用是牺牲了精度。整数类型 int 将全部 32 位用于表示数字，数字是均匀分布的；而由于指数位的存在，浮点数 float 的数值越大，相邻两个数字之间的差值就会趋向越大。

如下表所示，指数位 $E = 0$ 和 $E = 255$ 具有特殊含义，用于表示零、无穷大、$\mathrm{NaN}$ 等。

 表 <id>   指数位含义 </id>

指数位 E
分数位 $\mathrm{N} = 0$
分数位 $\mathrm{N} \ne 0$
计算公式

$0$
$\pm 0$
次正规数
$(-1)^{\mathrm{S} } \times 2^{-126} \times (0.\mathrm{N})$

$1, 2, \dots, 254$</td


to Mulgore,50.36,66.49,15,0
    .goto Mulgore,51.92,63.85,15,0
    .goto Mulgore,51.13,71.06,15,0
    .goto Mulgore,50.36,66.49,15,0
    >>Collect the |cRXP_PICK_Ambercorns|r. They can be found under the trees on the ground
    .complete 771,2 --Ambercorn (2)
step
	#completewith next
	>>Kill |cRXP_ENEMY_Swoops|r throughout Mulgore. Loot them for their |cRXP_LOOT_Quills|r
    .complete 761,1 --Trophy Swoop Quill (8)
    .mob Wiry Swoop
    .mob Swoop
step << Tauren
    #loop
	.goto Mulgore,50.82,66.66,0
	.goto Mulgore,50.82,66.66,50,0
	.goto Mulgore,51.06,63.63,50,0
	.goto Mulgore,52.79,62.06,50,0
	.goto Mulgore,53.98,61.68,50,0
	.goto Mulgore,55.67,62.77,50,0
	.goto Mulgore,56.46,64.93,50,0
	.goto Mulgore,56.02,67.78,50,0
	.goto Mulgore,55.02,69.65,50,0
	.goto Mulgore,52.33,70.07,50,0
	.goto Mulgore,50.40,70.24,50,0
	.goto Mulgore,48.60,69.43,50,0
	.goto Mulgore,45.98,69.70,50,0
	.goto Mulgore,48.58,67.37,50,0
    >>Kill |cRXP_ENEMY_Prairie Wolves|r and |cRXP_ENEMY_Adult Plainstriders|r. Loot them for their |cRXP_LOOT_Paws|r and |cRXP_LOOT_Talons|r
    .complete 748,1 --Prairie Wolf Paw (6)
    .mob +Prairie Wolf
    .complete 748,2 --Plainstrider Talon (4)
    .mob +Adult Plainstrider
step << Tauren
    .goto Mulgore,48.53,60.40
    >>|Tinterface/worldmap/chatbubble_64grey.blp:20|tTalk to |cRXP_FRIENDLY_Mull|r
    .turnin 748 >>Turn in Poison Water
    .accept 754 >>Accept Winterhoof Cleansing
    .target Mull Thunderhorn
step << Tauren
    #completewith next
    >>Collect the |cRXP_PICK_Well Stones|r around the Well
    .complete 771,1 --Well Stone (2)
step << Tauren
    #label Well
    .goto Mulgore,53.68,66.28
    >>|cRXP_WARN_Use the|r |T135139:0|t[Winterhoof Cleansing Totem] |cRXP_WARN_at the Well|r
    .complete 754,1 --Cleanse the Winterhoof Water Well (1)
step
    #label Stones
    #loop
    .goto Mulgore,54.06,66.40,0
    .goto Mulgore,53.35,65.78,10,0
    .goto Mulgore,53.70,65.59,10,0
    .goto Mulgore,53.98,65.94,10,0
    .goto Mulgore,54.06,66.40,10,0
    >>Collect the |cRXP_PICK_Well Stones|r around the Well
    .complete 771,1 --Well Stone (2)
step
    #completewith Gnolls
    >>|cRXP_WARN_Get the items for Mazzranache as you quest throughout the zone|r
    .complete 766,1 --Prairie Wolf Heart (1)
    .complete 766,2 --Flatland Cougar Femur (


[type=search] {
  padding-right: calc(var(--tsmb-size-sm) + var(--tsmb-size-base) + var(--tsmb-size-base));
}

.tsmb-icon-close {
  box-sizing: border-box;
  position: absolute;
  top: calc(var(--tsmb-size-edge) + var(--tsmb-size-sm) + (var(--tsmb-size-input)/2) - (var(--tsmb-size-base)/2));
  right: var(--tsmb-size-base);
  width: var(--tsmb-size-base);
  height: var(--tsmb-size-base);

  stroke: currentColor;
  border: 1px solid currentColor;
  border-radius: 50%;
  cursor: pointer;
}

form:not(.tsmb-form--open) .tsmb-icon-close {
  display: none;
}

.tsmb-form--slash:not(.tsmb-form--open):not(:focus-within)::after {
  content: '/';
  display: inline-block;
  position: absolute;
  top: calc(50% - (var(--tsmb-size-input) + var(--tsmb-size-sm)/2)/2);
  right: var(--tsmb-size-sm);
  width: calc(var(--tsmb-size-input) + var(--tsmb-size-sm)/2);
  height: calc(var(--tsmb-size-input) + var(--tsmb-size-sm)/2);

  font-size: var(--tsmb-size-base);
  line-height: calc(var(--tsmb-size-input) + var(--tsmb-size-sm)/2);
  text-align: center;

  background: var(--tsmb-color-base-background);
  border: var(--tsmb-size-edge) solid var(--tsmb-color-base90);
  border-radius: var(--tsmb-size-radius);
  color: var(--tsmb-color-base90);
}

.tsmb-form [role=listbox],
typesense-minibar [role=listbox] {
  position: absolute;
  z-index: 10;
  right: var(--tsmb-size-listbox-right);
  background: var(--tsmb-color-focus-background);
  color: var(--tsmb-color-focus30);
  margin-top: var(--tsmb-size-half);
  min-width: 100%;
  width: var(--tsmb-size-listbox-width);
  max-height: var(--tsmb-size-listbox-max-height);
  overflow: auto;
  border: var(--tsmb-size-edge) solid var(--tsmb-color-focus90);
  border-radius: var(--tsmb-size-radius);
  box-shadow: 0 var(--tsmb-size-sm) 20px rgba(0,0,0,0.12);
}

.tsmb-suggestion_group {
  margin: var(--tsmb-size-sm) var(--tsmb-size-base) 0 var(--tsmb-size-base);
  border-bottom: var(--tsmb-size-edge) solid var(--tsmb-color-focus90);
}

.tsmb-form [role=option] a,
typesense-minibar [role=option] a {
  display: block;
  padding: var(--tsmb-size-base);
  text-decoration: none;
  border-left: var(--tsmb-size-highlight) solid transparent;
}

.tsmb-form:not([data-group=true]) [role=option]:not(:first-child) a,
typesense-minibar:not([data-group=true]) [role=option]:not(:first-child) a {
  bo


/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved.
 *
 * The information contained herein is property of Nordic Semiconductor ASA.
 * Terms and conditions of usage are described in detail in NORDIC
 * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
 *
 * Licensees are granted free, non-transferable use of the information. NO
 * WARRANTY of ANY KIND is provided. This heading must NOT be removed from
 * the file.
 *
 */

#include "ble_gatts_evt_app.h"
#include <string.h>
#include "ble_serialization.h"
#include "ble_gatts_struct_serialization.h"
#include "app_ble_user_mem.h"
#include "app_util.h"

extern ser_ble_user_mem_t m_app_user_mem_table[];

uint32_t ble_gatts_evt_write_dec(uint8_t const * const p_buf,
                                 uint32_t              packet_len,
                                 ble_evt_t * const     p_event,
                                 uint32_t * const      p_event_len)
{
    SER_ASSERT_NOT_NULL(p_buf);
    SER_ASSERT_NOT_NULL(p_event_len);

    uint32_t err_code = NRF_SUCCESS;
    uint32_t index    = 0;

    uint32_t in_event_len = *p_event_len;

    *p_event_len = offsetof(ble_evt_t, evt.gatts_evt.params) - sizeof (ble_evt_hdr_t);

    uint16_t conn_handle;
    err_code = uint16_t_dec(p_buf, packet_len, &index, &conn_handle);
    SER_ASSERT(err_code == NRF_SUCCESS, err_code);

    void * p_void_write = NULL;

    if (p_event != NULL)
    {
        SER_ASSERT_LENGTH_LEQ(*p_event_len, in_event_len);
        p_event->evt.gatts_evt.conn_handle = conn_handle;

        p_void_write = &(p_event->evt.gatts_evt.params.write);
    }

    uint32_t tmp_struct_len = in_event_len - *p_event_len;
    err_code = ble_gatts_evt_write_t_dec(p_buf,
                                         packet_len,
                                         &index,
                                         &tmp_struct_len,
                                         p_void_write);
    SER_ASSERT(err_code == NRF_SUCCESS, err_code);

    *p_event_len += tmp_struct_len;

    if(p_event != NULL)
    {
        if(p_event->evt.gatts_evt.params.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW)
        {
            uint32_t conn_index;

            if(app_ble_user_mem_context_find(p_event->evt.gatts_evt.conn_handle, &conn_index) != NRF_ERROR_NOT_FOUND)
            {
                err_code = len16data_dec(p_buf, packet_len, &index, &m_app_user_mem_table[conn_index].mem_block.p_mem, &m_app_user_mem_table[conn_index].mem_block.len);
                SER_ASSERT(err_code == NRF_SUCCESS, err_code);
            }
        }
    }

    SER_ASSERT_LENGTH_EQ(index, packet_len);

    return err_code;
}


",_a,{onMouseMove:function(e){
var _53=this.widget;
if(_53.disabled||_53.readOnly){
return;
}
var _54=_53._abspos;
var bar=_53._bar;
var _55=_53._mouseOffset;
if(!_54){
_54=_53._abspos=_7.position(_53.sliderBarContainer,true);
_53._setPixelValue_=_2.hitch(_53,"_setPixelValue");
_53._getValueByPixelValue_=_2.hitch(_53,"_getValueByPixelValue");
_53._isReversed_=_53._isReversed();
}
if(!bar){
bar=_53._bar=_7.position(_53.progressBar,true);
}
var _56=e.touches?e.touches[0]:e;
if(!_55){
_55=_53._mouseOffset=_56[_53._mousePixelCoord]-_54[_53._startingPixelCoord]-bar[_53._startingPixelCoord];
}
var _57=_56[_53._mousePixelCoord]-_54[_53._startingPixelCoord]-_55,_58=_57+bar[_53._pixelCount];
pixelValues=[_57,_58];
pixelValues.sort(_14);
if(pixelValues[0]<=0){
pixelValues[0]=0;
pixelValues[1]=bar[_53._pixelCount];
}
if(pixelValues[1]>=_54[_53._pixelCount]){
pixelValues[1]=_54[_53._pixelCount];
pixelValues[0]=_54[_53._pixelCount]-bar[_53._pixelCount];
}
var _59=[_53._getValueByPixelValue(_53._isReversed_?(_54[_53._pixelCount]-pixelValues[0]):pixelValues[0],_54[_53._pixelCount]),_53._getValueByPixelValue(_53._isReversed_?(_54[_53._pixelCount]-pixelValues[1]):pixelValues[1],_54[_53._pixelCount])];
_53._setValueAttr(_59,false,false);
},destroy:function(){
_a.prototype.destroy.apply(this,arguments);
var _5a=this.widget;
_5a._abspos=null;
_5a._bar=null;
_5a._mouseOffset=null;
_5a._setValueAttr(_5a.value,true);
}});
_1("dojox.form.HorizontalRangeSlider",[_e,_15],{templateString:_c});
_1("dojox.form.VerticalRangeSlider",[_f,_15],{templateString:_d});
return _15;
});
//>>built
define("dojox/data/XmlStore", ["dojo/_base/lang", "dojo/_base/declare", "dojo/_base/xhr", "dojo/data/util/simpleFetch",
		"dojo/_base/query", "dojo/_base/array", "dojo/_base/window", "dojo/data/util/filter", "dojox/xml/parser",
		"dojox/data/XmlItem"],
  function(lang, declare, xhr, simpleFetch, domQuery, array, winUtil, filter, xmlParser, XmlItem) {

var XmlStore = declare("dojox.data.XmlStore", null, {
	//	summary:
	//		A data store for XML based services or documents
	//	description:
	//		A data store for XML based services or documents

	constructor: function(/* object */ args){
		//	summary:
		//		Constructor for the XML store.
		//	args:
		//		An anonymous object to initialize properties.  It expects the following values:
		//		url:		The url to a service or an XML document that represents the store
		//		rootItem:	A tag name for root items
		//		keyAttribute:	An attribute name for a key or an identity (unique identifier


         component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu)
    {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu)
    {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu)
    {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<SysMenu> list, SysMenu t)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符


not case-sensitive):
     * `tcp`, `udp`, or `icmp`.
     *

     *
     * string ip_protocol = 8;
     *
     * @param value The ipProtocol to set.
     * @return This builder for chaining.
     */
    public Builder setIpProtocol(java.lang.String value) {
      if (value == null) {
        throw new NullPointerException();
      }
      ipProtocol_ = value;
      bitField0_ |= 0x00000040;
      onChanged();
      return this;
    }

    /**
     *
     *
     *

     * The IP protocol to which the external access rule applies. This value can
     * be one of the following three protocol strings (not case-sensitive):
     * `tcp`, `udp`, or `icmp`.
     *

     *
     * string ip_protocol = 8;
     *
     * @return This builder for chaining.
     */
    public Builder clearIpProtocol() {
      ipProtocol_ = getDefaultInstance().getIpProtocol();
      bitField0_ = (bitField0_ & ~0x00000040);
      onChanged();
      return this;
    }

    /**
     *
     *
     *

     * The IP protocol to which the external access rule applies. This value can
     * be one of the following three protocol strings (not case-sensitive):
     * `tcp`, `udp`, or `icmp`.
     *

     *
     * string ip_protocol = 8;
     *
     * @param value The bytes for ipProtocol to set.
     * @return This builder for chaining.
     */
    public Builder setIpProtocolBytes(com.google.protobuf.ByteString value) {
      if (value == null) {
        throw new NullPointerException();
      }
      checkByteStringIsUtf8(value);
      ipProtocol_ = value;
      bitField0_ |= 0x00000040;
      onChanged();
      return this;
    }

    private java.util.List<com.google.cloud.vmwareengine.v1.ExternalAccessRule.IpRange>
        sourceIpRanges_ = java.util.Collections.emptyList();

    private void ensureSourceIpRangesIsMutable() {
      if (!((bitField0_ & 0x00000080) != 0)) {
        sourceIpRanges_ =
            new java.util.ArrayList<com.google.cloud.vmwareengine.v1.ExternalAccessRule.IpRange>(
                sourceIpRanges_);
        bitField0_ |= 0x00000080;
      }
    }

    private com.google.protobuf.RepeatedFieldBuilderV3<
            com.google.cloud.vmwareengine.v1.ExternalAccessRule.IpRange,
            com.google.cloud.vmwareengine.v1.ExternalAccessRule.IpRange.Builder,
            com.google.cloud.vmwareengine.v1.ExternalAccessRule.IpRangeOrBuilder>
        sourceIpRangesBuilder_;

    /**
     *
     *
     *

     * If source ranges are specified, the external access rule applies only to
     * traffic that has a source IP address in these ranges. These ranges can
     * either be expressed in the CIDR format or as an IP address. As only inbound
     * rules are supported, `ExternalAddress` resources cannot be the source IP
     * addresses of an external access rule. To match all source addresses,
     * specify `0.0.0.0/0`.
     *

     *
     * repeated .google.cloud.vmwareengine.v1.ExternalAccessRule.IpRange source_ip_ranges = 9;
     *
     */
    public java.util.List<com.google.cloud.vmwareengine.v1.ExternalAccessRule.IpRange>
        getSourceIpRangesList() {
      if (sourceIpRangesBuilder_ == null) {
        return java.util.Collections.unmodifiableList(sourceIpRanges_);
      } else {
        return sourceIpRangesBuilder_.getMessageList();
      }
    }

    /**
     *
     *
     *

     * If sour


rInfo != null) {
      userName.value = userInfo['name'];
    }
  }

  Future<void> reset({bool resetOther = false}) async {
    await bind.mainSetLocalOption(key: 'access_token', value: '');
    await bind.mainSetLocalOption(key: 'user_info', value: '');
    if (resetOther) {
      await gFFI.abModel.reset();
      await gFFI.groupModel.reset();
    }
    userName.value = '';
  }

  _parseAndUpdateUser(UserPayload user) {
    userName.value = user.name;
    isAdmin.value = user.isAdmin;
    bind.mainSetLocalOption(key: 'user_info', value: jsonEncode(user));
    if (isWeb) {
      // ugly here, tmp solution
      bind.mainSetLocalOption(key: 'verifier', value: user.verifier ?? '');
    }
  }

  // update ab and group status
  static Future<void> updateOtherModels() async {
    await Future.wait([
      gFFI.abModel.pullAb(force: ForcePullAb.listAndCurrent, quiet: false),
      gFFI.groupModel.pull()
    ]);
  }

  Future<void> logOut({String? apiServer}) async {
    final tag = gFFI.dialogManager.showLoading(translate('Waiting'));
    try {
      final url = apiServer ?? await bind.mainGetApiServer();
      final authHeaders = getHttpHeaders();
      authHeaders['Content-Type'] = "application/json";
      await http
          .post(Uri.parse('$url/api/logout'),
              body: jsonEncode({
                'id': await bind.mainGetMyId(),
                'uuid': await bind.mainGetUuid(),
              }),
              headers: authHeaders)
          .timeout(Duration(seconds: 2));
    } catch (e) {
      debugPrint("request /api/logout failed: err=$e");
    } finally {
      await reset(resetOther: true);
      gFFI.dialogManager.dismissByTag(tag);
    }
  }

  /// throw [RequestException]
  Future<LoginResponse> login(LoginRequest loginRequest) async {
    final url = await bind.mainGetApiServer();
    final resp = await http.post(Uri.parse('$url/api/login'),
        body: jsonEncode(loginRequest.toJson()));

    final Map<String, dynamic> body;
    try {
      body = jsonDecode(decode_http_response(resp));
    } catch (e) {
      debugPrint("login: jsonDecode resp body failed: ${e.toString()}");
      if (resp.statusCode != 200) {
        BotToast.showText(
            contentColor: Colors.red, text: 'HTTP ${resp.statusCode}');
      }
      rethrow;
    }
    if (resp.statusCode != 200) {
      throw RequestException(resp.statusCode, body['error'] ?? '');
    }
    if (body['error'] != null) {
      throw RequestException(0, body['error']);
    }

    return getLoginResponseFromAuthBody(body);
  }

  LoginResponse getLoginResponseFromAuthBody(Map<String, dynamic> body) {
    final LoginResponse loginResponse;
    try {
      loginResponse = LoginResponse.fromJson(body);
    } catch (e) {
      debugPrint("login: jsonDecode LoginResponse failed: ${e.toString()}");
      rethrow;
    }

    final isLogInDone = loginResponse.type == HttpType.kAuthResTypeToken &&
        loginResponse.access_token != null;
    if (isLogInDone && loginResponse.user != null) {
      _parseAndUpdateUser(loginResponse.user!);
    }

    return loginResponse;
  }

  static Future<List<dynamic>> queryOidcLoginOptions() async {
    try {
      final url = await bind.mainGetApiServer();
      if (url.trim().isEmpty) return [];
      final


01,0xcb,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, flat_scratch_lo
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xcd,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, flat_scratch_hi
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xcf,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, vcc_lo
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xd5,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, vcc_hi
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xd7,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, ttmp15
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xf7,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, m0
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xf9,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, exec_lo
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xfd,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, exec_hi
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xff,0x00,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, 0
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0x01,0x01,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, -1
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0x83,0x01,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, 0.5
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xe1,0x01,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, -4.0
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xef,0x01,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, src_vccz
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xf7,0x01,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, src_execz
// CHECK: [0x05,0x0c,0x1a,0xd1,0x01,0xf9,0x01,0x00]

v_sub_co_u32_e64 v5, s[12:13], v1, src_scc
// CHECK: [0x05,0x0c,0x1a,0x


ide
		public boolean equals(Object obj) {
			if (!(obj instanceof DecisionEntryKey)) {
				return false;
			}
			DecisionEntryKey other = (DecisionEntryKey) obj;
			return this.constraint.equals(other.constraint) && (this.strict == other.strict);
		}

		@Override
		public int hashCode() {
			int hash = 0;
			hash = constraint.hashCode() + (hash << 6) + (hash << 16) - hash;
			hash = (strict ? 13 : 17) + (hash << 6) + (hash << 16) - hash;

			return hash;
		}
	}

	/**
	 * Class to store keys for the cache of the decision procedure.
	 */
	class DecisionEntryValue {
		/** region this result is valid for */
		Region region;
		/** result, that is whether corresponding constraint holds in region */
		boolean result;

		@Override
		public boolean equals(Object obj) {
			if (!(obj instanceof DecisionEntryValue)) {
				return false;
			}
			DecisionEntryValue other = (DecisionEntryValue) obj;
			return this.region.equals(other.region) && (this.result == other.result);
		}

		@Override
		public int hashCode() {
			int hash = 0;
			hash = region.hashCode() + (hash << 6) + (hash << 16) - hash;
			hash = (result ? 13 : 17) + (hash << 6) + (hash << 16) - hash;

			return hash;
		}
	}

	/** number of random points to evaluate in decision procedure */
	private int numRandomPoints;
	/** decision cache */
	protected HashMap<DecisionEntryKey,ArrayList<DecisionEntryValue>> decisions;

	/**
	 * Constructs a new constraint checker.
	 *
	 * @param numRandomPoints number of inner points to evaluate in addition to border points
	 */
	ConstraintChecker(int numRandomPoints) {
		this.numRandomPoints = numRandomPoints;
		decisions = new HashMap<DecisionEntryKey,ArrayList<DecisionEntryValue>>();
	}

	/**
	 * Main decision check.
	 * In this class, does nothing. Derived class could override this method
	 * for instance by calling an external decision procedure, use a library
	 * to decide validity in a given region, etc.
	 *
	 * @param region region for which to check validity of constraint
	 * @param constraint constraint to check (whether >=/> 0)
	 * @param strict true iff ">" shold be checked rathern than ">="
	 * @return true
	 */
	boolean mainCheck(Region region, Function constraint, boolean strict)
	{
		usedUnsoundCheck = true;
		return true;
	}

	/**
	 * Does a quick pre-check by evaluating constraint at random points.
	 *
	 * @param region region for which to check validity of constraint
	 * @param constraint constraint to check (whether >=/> 0)
	 * @param strict true iff ">" shold be checked rathern than ">="
	 * @return true if no counterexamples to validity found
	 */
	boolean preCheck(Region region, Function constraint, boolean strict)
	{
		ArrayList<Point> points = region.specialPoints();
		for (Point point : points) {
			if (!constraint.check(point, strict)) {
				return false;
			}
		}

		for (int pointNr = 0; pointNr < numRandomPoints; pointNr++) {
			if (!constraint.check(region.randomPoint(), strict)) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Checks whether constraint holds in given region.
	 *
	 * @param region region for which to check validity of constraint
	 * @param constraint constraint to check (whether >=/> 0)
	 * @param strict true iff ">" shold be checked rathern than ">="
	 * @return true iff function values are (strictly) larger than zero in whole region


hod* method)
{
	int32_t V_0 = 0;
	{
		String_t* L_0 = ___format0;
		NumberFormatter_Init_mE4CB58F7935FD515BDBC5A88C389CCAE85A45286(__this, L_0, /*hidden argument*/NULL);
		int32_t L_1 = ___defPrecision2;
		__this->set__defPrecision_15(L_1);
		__this->set__positive_12((bool)1);
		uint32_t L_2 = ___value1;
		if (!L_2)
		{
			goto IL_0022;
		}
	}
	{
		Il2CppChar L_3 = __this->get__specifier_13();
		if ((!(((uint32_t)L_3) == ((uint32_t)((int32_t)88)))))
		{
			goto IL_002b;
		}
	}

IL_0022:
	{
		uint32_t L_4 = ___value1;
		NumberFormatter_InitHex_mE69DD9D0FA84E4553B40C522E76D49E850A6AE30(__this, (((int64_t)((uint64_t)L_4))), /*hidden argument*/NULL);
		return;
	}

IL_002b:
	{
		uint32_t L_5 = ___value1;
		NumberFormatter_InitDecHexDigits_mDDED506A219AEEA8A1A12EBC660550D440FF873B(__this, L_5, /*hidden argument*/NULL);
		int32_t L_6 = NumberFormatter_DecHexLen_m6624BB04300860C2C7187CC1C66FF3FB9A68D97B(__this, /*hidden argument*/NULL);
		int32_t L_7 = L_6;
		V_0 = L_7;
		__this->set__digitsLen_16(L_7);
		int32_t L_8 = V_0;
		__this->set__decPointPos_18(L_8);
		return;
	}
}
// System.Void System.NumberFormatter::Init(System.String,System.Int64)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NumberFormatter_Init_mC48E49CCC89DD59718AC2D00A477CA8F397FBA8C (NumberFormatter_t73E68FC7EA017E5EEB4AB92AF2FD959466D1A4BC * __this, String_t* ___format0, int64_t ___value1, const RuntimeMethod* method)
{
	int32_t V_0 = 0;
	{
		String_t* L_0 = ___format0;
		NumberFormatter_Init_mE4CB58F7935FD515BDBC5A88C389CCAE85A45286(__this, L_0, /*hidden argument*/NULL);
		__this->set__defPrecision_15(((int32_t)19));
		int64_t L_1 = ___value1;
		__this->set__positive_12((bool)((((int32_t)((((int64_t)L_1) < ((int64_t)(((int64_t)((int64_t)0)))))? 1 : 0)) == ((int32_t)0))? 1 : 0));
		int64_t L_2 = ___value1;
		if (!L_2)
		{
			goto IL_002a;
		}
	}
	{
		Il2CppChar L_3 = __this->get__specifier_13();
		if ((!(((uint32_t)L_3) == ((uint32_t)((int32_t)88)))))
		{
			goto IL_0032;
		}
	}

IL_002a:
	{
		int64_t L_4 = ___value1;
		NumberFormatter_InitHex_mE69DD9D0FA84E4553B40C522E76D49E850A6AE30(__this, L_4, /*hidden argument*/


:inline-flex;margin-right:1rem}.custom-control-input{position:absolute;left:0;z-index:-1;width:1rem;height:1.25rem;opacity:0}.custom-control-input:checked~.custom-control-label::before{color:#fff;border-color:#007bff;background-color:#007bff}.custom-control-input:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-control-input:focus:not(:checked)~.custom-control-label::before{border-color:#80bdff}.custom-control-input:not(:disabled):active~.custom-control-label::before{color:#fff;background-color:#b3d7ff;border-color:#b3d7ff}.custom-control-input:disabled~.custom-control-label,.custom-control-input[disabled]~.custom-control-label{color:#6c757d}.custom-control-input:disabled~.custom-control-label::before,.custom-control-input[disabled]~.custom-control-label::before{background-color:#e9ecef}.custom-control-label{position:relative;margin-bottom:0;vertical-align:top}.custom-control-label::before{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;pointer-events:none;content:"";background-color:#fff;border:#adb5bd solid 1px}.custom-control-label::after{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;content:"";background:no-repeat 50%/50% 50%}.custom-checkbox .custom-control-label::before{border-radius:.25rem}.custom-checkbox .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26l2.974 2.99L8 2.193z'/%3e%3c/svg%3e")}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before{border-color:#007bff;background-color:#007bff}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='4' viewBox='0 0 4 4'%3e%3cpath stroke='%23fff' d='M0 2h4'/%3e%3c/svg%3e")}.custom-checkbox .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-checkbox .custom-control-input:disabled:indeterminate~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-radio .custom-control-label::before{border-radius:50%}.custom-radio .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e")}.custom-radio .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-switch{padding-left:2.25rem}.custom-switch .custom-control-label::before{left:-2.25rem;wi


nter[0] + length, center[1]:center[1] + length] = 0
        return data

class XShear(object):
    """增加椒盐噪声
    Args:
        snr （float）: Signal Noise Rate
        p (float): 概率值，依概率执行该操作
    """

    def __init__(self, angle=8):
        self.angle = angle

    def __call__(self, data):
        # Define the most occuring variables
        angle = random.randint(-self.angle, self.angle)
        data = np.ascontiguousarray(data)
        data = torch.Tensor(data)
        data = F.affine(data, angle=0, scale=1, shear=[angle, 0], fill=0, translate=(0, 0))
        return data.numpy()

def mixup_data(x, y, alpha=0.5, use_cuda=True):
    '''Compute the mixup data. Return mixed inputs, pairs of targets, and lambda'''
    if alpha > 0.:
        lam = np.random.beta(alpha, alpha)
    else:
        lam = 1.
    batch_size = x.size()[0]
    if use_cuda:
        index = torch.randperm(batch_size).cuda()
    else:
        index = torch.randperm(batch_size)

    mixed_x = lam * x + (1 - lam) * x[index, :]
    y_a, y_b = y, y[index]
    return mixed_x, y_a, y_b, lam

def mixup_criterion(y_a, y_b, lam):
    return lambda criterion, pred: lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)


clip-path:polygon(0 0,0 50%,10% 50%,10% 0,30% 0,30% 100%,40% 100%,40% 0,70% 0,70% 50%,80% 50%,80% 100%,90% 100%,calc(100% - 6px) 100%,100% 0)}.cyber-h{display:block;width:60%}.cyber-h:after{content:" ";width:100%;height:6px;display:block;background-color:var(--ac);clip-path:polygon(0 0,0 100%,10% 100%,calc(10% + 4px) 2px,100% 2px,100% 0)}h1.cyber-h{font-size:3rem;margin:2rem 0;width:100%}h2.cyber-h{font-size:2.5rem;margin:1.6rem 0;width:90%}h3.cyber-h{font-size:2rem;margin:1.4rem 0;width:80%}h4.cyber-h{font-size:1.5rem;margin:1.2rem 0;width:70%}h5.cyber-h{font-size:1rem;margin:1rem 0;width:60%}h6.cyber-h{font-size:1rem;margin:1rem 0;font-weight:400;width:60%}.cyber-banner,.cyber-banner-short{width:100%;height:50px;background-repeat:no-repeat;font-size:1.5rem;font-weight:700;text-align:center;line-height:50px;overflow:hidden;clip-path:polygon(0 0,0 100%,calc(100% - 20px) 100%,100% calc(100% - 20px),100% 0);background:linear-gradient(90deg,var(--banner-color1),var(--banner-color2),var(--banner-color3),var(--banner-color4) var(--banner-gradient-stop))}.cyber-banner-short{--banner-gradient-stop: 220px}.cyber-banner.bg-yellow,.cyber-banner-short.bg-yellow{--banner-color1: var(--cyan);--banner-color2: var(--purple);--banner-color3: var(--red);--banner-color4: var(--yellow)}.cyber-banner.bg-purple,.cyber-banner-short.bg-purple{--banner-color1: var(--red);--banner-color2: var(--yellow);--banner-color3: var(--cyan);--banner-color4: var(--purple)}.cyber-banner.bg-red,.cyber-banner-short.bg-red{--banner-color1: var(--yellow);--banner-color2: var(--cyan);--banner-color3: var(--purple);--banner-color4: var(--red)}.cyber-banner:before,.cyber-banner-short:before{content:" ";height:inherit;display:block;float:left;background-position:top left;background-repeat:no-repeat;background-size:cover}.cyber-banner:before{width:405px;background-image:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="405" height="50"><path d="M0 0v50h20L45 0zM47 0 22 50h28L75 0zM79 0 54 50h26l25-50zM111 0 86 50h24l25-50zM143 0l-25 50h22l25-50zM175 0l-25 50h20l25-50zM207 0l-25 50h18l25-50zM239 0l-25 50h16l25-50zM271 0l-25 50h14l25-50zM303 0l-25 50h12l25-50zM335 0l-25 50h10l25-50zM367 0l-25 50h8l25-50zM399 0l-25 50h6l25-50z"/></svg>')}.cyber-banner-short:before{width:220px;background-image:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="220" height="50"><path d="m0 0-10 50h20


['videoPath'];
    messageEntity.thumbPath = file['thumbPath'];
    messageEntity.messageOwner = 0;
    messageEntity.length = int.parse(file['length']) + 1;
    messageEntity.status = '2';
    messageEntity.contentType = Constants.CONTENT_TYPE_VIDEO;
    setState(() {
      _messageList.insert(0, messageEntity);
      _controller.clear();
    });
    _sendMessage(messageEntity);
  }

  _sendMessage(MessageEntity messageEntity, {bool isResend = false}) {
    if (isResend) {
      setState(() {
        messageEntity.status = '2';
      });
    }
    InteractNative.goNativeWithValue(InteractNative.methodNames['sendMessage'],
            ObjectUtil.buildMessage(messageEntity))
        .then((success) {
      if (success == true) {
        setState(() {
          messageEntity.status = '0';
        });
      } else {
        //一般黑名单的情况就发送失败
        DialogUtil.buildToast('发送失败');
        setState(() {
          messageEntity.status = '1';
        });
      }
      //插入数据库
      MessageDataBase.get()
          .insertMessageEntity(messageEntity.titleName, messageEntity)
          .then((res) {
        MessageDataBase.get()
            .getOneMessageUnreadCount(messageEntity.titleName)
            .then((onValue) {
          MessageTypeEntity messageTypeEntity = new MessageTypeEntity(
              senderAccount: messageEntity.titleName, isUnreadCount: onValue);
          MessageDataBase.get().insertMessageTypeEntity(messageTypeEntity);
          //刷新消息页面
          InteractNative.getMessageEventSink().add(messageEntity);
        });
      });
    });
  }

  @override
  void updateData(MessageEntity entity) {
    // TODO: implement updateData
    if (null == entity) {
      return;
    }
    if (entity.messageOwner == 0 || _first) {
      //自己发的消息，通知消息页面刷新的时候，这里也会收到，但是这些不处理
      _first = false;
      return;
    } else if (entity.type == Constants.MESSAGE_TYPE_CHAT) {
      MessageDataBase.get()
          .updateAllMessageTypeEntity(widget.senderAccount)
          .then((res) {
        //标记改对话所有消息为已读
        InteractNative.getMessageEventSink().add(ObjectUtil.getDefaultData(
            InteractNative.SYSTEM_MESSAGE_HAS_READ, widget.senderAccount));
      });
      setState(() {
        _messageList.insert(0, entity);
      });
    }
  }
}
import 'package:FSOUNotes/enums/constants.dart';
import 'package:FSOUNotes/ui/shared/app_config.dart';
import 'package:flutter/material.dart';

class BackIconAppBar extends StatelessWidget with PreferredSizeWidget {
  final String title;
  final bool showTitle;
  @override
  final Size preferredSize;
  BackIconAppBar({Key key, this.title, this.showTitle})
      : preferredSize = Size.fromHeight(60.0),
        super(key: key);
  @override
  Widget build(BuildContext context) {
    BoxShadow defaultAppBarShadow = BoxShadow(
      color: Colors.grey.withOpacity(0.2),
      // blurRadius: 0.5,
      offset: Offset(0, 2),
    );
    return Container(
      color: Theme.of(context).scaffoldBackgroundColor,
      child: SafeArea(
        bottom: false,
        maintainBottomViewPadding: false,
        child: Container(
          height: 60,
          decoration: BoxDecoration(
            color: Theme.of(context).scaffoldBackgroundColor,
            boxShadow: [defaultAppBarShadow],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                  child: Stack(
                alignment: Alignment.center,
                children: [
                  Align(
                    alignment: Alignment.centerLeft,
                    child: IconButton(
                      icon: Container(
                        margin: EdgeInsets.only(lef


item}'`)
      .join(',')
  }
  else if (v.enum) {
    result.isType = true
    result.propType = v.type === 'string' ? getEnums(v.enum).map(item => `'${item}'`).join('|') : v.enum.join('|')
  }
  else if (v.oneOf && v.oneOf.length > 0) {
    result.isUnionType = true;
    result.propType = v.oneOf.map((type) => {
      return refClassName(type.$ref);
    }).join(',')
  }
  else if (v.allOf && v.allOf) {
    result.isCombinedType = true;
    result.propType = v.allOf.map((type) => {
      return refClassName(type.$ref);
    }).join(',')
  }
  // 基本类型
  else {
    result.propType = toBaseType(v.type)
  }
  return result
}

function getEnums(enumObject: any): any[] {
  return Object.prototype.toString.call(enumObject) === '[object Object]' ? Object.values(enumObject) : enumObject;
}import { Observable, of as observableOf } from 'rxjs';
import { map } from 'rxjs/operators';
import { ConsistentWith } from './util';

export interface GetInputs<I> {
  <K1 extends keyof I>(k1: K1): Observable<Pick<I, K1>>;
  <K1 extends keyof I, K2 extends keyof I>(k1: K1, k2: K2): Observable<Pick<I, K1 | K2>>;
  <K1 extends keyof I, K2 extends keyof I, K3 extends keyof I>(k1: K1, k2: K2, k3: K3): Observable<
    Pick<I, K1 | K2 | K3>
  >;
  <K1 extends keyof I, K2 extends keyof I, K3 extends keyof I, K4 extends keyof I>(
    k1: K1,
    k2: K2,
    k3: K3,
    k4: K4,
  ): Observable<Pick<I, K1 | K2 | K3 | K4>>;
  <
    K1 extends keyof I,
    K2 extends keyof I,
    K3 extends keyof I,
    K4 extends keyof I,
    K5 extends keyof I
  >(
    k1: K1,
    k2: K2,
    k3: K3,
    k4: K4,
    k5: K5,
  ): Observable<Pick<I, K1 | K2 | K3 | K4 | K5>>;
  <
    K1 extends keyof I,
    K2 extends keyof I,
    K3 extends keyof I,
    K4 extends keyof I,
    K5 extends keyof I,
    K6 extends keyof I
  >(
    k1: K1,
    k2: K2,
    k3: K3,
    k4: K4,
    k5: K5,
    k6: K6,
  ): Observable<Pick<I, K1 | K2 | K3 | K4 | K5 | K6>>;
}
export type Outputs<O> = { [K in keyof O]: Observable<O[K]> };

export interface Conduit<I, O extends ConsistentWith<I>> {
  (get: GetInputs<I>): Outputs<O>;
}

export function source<O>(src: { [K in keyof O]: O[K] | Observable<O[K]> }): Conduit<{}, O> {
  const outputs: Outputs<O> = {} as any;
  for (const k in src) {
    const val = src[k];
    outputs[k] = val instanceof Observable ? val : observableOf(val);
  }
  return () => outputs;
}

export function sink<K extends string, I extends Record<K, any>>(
  k: K,
  fn: (arg: I[K]) => void,
): Conduit<I, {}> {
  return get => {
    get(k)
      .pipe(map(o => o[k]))
      .subscribe(fn);
    return {};
  };
}
import { Recipe } from '../class/recipe';
import { Items as i } from '../constants/items';
import { Categories as c } from '../constants/categories';
import { Timer } from '..


0, 0, 0, 0.3);
}
.webix_header.webix_dark .webix_el_counter input[type=text]:focus {
  border-color: transparent;
}
.webix_header.webix_dark .webix_placeholder {
  color: rgba(255, 255, 255, 0.4);
}
.webix_header.webix_dark ::-webkit-input-placeholder {
  color: rgba(255, 255, 255, 0.4);
}
.webix_header.webix_dark ::-moz-placeholder {
  color: rgba(255, 255, 255, 0.4);
}
.webix_header.webix_dark :-moz-placeholder {
  color: rgba(255, 255, 255, 0.4);
}
.webix_header.webix_dark :-ms-input-placeholder {
  color: rgba(255, 255, 255, 0.4);
}
.webix_header.webix_dark .webix_input_icon {
  color: rgba(255, 255, 255, 0.7);
}
.webix_header.webix_dark .webix_selected.webix_segment_0,
.webix_header.webix_dark .webix_selected.webix_segment_1,
.webix_header.webix_dark .webix_selected.webix_segment_N {
  background: #1CA1C1;
  color: #FFFFFF;
}
.webix_header.webix_dark .webix_selected.webix_segment_0:hover,
.webix_header.webix_dark .webix_selected.webix_segment_1:hover,
.webix_header.webix_dark .webix_selected.webix_segment_N:hover {
  background-color: #1992af;
}
.webix_header.webix_dark .webix_selected.webix_segment_0:focus,
.webix_header.webix_dark .webix_selected.webix_segment_1:focus,
.webix_header.webix_dark .webix_selected.webix_segment_N:focus {
  background-color: #1992af;
}
.webix_header.webix_dark .webix_selected.webix_segment_0:active,
.webix_header.webix_dark .webix_selected.webix_segment_1:active,
.webix_header.webix_dark .webix_selected.webix_segment_N:active {
  background-color: #17839d;
}
.webix_header.webix_dark .webix_el_icon,
.webix_header.webix_dark .webix_icon_button {
  color: #FFFFFF;
}
.webix_header.webix_dark .webix_control {
  border-color: #1CA1C1;
}
.webix_header.webix_dark .webix_icon_button:hover:before {
  background-color: rgba(0, 0, 0, 0.2);
}
.webix_header.webix_dark .webix_icon_button:hover .webix_icon {
  opacity: 1;
}
.webix_header.webix_dark .webix_icon_button .webix_icon {
  color: #FFFFFF;
  opacity: 0.7;
}
.webix_header.webix_dark .webix_custom_checkbox,
.webix_header.webix_dark .webix_custom_radio {
  color: #FFFFFF;
}
.webix_header.webix_dark .webix_custom_checkbox:focus,
.webix_header.webix_dark .webix_custom_radio:focus {
  color: #f0f0f0;
}
.webix_header.webix_dark .webix_label_right {
  color: #FFFFFF;
}
.webix_header.webix_dark .webix_view.webix_control .webix_disabled_box .webix_button {
  color: rgba(255, 255, 255, 0.4);


.add_system(initial_camera_setup)
            .add_startup_system_to_stage(StartupStage::PreStartup, spawn_editor_cameras);

        editor_cam_render::setup(app);

        #[cfg(feature = "viewport")]
        app.add_system_to_stage(
            CoreStage::PostUpdate,
            set_main_pass_viewport.before(bevy::render::camera::UpdateCameraProjectionSystem),
        );
    }
}

fn set_active_editor_camera_marker(world: &mut World, editor_cam: EditorCamKind) {
    let mut previously_active = world.query_filtered::<Entity, With<ActiveEditorCamera>>();
    let mut previously_active_iter = previously_active.iter(world);
    let previously_active = previously_active_iter
        .next()
        .expect("there should be a camera with the `ActiveEditorCamera` component");
    assert!(
        previously_active_iter.next().is_none(),
        "there should be only one `ActiveEditorCamera`"
    );
    world
        .entity_mut(previously_active)
        .remove::<ActiveEditorCamera>();

    let entity = match editor_cam {
        EditorCamKind::D2PanZoom => {
            let mut state = world.query_filtered::<Entity, With<EditorCamera2dPanZoom>>();
            state.iter(world).next().unwrap()
        }
        EditorCamKind::D3Free => {
            let mut state = world.query_filtered::<Entity, With<EditorCamera3dFree>>();
            state.iter(world).next().unwrap()
        }
        EditorCamKind::D3PanOrbit => {
            let mut state = world.query_filtered::<Entity, With<EditorCamera3dPanOrbit>>();
            state.iter(world).next().unwrap()
        }
    };
    world.entity_mut(entity).insert(ActiveEditorCamera);
}

fn cameras_ui(
    ui: &mut egui::Ui,
    active_cameras: &mut PersistentActiveCameras,
    mut active_cameras_raw: Mut<ActiveCameras>,
) {
    let cameras = active_cameras.all_sorted();

    let mut toggle_cam_visibility = None;

    ui.label("Cameras");
    for (camera, active) in cameras {
        ui.horizontal(|ui| {
            let text = egui::RichText::new("👁").heading();
            let show_hide_button = egui::Button::new(text).frame(false);
            if ui.add(show_hide_button).clicked() {
                toggle_cam_visibility = Some((camera.to_string(), active));
            }

            if !active {
                ui.set_enabled(false);
            }

            ui.label(camera);
        });
    }

    if let Some((camera, previously_active)) = toggle_cam_visibility {
        active_cameras.set_active(camera, !previously_active, &mut active_cameras_raw);
    }
}

fn spawn_editor_cameras(mut commands: Commands) {
    commands
        .spawn_bundle(PerspectiveCameraBundle {
            camera: Camera {
                name: None,
                ..Default::default()
            },
            transform: Transform::from_xyz(0.0, 2.0, 5.0),
            ..Default::default()
        })
        .insert(camera_3d_free::FlycamControls::default())
        .insert(crate::hierarchy::picking::EditorRayCastSource::new())
        .insert(EditorCamera)
        .insert(EditorCamera3dFree)
        .insert(HideInEditor)
        .insert(Name::new("Editor Camera 3D Free"));

    commands
        .spawn_bundle(PerspectiveCameraBundle {
            camera: Camera {
                name: None,
                ..Default::default()
            },
            tr


local function createJailTimer(target, jailTime)
    if jailTime == 0 then return end

    timer.Create("FAdmin_jail" .. target:UserID(), jailTime, 1, function()
        if not IsValid(target) then return end
        if not target:FAdmin_GetGlobal("fadmin_jailed") then return end
        timer.Remove("FAdmin_jail_watch" .. target:UserID())
        target:FAdmin_SetGlobal("fadmin_jailed", false)

        for k in pairs(target.FAdminJailProps) do
            if not IsValid(k) then continue end
            k:SetCanRemove(true)
            k:Remove()
        end

        target.FAdminJailProps = nil
    end)
end

local function Jail(ply, cmd, args)
    if not args[1] then return false end

    local targets = FAdmin.FindPlayer(args[1])
    if not targets or #targets == 1 and not IsValid(targets[1]) then
        FAdmin.Messages.SendMessage(ply, 1, "Player not found")
        return false
    end

    local JailType = FAdmin.PlayerActions.JailTypes[tonumber(args[2])] or args[2] or FAdmin.PlayerActions.JailTypes[2]
    JailType = string.lower(JailType)
    local JailTime = tonumber(args[3]) or 0
    local time = ""

    for _, target in ipairs(targets) do
        if not IsValid(target) then continue end
        if not FAdmin.Access.PlayerHasPrivilege(ply, "Jail", target) then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end

        local jailDistance

        ply:ExitVehicle()

        local JailProps = {}
        if JailType == "unjail" or string.lower(cmd) == "unjail" then
            if target.FAdminJailProps then
                for k in pairs(target.FAdminJailProps) do
                    if not IsValid(k) then continue end
                    k:SetCanRemove(true)
                    k:Remove()
                end
            end

            target.FAdminJailProps = nil
            timer.Remove("FAdmin_jail" .. target:UserID())
            timer.Remove("FAdmin_jail_watch" .. target:UserID())
            target:FAdmin_SetGlobal("fadmin_jailed", false)
        elseif JailType == "small" then
            jailDistance = 50
            table.insert(JailProps, {pos = Vector(0,0,58), ang = Angle(0,0,0), model = "models/props_wasteland/laundry_dryer001.mdl"})
        elseif JailType == "normal" then
            jailDistance = 70
            table.insert(JailProps, {pos = Vector(0,0,-5), ang = Angle(90,0,0), model = "models/props_building_details/Storefront_Template001a_Bars.mdl"})
            table.insert(JailProps, {pos = Vector(0,0,97), ang = Angle(90,0,0), model = "models/props_building_details/Storefront_Template001a_Bars.mdl"})

            table.insert(JailProps, {pos = Vector(21,31,46), ang = Angle(0,90,0), model = "models/props_building_details/Storefront_Template001a_Bars.mdl"})
            table.insert(JailProps, {pos = Vector(21,-31,46), ang = Angle(0,90,0), model = "models/props_building_details/Storefront_Template001a_Bars.mdl"})
            table.insert(JailProps, {pos = Vector(-21,31,46), ang = Angle(0,90,0), model = "models/props_building_details/Storefront_Template001a_Bars.mdl"})
            table.insert(JailProps, {pos = Vector(-21,-31,46), ang = Angle(0,90,0), model = "models/props_bui


/* @(#)e_fmod.c 1.3 95/01/18 */
/*-
 * ====================================================
 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
 *
 * Developed at SunSoft, a Sun Microsystems, Inc. business.
 * Permission to use, copy, modify, and distribute this
 * software is freely granted, provided that this notice
 * is preserved.
 * ====================================================
 */

#include <float.h>
#include <math.h>

#include "math_private.h"

static const double Zero[] = {0.0, -0.0,};

/*
 * Return the IEEE remainder and set *quo to the last n bits of the
 * quotient, rounded to the nearest integer.  We choose n=31 because
 * we wind up computing all the integer bits of the quotient anyway as
 * a side-effect of computing the remainder by the shift and subtract
 * method.  In practice, this is far more bits than are needed to use
 * remquo in reduction algorithms.
 */
double
remquo(double x, double y, int *quo)
{
	int32_t n,hx,hy,hz,ix,iy,sx,i;
	u_int32_t lx,ly,lz,q,sxy;

	EXTRACT_WORDS(hx,lx,x);
	EXTRACT_WORDS(hy,ly,y);
	sxy = (hx ^ hy) & 0x80000000;
	sx = hx&0x80000000;		/* sign of x */
	hx ^=sx;		/* |x| */
	hy &= 0x7fffffff;	/* |y| */

    /* purge off exception values */
	if((hy|ly)==0||(hx>=0x7ff00000)||	/* y=0,or x not finite */
	  ((hy|((ly|-ly)>>31))>0x7ff00000))	/* or y is NaN */
	    return (x*y)/(x*y);
	if(hx<=hy) {
	    if((hx<hy)||(lx<ly)) {
		q = 0;
		goto fixup;	/* |x|<|y| return x or x-y */
	    }
	    if(lx==ly) {
		*quo = 1;
		return Zero[(u_int32_t)sx>>31];	/* |x|=|y| return x*0*/
	    }
	}

    /* determine ix = ilogb(x) */
	if(hx<0x00100000) {	/* subnormal x */
	    if(hx==0) {
		for (ix = -1043, i=lx; i>0; i<<=1) ix -=1;
	    } else {
		for (ix = -1022,i=(hx<<11); i>0; i<<=1) ix -=1;
	    }
	} else ix = (hx>>20)-1023;

    /* determine iy = ilogb(y) */
	if(hy<0x00100000) {	/* subnormal y */
	    if(hy==0) {
		for (iy = -1043, i=ly; i>0; i<<=1) iy -=1;
	    } else {
		for (iy = -1022,i=(hy<<11); i>0; i<<=1) iy -=1;
	    }
	} else iy = (hy>>20)-1023;

    /* set up {hx,lx}, {hy,ly} and align y to x */
	if(ix >= -1022)
	    hx = 0x00100000|(0x000fffff&hx);
	else {		/* subnormal x, shift x to normal */
	    n = -1022-ix;
	    if(n<=31) {
	        hx = (hx<<n)|(lx>>(32-n));
	        lx <<= n;
	    } else {
		hx = lx<<(n-32);
		lx = 0;
	    }
	}
	if(iy >= -1022)
	    hy = 0x00100000|(0x000fffff&hy);
	else {		/* subnormal y, shift y to normal */
	    n = -1022-iy;
	    if(n<=31) {
	        hy = (hy<<n)|(ly>>(32-n));
	        ly <<= n;
	    } else {
		hy = ly<<(n-32);
		ly = 0;
	    }
	}

    /* fix point fmod */
	n = ix - iy;
	q = 0;
	while(n--) {
	    hz=hx-hy;lz=lx-ly; if(lx<ly) hz -= 1;
	    if(hz<0){hx = hx+hx+(lx>>31); lx = lx+lx;}
	    else {hx = hz+hz+(lz>>31); lx = lz+lz; q++;}
	    q <<= 1;
	}
	hz=hx-hy;lz=lx-ly; if(lx<ly) hz -= 1;
	if(hz>=0) {hx=hz;lx=lz;q++;}

    /* convert back to floating value and restore the sign */
	if((hx|lx)==0) {			/* return sign(x)*0 */
	    *quo = (sxy ? -q : q);
	    return Zero[(u_int32_t)sx>>31];
	}
	while(hx<0x00100000) {		/* normalize x */
	    hx = hx+hx+(lx>>31); lx = lx+lx;
	    iy -= 1;
	}
	if(iy>= -1022) {	/* normalize output */
	    hx = ((hx-0x00100000)|((iy+1023)<<20));
	} else {		/* subnormal output */
	    n = -1022 - iy;
	    if(n<=20) {
		lx = (lx>>n)|((u_int32_t)hx<<(32-n));
		hx >>= n;
	    } else if (n<=31) {
		lx = (hx<<(32-n))|(lx>>n); hx = sx;
	    } else {
		lx = hx>>(n-32); hx = sx;
	    }
	}
fixup:
	INSERT_WORDS(x,hx,lx);
	y = fabs(y);
	if (y < 0x1p-1021) {
	    if (x+x>y || (x+x==y && (q & 1))) {
		q++;
		x-=y;
	    }
	} else if (x>0.5*y || (x==0.5*y && (q & 1))) {
	    q++;
	    x-=y;
	}
	GET_HIGH_WORD(hx,x);
	SET_HIGH_WORD(x,hx^sx);
	q &= 0x7fffffff;
	*quo = (sxy ? -q : q);
	return x;
}

#if	LDBL_MANT_DIG == DBL_MANT_DIG
__strong_alias(remquol, remquo);
#endif	/* LDBL_MANT_DIG == DBL_MANT_DIG */


a),
	("nleftrightarrow", 0x21ae),
	("nleq", 0x2270),
	("nless", 0x226e),
	("nlsim", 0x2274),
	("nlt", 0x226e),
	("nltri", 0x22ea),
	("nltrie", 0x22ec),
	("nmid", 0x2224),
	("nopf", 0x1d55f),
	("not", 0xac),
	("notin", 0x2209),
	("notinva", 0x2209),
	("notinvb", 0x22f7),
	("notinvc", 0x22f6),
	("notni", 0x220c),
	("notniva", 0x220c),
	("notnivb", 0x22fe),
	("notnivc", 0x22fd),
	("npar", 0x2226),
	("nparallel", 0x2226),
	("npolint", 0x2a14),
	("npr", 0x2280),
	("nprcue", 0x22e0),
	("nprec", 0x2280),
	("nrArr", 0x21cf),
	("nrarr", 0x219b),
	("nrightarrow", 0x219b),
	("nrtri", 0x22eb),
	("nrtrie", 0x22ed),
	("nsc", 0x2281),
	("nsccue", 0x22e1),
	("nscr", 0x1d4c3),
	("nshortmid", 0x2224),
	("nshortparallel", 0x2226),
	("nsim", 0x2241),
	("nsime", 0x2244),
	("nsimeq", 0x2244),
	("nsmid", 0x2224),
	("nspar", 0x2226),
	("nsqsube", 0x22e2),
	("nsqsupe", 0x22e3),
	("nsub", 0x2284),
	("nsube", 0x2288),
	("nsubseteq", 0x2288),
	("nsucc", 0x2281),
	("nsup", 0x2285),
	("nsupe", 0x2289),
	("nsupseteq", 0x2289),
	("ntgl", 0x2279),
	("ntilde", 0xf1),
	("ntlg", 0x2278),
	("ntriangleleft", 0x22ea),
	("ntrianglelefteq", 0x22ec),
	("ntriangleright", 0x22eb),
	("ntrianglerighteq", 0x22ed),
	("nu", 0x3bd),
	("num", 0x23),
	("numero", 0x2116),
	("numsp", 0x2007),
	("nvDash", 0x22ad),
	("nvHarr", 0x2904),
	("nvdash", 0x22ac),
	("nvinfin", 0x29de),
	("nvlArr", 0x2902),
	("nvrArr", 0x2903),
	("nwArr", 0x21d6),
	("nwarhk", 0x2923),
	("nwarr", 0x2196),
	("nwarrow", 0x2196),
	("nwnear", 0x2927),
	("oS", 0x24c8),
	("oacute", 0xf3),
	("oast", 0x229b),
	("ocir", 0x229a),
	("ocirc", 0xf4),
	("ocy", 0x43e),
	("odash", 0x229d),
	("odblac", 0x151),
	("odiv", 0x2a38),
	("odot", 0x2299),
	("odsold", 0x29bc),
	("oelig", 0x153),
	("ofcir", 0x29bf),
	("ofr", 0x1d52c),
	("ogon", 0x2db),
	("ograve",


             "z4IKNSEkee1KO9z0HTftcC/dcfsstiWHO4h1IDglFeqCCjX6e0jCdQfa4fZMmr0Wm9diY0vBUJIw\n" +
                "RjI6LVe8fqajcZTZ2mwLLKlQI/GQhIhHrNa9STNwKeD1h1qtBCDRq4C9uWKhWKUQqRTIOiQhIm4F\n" +
                "C+PpQVVGf3LBqqlcq0H2CCQhApFJwG5rCASSEIFAEiIQCCQhAoEkRCAQSEIEAkmIQCCQhAgEkhCB\n" +
                "QCAJEQgkIQKBQBIiEEhCBAKBJEQgkIQIBAJJiEAgCREIBJIQgUASIhAIJCECgSREIBBIQgQCSYhA\n" +
                "IJCECASSEIFAIAkRCCQhAoFAEiIQSEIEAoEkRCCQhAgEAkmIQCAJEQgEkhCBQBIiEAgkIQKBJEQg\n" +
                "EEhCBAJJiEAgkIQIBJIQgUAgCREIJCECgUASIhBIQgQCgSREIDID/x/SIJFenwIhyAAAAABJRU5E\n" +
                "rkJggg==\"}", ArticleModel.class));
        articlesDefault.add(gson.fromJson("{\"page\":2,\"link\":\"https://developer.ibm.com/code/patterns/use-mongoose-and-mongodb-to-serve-app-data/\",\"title\":\"cloud\",\"subtitle\":\"native\",\"image\":\"cloud\",\"subtext\":\"\",\"description\":\"this app was architected to scale on cloud technology\",\"imageEncoded\":\"iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAIAAAD2HxkiAAAACXBIWXMAAAsSAAALEgHS3X78AAAQ\n" +
                "SElEQVR42u3dP0xb96LA8dP7OviYN4Cj58o1y7FgsRxfyRlsXd5AOF2gCcODASR3KnS7cceKLF2I\n" +
                "OtbcrZApSGSADoTAUkOGx5U9xINjsTiyF7vWsxSTocaWbiXe4ApxSXp+x3+wz++c72eK1CQl9u97\n" +
                "zu/8+51PLi8vFQDD8xc+AoAIASIEQIQAEQIgQoAIARAhQIQAiBAgQgBECBAhACIEiBAAEQJECIAI\n" +
                "ASIEQIQAEQIgQoAIARAhQIQAiBAgQgBECBAhACIEiBAAEQJECIAIASIEQIQAEQIgQoAIARAhQIQA\n" +
                "iBAgQgBECBAhACIEiBAAEQJECIAIASIEQIQAEQIgQoAIARAhQIQAiBAgQgBECBAhACIEiBAAEQJE\n" +
                "CBAhACIEiBAAEQJECIAIASIEQIQAEQIgQsBJPuUjsKVCvvjHL96UbvynO94xz2ejiqKoI+q45uOz\n" +
                "IkL0J7lysVopVd/Vzt/mSx39WY931OMd


# =============================================================================
#  Filename: rag_facade_demo.py
#
#  Short Description: Demo of the new rag() facade method in Animals class.
#
#  Creation date: 2025-01-06
#  Author: Asif Qamar
# =============================================================================

"""
Demo of the new rag() facade method in the Animals class.

This example shows how to use the convenient rag() method that encapsulates
the entire RAG pipeline: search + LLM response in a single method call.
"""

import sys
from pathlib import Path
import time

# Add the src directory to the path so we can import our modules
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from rag_to_riches.corpus.animals import Animals
from rag_to_riches.vectordb.embedded_vectordb import EmbeddedVectorDB
from rag_to_riches.vectordb.embedder import SimpleTextEmbedder
from loguru import logger

def main():
    """Main demo function using the new rag() facade method."""
    print("🎯 RAG Facade Method Demo")
    print("=" * 50)

    # Example user queries
    queries = [
        "What do animals teach us about friendship?",
        "How do literary authors view animal companionship?",
        "What is the wisdom about animal loyalty?"
    ]

    # Initialize components with retry logic
    print("\n🔍 Initializing vector DB and embedder...")
    try:
        vector_db = EmbeddedVectorDB()
        print("   ✅ Vector database connected")
    except Exception as e:
        print(f"   ❌ Vector database failed: {str(e)}")
        return None

    # Try to initialize embedder with retry logic
    embedder = None
    max_retries = 3
    for attempt in range(max_retries):
        try:
            print(f"   🔄 Loading embedder (attempt {attempt + 1}/{max_retries})...")
            embedder = SimpleTextEmbedder(model_name="sentence-transformers/all-MiniLM-L6-v2")
            print("   ✅ Embedder loaded successfully")
            break
        except Exception as e:
            print(f"   ⚠  Attempt {attempt + 1} failed: {str(e)}")
            if attempt < max_retries - 1:
                print("   🔄 Retrying in 5 seconds...")
                time.sleep(5)
            else:
                print("   ❌ All attempts failed. Trying with default model...")
                try:
                    embedder = SimpleTextEmbedder()  # Use default model
                    print("   ✅ Default embedder loaded successfully")
                except Exception as e2:
                    print(f"   ❌ Default embedder also failed: {str(e2)}")
                    return None

    if embedder is None:
        print("   ❌ Could not initialize any embedder")
        return None

    try:
        animals = Animals(vector_db=vector_db, embedder=embedder)
        print("   ✅ Animals class initialized successfully")
    except Exception as e:
        print(f"   ❌ Animals class initialization failed: {str(e)}")
        return None

    # Demo 1: Structured RAG response
    print("\n" + "="*60)
    print("1⃣ STRUCTURED RAG RESPONSE")
    print("="*60)

    query = queries[0]
    print(f"\n📝 Query: '{query}'")

    try:
        # Use the new rag() facade method
        result = animals.rag(
            user_query=query,
            limit=5,
            response_type="structured"
        )

        print(f"\n✅ RAG pipeline completed successfully!")
        print(f"   📊 Found {result['query_info']['results_count']} search results")
        print(f"   🤖 Generated {result['query_info']['response_type']} LLM response")

        # Display the structured response
        print("\n" + "🤖"*20)
        print("🤖 LLM RESPONSE")
        print("🤖"*20)
        animals.display_llm_response(result['llm_response'], query)

        # Show some search result details
        print(f"\n📋 Search Results Summary:")
        print(f"   • Total results: {len(result['search_results'])}")
        if result['search_results']:
            top_result = result['search_results'][0]
            print(f"   • Top score: {top_result.score:.3f}")
            print(f"   • Top quote: '{top_result.payload.get('content', 'N/A')[:80]}...'")

    except Exception as e:
        print(f"   ❌ RAG pipeline failed: {str(e)}")

    # Demo 2: Simple RAG response
    print("\n" + "="*60)
    print("2⃣ SIMPLE RAG RESPONSE")
    print("="*60)

    query = queries[1]
    print(f"\n📝 Query: '{query}'")

    try: