/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef __nsAppShellService_h
#define __nsAppShellService_h

#include "nsIAppShellService.h"
#include "nsIObserver.h"

//Interfaces Needed
#include "nsWebShellWindow.h"
#include "nsStringFwd.h"
#include "nsAutoPtr.h"
#include "nsITabParent.h"
#include "mozilla/Attributes.h"

// {0099907D-123C-4853-A46A-43098B5FB68C}
#define NS_APPSHELLSERVICE_CID \
{ 0x99907d, 0x123c, 0x4853, { 0xa4, 0x6a, 0x43, 0x9, 0x8b, 0x5f, 0xb6, 0x8c } }

class nsAppShellService final : public nsIAppShellService,
                                public nsIObserver
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIAPPSHELLSERVICE
  NS_DECL_NSIOBSERVER

  nsAppShellService();

protected:
  ~nsAppShellService();

  nsresult CreateHiddenWindowHelper(bool aIsPrivate);
  void EnsurePrivateHiddenWindow();

  nsresult JustCreateTopWindow(nsIXULWindow *aParent,
                               nsIURI *aUrl,
                               uint32_t aChromeMask,
                               int32_t aInitialWidth, int32_t aInitialHeight,
                               bool aIsHiddenWindow,
                               nsITabParent *aOpeningTab,
                               nsWebShellWindow **aResult);
  uint32_t CalculateWindowZLevel(nsIXULWindow *aParent, uint32_t aChromeMask);

  RefPtr<nsWebShellWindow>  mHiddenWindow;
  RefPtr<nsWebShellWindow>  mHiddenPrivateWindow;
  bool                        mXPCOMWillShutDown;
  bool                        mXPCOMShuttingDown;
  uint16_t                    mModalWindowCount;
  bool                        mApplicationProvidedHiddenWindow;
  uint32_t                    mScreenId;
};

#endif


CP_SecurityInformation),
    #[asn(key = 280)]
    Id_EndIndication(EndIndication),
    #[asn(key = 251)]
    Id_EnhancedCoverageRestricted(EnhancedCoverageRestricted),
    #[asn(key = 0)]
    Id_MME_UE_S1AP_ID(MME_UE_S1AP_ID),
    #[asn(key = 278)]
    Id_Subscription_Based_UE_DifferentiationInfo(Subscription_Based_UE_DifferentiationInfo),
    #[asn(key = 252)]
    Id_UE_Level_QoS_Parameters(E_RABLevelQoSParameters),
    #[asn(key = 74)]
    Id_UERadioCapability(UERadioCapability),
    #[asn(key = 314)]
    Id_UERadioCapabilityID(UERadioCapabilityID),
    #[asn(key = 8)]
    Id_eNB_UE_S1AP_ID(ENB_UE_S1AP_ID),
}

#[derive(Debug, AperCodec)]
#[asn(type = "SEQUENCE", extensible = false)]
pub struct ConnectionEstablishmentIndicationProtocolIEs_Entry {
    #[asn(key_field = true)]
    pub id: ProtocolIE_ID,
    pub criticality: Criticality,
    pub value: ConnectionEstablishmentIndicationProtocolIEs_EntryValue,
}

#[derive(Debug, AperCodec)]
#[asn(
    type = "SEQUENCE-OF",
    sz_extensible = false,
    sz_lb = "0",
    sz_ub = "65535"
)]
pub struct ConnectionEstablishmentIndicationProtocolIEs(
    pub Vec<ConnectionEstablishmentIndicationProtocolIEs_Entry>,
);

#[derive(Debug, AperCodec)]
#[asn(type = "SEQUENCE", extensible = false)]
pub struct ContextatSourceIE_Extensions_Entry {}

#[derive(Debug, AperCodec)]
#[asn(
    type = "SEQUENCE-OF",
    sz_extensible = false,
    sz_lb = "1",
    sz_ub = "65535"
)]
pub struct ContextatSourceIE_Extensions(pub Vec<ContextatSourceIE_Extensions_Entry>);

#[derive(Debug, AperCodec)]
#[asn(type = "SEQUENCE", extensible = false)]
pub struct CriticalityDiagnosticsIE_Extensions_Entry {}

#[derive(Debug, AperCodec)]
#[asn(
    type = "SEQUENCE-OF",
    sz_extensible = false,
    sz_lb = "1",
    sz_ub = "65535"
)]
pub struct CriticalityDiagnosticsIE_Extensions(pub Vec<CriticalityDiagnosticsIE_Extensions_Entry>);

#[derive(Debug, AperCodec)]
#[asn(type = "SEQUENCE", extensible = false)]
pub struct CriticalityDiagnostics_IE_ItemIE_Extensions_Entry {}

#[derive(Debug, AperCodec)]
#[asn(
    type = "SEQUENCE-OF",
    sz_extensible = false,
    sz_lb = "1",
    sz_ub = "65535"
)]
pub struct CriticalityDiagnostics_IE_ItemIE_Extensions(
    pub Vec<CriticalityDiagnostics_IE_ItemIE_Extensions_Entry>,
);

#[derive(Debug, AperCodec)]
#[asn(type = "ENUMERATED", extensible = true, lb = "0", ub = "0")]
pub struct ENUMERATED_11(pub u8);
impl ENUMERATED_11 {
    pub const D_APS_HO_REQUIRED: u8 = 0u8;
}

#[derive(Debug, AperCodec)]
#[asn(type = "SEQUENCE", extensible = false)]
pub struct DAPSRequestInfoIE_


ls(runningTools);
	}

	@Test
	public void testOpenMultipleReuseTool() throws Exception {

		Program p = ToyProgramBuilder.buildSimpleProgram("y", this);
		rootFolder.createFile("Y", p, TaskMonitor.DUMMY);
		p.release(this);

		ToolOptions options = frontEndTool.getOptions(ToolConstants.TOOL_OPTIONS);
		options.setEnum(FrontEndTool.DEFAULT_TOOL_LAUNCH_MODE, DefaultLaunchMode.REUSE_TOOL);

		//Open 1st File
		DomainFile sampleDf = openInDefaultTool("sample");
		PluginTool[] runningTools = env.getProject().getToolManager().getRunningTools();
		assertEquals(1, runningTools.length);
		assertOpenFiles(runningTools[0], sampleDf);

		String toolName = runningTools[0].getName();

		//Open two additional files in same tool
		openInTool(toolName, "X", "Y");

		runningTools = env.getProject().getToolManager().getRunningTools();
		assertEquals(1, runningTools.length);

		DomainFile[] domainFiles0 = runningTools[0].getDomainFiles();
		assertEquals(3, domainFiles0.length);

		exitTools(runningTools);
	}

	@Test
	public void testOpenWith() throws Exception {

		GTreeNode npNode = rootNode.getChild("sample");
		setSelectionPath(npNode.getTreePath());
		waitForTree();

		ToolChest tc = env.getProject().getLocalToolChest();
		ToolTemplate[] configs = tc.getToolTemplates();

		DockingActionIf action = getAction("Open" + configs[0].getName());
		performAction(action, getFrontEndContext(), true);
		verifyToolExistsAndCloseTool();
	}

	@Test
	public void testOpenWithDoubleClick() throws Exception {
		// make sure that the Code Browser tool is the default
		ToolChest tc = env.getProject().getLocalToolChest();
		ToolTemplate[] configs = tc.getToolTemplates();
		ToolTemplate codeBrowserConfig = null;
		for (ToolTemplate config : configs) {
			if ("CodeBrowser".equals(config.getName())) {
				codeBrowserConfig = config;
			}
		}

		if (codeBrowserConfig == null) {
			Assert.fail("Unable to find the Code Browser config file.");
		}

		// double click on the program node
		GTreeNode npNode = rootNode.getChild("sample");
		JTree jTree = (JTree) invokeInstanceMethod("getJTree", tree);
		Rectangle rect = jTree.getPathBounds(npNode.getTreePath());
		setSelectionPath(npNode.getTreePath());
		waitForTree();

		clickMouse(jTree, MouseEvent.BUTTON1, rect.x, rect.y, 2, 0);

		// make sure that the tool is loaded and processes all of the tasks it launches
		Window window = waitForToolLaunch();

		// DEBUG:
		if (window == null) {
			// see if any tools have been launched
			PluginTool[] runningTools = frontEndTool.getToolServices().getRunningTools();
			for (PluginTool tool : runningTools) {
				System.err.println("\t\"" + tool.getName() + "\"");
				JFrame toolFrame = tool.getToolFrame();
				System.err.println("\t\twith window: " + toolFrame.getTitle());
			}

			System.err.println("Open Windows: ");
			System.err.println(getOpenWindowsAsString());
		}

		assertNotNull(window);
		waitForBusyTool(env.getProject().getToolManager().getRunningTools()[0]);
		waitForTasks();

		verifyToolExistsAndCloseTool();
	}

	private Window waitForToolLaunch() {

		waitForSwing();

		long start = System.currentTimeMillis();
		int tryCount = 0;
		Window window = null;
		while (window == null && tryCount < 5) {
			++tryCount;
			window = waitForValueWithoutFailing(() -> {
				return getWindowByTitleContaining(null,
					"CodeBrowser: " + PROJECT_


= self.current_creature()?;
    if current.can_move() {
      Ok(CombatMove {
        combat: self,
        movement_left: self.current_creature()?.speed() - self.combat.movement_used,
      })
    } else {
      Err(GameError::CannotAct(current.id()).into())
    }
  }

  pub fn reroll_initiative(&self) -> Result<ChangedCombat<'game>, GameError> {
    let cids = self.combat.creature_ids();
    let combatants = Combat::roll_initiative(self.game, cids)?;
    self.change_with(CombatLog::RerollInitiative(combatants))
  }

  pub fn change(&self) -> ChangedCombat<'game> {
    ChangedCombat { scene: self.scene, combat: self.combat.clone(), logs: vec![], game: self.game }
  }

  pub fn change_with(&self, log: CombatLog) -> Result<ChangedCombat<'game>, GameError> {
    let combat = self.apply_log(&log)?;
    Ok(ChangedCombat { scene: self.scene, combat: combat, game: self.game, logs: vec![log] })
  }

  pub fn current_creature(&self) -> Result<DynamicCreature<'game, 'game>, GameError> {
    self.game.get_creature(self.combat.current_creature_id())
  }

  pub fn current_pos(&self) -> Result<Point3, GameError> {
    self.scene.get_pos(self.combat.current_creature_id())
  }
}

fn sort_combatants(
  mut combatants: Vec<(CreatureID, i16)>,
) -> Result<nonempty::NonEmptyWithCursor<(CreatureID, i16)>, GameError> {
  combatants.sort_by_key(|&(_, i)| -i);
  nonempty::NonEmptyWithCursor::from_vec(combatants)
    .ok_or_else(|| GameError::CombatMustHaveCreatures.into())
}

impl Combat {
  pub fn new(scene: SceneID, combatants: Vec<(CreatureID, i16)>) -> Result<Combat, GameError> {
    Ok(Combat {
      scene: scene,
      movement_used: Zero::zero(),
      creatures: sort_combatants(combatants)?,
    })
  }

  pub fn creature_ids(&self) -> Vec<CreatureID> { self.creatures.iter().map(|&(c, _)| c).collect() }

  pub fn roll_initiative(
    game: &Game, cids: Vec<CreatureID>,
  ) -> Result<Vec<(CreatureID, i16)>, GameError> {
    cids
      .iter()
      .map(|cid| {
        let creature = game.get_creature(*cid)?;
        Ok((*cid, creature.creature.initiative.roll().1 as i16))
      })
      .collect::<Result<Vec<(CreatureID, i16)>, GameError>>()
  }

  pub fn current_creature_id(&self) -> CreatureID { self.creatures.get_current().0 }

  pub fn contains_creature(&self, cid: CreatureID) -> bool {
    self.creatures.iter().any(|&(c, _)| c == cid)
  }

  /// the Option<Combat> will be None if you're removing the last creature from a combat.
  pub fn remove_from_combat(&self, cid: CreatureID) -> Result<Option<Combat>, GameError> {
    let mut combat = self.clone();
    let idx = combat
      .creatures
      .iter()
      .position(|&(c, _)| c == cid)
      .ok_or_else(|| GameError::CreatureNotFound(cid.to_string()))?;
    match combat.creatures.remove(idx) {
      Err(nonempty::Error::OutOfBounds { .. }) => Err(
        GameError::


* at a given offset
     */
    private fun writeShort(s: Int, buf: ByteBuffer) {
        buf.put((s and 0xff).toByte())
        buf.put((s shr 8 and 0xff).toByte())
    }

    private var headerWrited = false
    private suspend fun writeHeader() {
        if (headerWrited)
            return
        header.clear()
        stream.write(header)
        headerWrited = true
    }
}

fun AsyncOutput.gzip(level: Int = 6, bufferSize: Int = 1024, closeStream: Boolean = true) =
    AsyncGZIPOutput(
        stream = this,
        level = level,
        bufferSize = bufferSize,
        closeStream = closeStream,
    )

private val header = ByteBuffer.alloc(10).also {
    it.put(GZIP_MAGIC1)// Magic number (short)
    it.put(GZIP_MAGIC2)  // Magic number (short)
    it.put(DEFLATED)  // Compression method (CM)
    it.put(0)  // Flags (FLG)
    it.put(0)  // Modification time MTIME (int)
    it.put(0)  // Modification time MTIME (int)
    it.put(0)  // Modification time MTIME (int)
    it.put(0)  // Modification time MTIME (int)
    it.put(0)  // Extra flags (XFLG)
    it.put(0) // Operating system (OS)
}package pw.binom.io.examples.httpServer

import pw.binom.ByteBufferPool
import pw.binom.async
import pw.binom.charset.Charsets
import pw.binom.io.*
import pw.binom.network.NetworkAddress
import pw.binom.network.NetworkDispatcher
import kotlin.time.ExperimentalTime

@OptIn(ExperimentalTime::class)
fun main(args: Array<String>) {
    val nioManager = NetworkDispatcher()
    val server = nioManager.bindTcp(NetworkAddress.Immutable(port = 7328))
    val pool = ByteBufferPool(10)
    var count = 0L
    async {
        val c = Charsets.UTF8
        while (true) {
            count++
            println("accepting")
            val client = server.accept()!!
            println("accepted")
            async {
                println("Connected!")
                val reader = client.bufferedReader(pool, charBufferSize = 1024)
                val writer = client.bufferedWriter(pool, charBufferSize = 1024)
//                client.write(ByteBuffer.wrap("1-Hello!\r\n".encodeToByteArray()))
//                writer.append("2-Hello!\r\n")
//                println("Flushing...")
//                writer.flush()
//                println("Flushed!")
//                client.close()
//                return@async
                while (true) {
                    try {
                        val input = reader.readln()?.trim() ?: break
                        val output = input.reversed()
                        writer.append(output).append("\r\n")
//                        writer.appendln("GET /")
                        writer.flush()
                    } catch (e: IOException) {
                        client.close()
                        break
                    }
                }
            }
        }
    }
    while (true) {
        nioManager.select()
    }
}package pw.binom.json

import pw.binom.io.AsyncAppendable

interface JsonNode {
    suspend fun accept(visiter: JsonVisiter)
}

class JsonObject(private val childs: MutableMap<String, JsonNode?> = HashMap()) : JsonNode, MutableMap<String, JsonNode?> by childs {
    override suspend fun accept(visiter: JsonVisiter) {
        accept(visiter.objectValue())
    }

    suspend fun accept(visiter: JsonObjectVisiter) {
        visiter.start()
        childs.forEach {
            if (it.value == null)
                visiter.property(it.key).nullValue()
            else


 unittest.hasLength(2));
  unittest.expect(o[0], unittest.equals('foo'));
  unittest.expect(o[1], unittest.equals('foo'));
}

core.int buildCounterInTotoProvenance = 0;
api.InTotoProvenance buildInTotoProvenance() {
  final o = api.InTotoProvenance();
  buildCounterInTotoProvenance++;
  if (buildCounterInTotoProvenance < 3) {
    o.builderConfig = buildBuilderConfig();
    o.materials = buildUnnamed28();
    o.metadata = buildMetadata();
    o.recipe = buildRecipe();
  }
  buildCounterInTotoProvenance--;
  return o;
}

void checkInTotoProvenance(api.InTotoProvenance o) {
  buildCounterInTotoProvenance++;
  if (buildCounterInTotoProvenance < 3) {
    checkBuilderConfig(o.builderConfig!);
    checkUnnamed28(o.materials!);
    checkMetadata(o.metadata!);
    checkRecipe(o.recipe!);
  }
  buildCounterInTotoProvenance--;
}

core.List<api.Subject> buildUnnamed29() => [buildSubject(), buildSubject()];

void checkUnnamed29(core.List<api.Subject> o) {
  unittest.expect(o, unittest.hasLength(2));
  checkSubject(o[0]);
  checkSubject(o[1]);
}

core.int buildCounterInTotoSlsaProvenanceV1 = 0;
api.InTotoSlsaProvenanceV1 buildInTotoSlsaProvenanceV1() {
  final o = api.InTotoSlsaProvenanceV1();
  buildCounterInTotoSlsaProvenanceV1++;
  if (buildCounterInTotoSlsaProvenanceV1 < 3) {
    o.P_type = 'foo';
    o.predicate = buildSlsaProvenanceV1();
    o.predicateType = 'foo';
    o.subject = buildUnnamed29();
  }
  buildCounterInTotoSlsaProvenanceV1--;
  return o;
}

void checkInTotoSlsaProvenanceV1(api.InTotoSlsaProvenanceV1 o) {
  buildCounterInTotoSlsaProvenanceV1++;
  if (buildCounterInTotoSlsaProvenanceV1 < 3) {
    unittest.expect(o.P_type!, unittest.equals('foo'));
    checkSlsaProvenanceV1(o.predicate!);
    unittest.expect(o.predicateType!, unittest.equals('foo'));
    checkUnnamed29(o.subject!);
  }
  buildCounterInTotoSlsaProvenanceV1--;
}

core.List<api.Subject> buildUnnamed30() => [buildSubject(), buildSubject()];

void checkUnnamed30(core.List<api.Subject> o) {
  unittest.expect(o, unittest.hasLength(2));
  checkSubject(o[0]);
  checkSubject(o[1]);
}

core.int buildCounterInTotoStatement = 0;
api.InTotoStatement buildInTotoStatement() {
  final o = api.InTotoStatement();
  buildCounterInTotoStatement++;
  if (buildCounterInTotoStatement < 3) {
    o.P_type = 'foo';
    o.predicateType = 'foo';
    o.provenance = buildInTotoProvenance();
    o.slsaProvenance = buildSlsaProvenance();
    o.slsaProvenanceZeroTwo = buildSlsaProvenanceZeroTwo();
    o.subject = buildUnnamed30();
  }
  buildCounterInTotoStatement--;
  return o;
}

void checkInTotoStatement(api.InTotoStatement o) {
  buildCounterInTotoStatement++;
  if (buildCounterInTotoStatement < 3) {
    unittest.expect(o.P_type!, unittest.equals('foo'));


? matricula;
	DateTime? dataCadastro;
	DateTime? dataAdmissao;
	DateTime? dataDemissao;
	String? ctpsNumero;
	String? ctpsSerie;
	DateTime? ctpsDataExpedicao;
	String? ctpsUf;
	String? observacao;
	String? logradouro;
	String? numero;
	String? complemento;
	String? bairro;
	String? cidade;
	String? cep;
	int? municipioIbge;
	String? uf;
	int? idPessoa;
	int? idCargo;
	int? idSetor;

	ViewPessoaColaborador({
			id,
			nome,
			tipo,
			email,
			site,
			cpfCnpj,
			rgIe,
			matricula,
			dataCadastro,
			dataAdmissao,
			dataDemissao,
			ctpsNumero,
			ctpsSerie,
			ctpsDataExpedicao,
			ctpsUf,
			observacao,
			logradouro,
			numero,
			complemento,
			bairro,
			cidade,
			cep,
			municipioIbge,
			uf,
			idPessoa,
			idCargo,
			idSetor,
		});

	static List<String> campos = <String>[
		'ID',
		'NOME',
		'TIPO',
		'EMAIL',
		'SITE',
		'CPF_CNPJ',
		'RG_IE',
		'MATRICULA',
		'DATA_CADASTRO',
		'DATA_ADMISSAO',
		'DATA_DEMISSAO',
		'CTPS_NUMERO',
		'CTPS_SERIE',
		'CTPS_DATA_EXPEDICAO',
		'CTPS_UF',
		'OBSERVACAO',
		'LOGRADOURO',
		'NUMERO',
		'COMPLEMENTO',
		'BAIRRO',
		'CIDADE',
		'CEP',
		'MUNICIPIO_IBGE',
		'UF',
	];

	static List<String> colunas = <String>[
		'Id',
		'Nome',
		'Tipo',
		'Email',
		'Site',
		'Cpf Cnpj',
		'Rg Ie',
		'Matricula',
		'Data Cadastro',
		'Data Admissao',
		'Data Demissao',
		'Ctps Numero',
		'Ctps Serie',
		'Ctps Data Expedicao',
		'Ctps Uf',
		'Observacao',
		'Logradouro',
		'Numero',
		'Complemento',
		'Bairro',
		'Cidade',
		'Cep',
		'Municipio Ibge',
		'Uf',
	];

	ViewPessoaColaborador.fromJson(Map<String, dynamic> jsonDados) {
		id = jsonDados['id'];
		nome = jsonDados['nome'];
		tipo = jsonDados['tipo'];
		email = jsonDados['email'];
		site = jsonDados['site'];
		cpfCnpj = jsonDados['cpfCnpj'];
		rgIe = jsonDados['rgIe'];
		matricula = jsonDados['matricula'];
		dataCadastro = jsonDados['dataCadastro'] != null ? DateTime.tryParse(jsonDados['dataCadastro']) : null;
		dataAdmissao = jsonDados['dataAdmissao'] != null ? DateTime.tryParse(jsonDados['dataAdmissao']) : null;
		dataDemissao = jsonDados['dataDemissao'] != null ? DateTime.tryParse(jsonDados['dataDemissao']) : null;
		ctpsNumero = jsonDados['ctpsNumero'];
		ctpsSerie = jsonDados['ctpsSerie'];
		ctpsDataExpedicao = jsonDados['ctpsDataExpedicao'] != null ? DateTime.tryParse(jsonDados['ctpsDataExpedicao']) : null;
		ctpsUf = jsonDados['ctpsUf'];
		observacao = jsonDados['observacao'];
		logradouro = jsonDados['logradouro'];
		numero = jsonDados['numero'];
		complemento = jsonDados['complemento'];
		bairro = jsonDados['bairro'];
		cidade = jsonDados['cidade'];


ual pxr_boost::python::handle<> GetNoticePythonObject() const {
        TfPyLock lock;
        return pxr_boost::python::handle<>(pxr_boost::python::borrowed(_self));
    }

    // Arbitrary argument constructor (with a leading PyObject *) which
    // forwards to the base Notice class's constructor.
    template <typename... Args>
    TfPyNoticeWrapper(PyObject *self, Args... args)
        : NoticeType(args...)
        , _self(self) {}

private:
    PyObject *_self;

};

#define TF_INSTANTIATE_NOTICE_WRAPPER(T, Base) \
TF_REGISTRY_FUNCTION(TfType) \
{ \
    TfType::Define< TfPyNoticeWrapper<T, Base>, \
                    TfType::Bases<Base> >(); \
}

PXR_NAMESPACE_CLOSE_SCOPE

#endif // PXR_BASE_TF_PY_NOTICE_WRAPPER_H


0 0 0-1.112.338A2 2 0 0 0 5 5H3zm0 1h.941c.264 0 .348.356.112.474l-.457.228a2 2 0 0 0-.894.894l-.228.457C2.356 8.289 2 8.205 2 7.94V7a1 1 0 0 1 1-1z"/>'),TA=Bi("Table",'<path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm15 2h-4v3h4V4zm0 4h-4v3h4V8zm0 4h-4v3h3a1 1 0 0 0 1-1v-2zm-5 3v-3H6v3h4zm-5 0v-3H1v2a1 1 0 0 0 1 1h3zm-4-4h4V8H1v3zm0-4h4V4H1v3zm5-3v3h4V4H6zm4 4H6v3h4V8z"/>'),jA=Bi("Tablet",'<path d="M12 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h8zM4 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H4z"/><path d="M8 14a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>'),FA=Bi("TabletFill",'<path d="M2 2a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2zm7 11a1 1 0 1 0-2 0 1 1 0 0 0 2 0z"/>'),RA=Bi("TabletLandscape",'<path d="M1 4a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V4zm-1 8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2v8z"/><path d="M14 8a1 1 0 1 0-2 0 1 1 0 0 0 2 0z"/>'),DA=Bi("TabletLandscapeFill",'<path d="M2 14a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H2zm11-7a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"/>'),$A=Bi("Tag",'<path d="M6 4.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm-1 0a.5.5 0 1 0-1 0 .5.5 0 0 0 1 0z"/><path d="M2 1h4.586a1 1 0 0 1 .707.293l7 7a1 1 0 0 1 0 1.414l-4.586 4.586a1 1 0 0 1-1.414 0l-7-7A1 1 0 0 1 1 6.586V2a1 1 0 0 1 1-1zm0 5.586l7 7L13.586 9l-7-7H2v4.586z"/>'),NA=Bi("TagFill",'<path d="M2 1a1 1 0 0 0-1 1v4.586a1 1 0 0 0 .293.707l7 7a1 1 0 0 0 1.414 0l4.586-4.586a1 1 0 0 0 0-1.414l-7-7A1 1 0 0 0 6.586 1H2zm4 3.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/>'),UA=Bi("Tags",'<path d="M3 2v4.586l7 7L14.586 9l-7-7


family:Tahoma,Verdana,宋体;
}

.mini-grid, .mini-datagrid
{
    display:none;
}
.mini-grid-viewport
{
    background:white;

}

.mini-grid-columns
{

    position:relative;
    width:100%;
    overflow:hidden;
}
.mini-grid-columns-view
{
    position:relative;overflow:hidden;z-index:9;width:100%;
}
.mini-grid-columns-view .mini-grid-table
{
    z-index:100;
}

.mini-grid .mini-grid-rows
{
    overflow:hidden;width:100%;padding:0;z-index:0;
}
.mini-grid-rows-view
{
    position:relative;z-index:9;
    overflow:auto;height:100%;
    width:auto;
    _width:100%;

}
.mini-grid-rows-content
{
    *zoom:1;padding:0;margin:0;border:0;

}
.mini-grid-autoheight .mini-grid-rows-view,
.mini-grid-hidden-y
{
    overflow-y:hidden;
}

.mini-grid-table
{
    position:relative;
    text-align:left;

    table-layout:fixed;
    display:table;
    width:100%;
    height:1px;
}
.mini-grid-rowstable
{
    padding-bottom:1px;
}
.mini-grid-cell, .mini-grid-headerCell,
.mini-grid-filterCell, .mini-grid-summaryCell
{
    overflow: hidden;
    padding:0px;
    border:0;
    border-right:#d2d2d2 1px solid;
    border-bottom:#d2d2d2 1px solid;
    cursor:default;
    text-align:left;
    overflow:hidden;
    _text-overflow:ellipsis;

    padding-left:4px;
    padding-right:4px;
}
.mini-grid-summaryCell
{
    border-bottom:0;
    border-top:#d2d2d2 1px solid;
}
.mini-grid-cell-inner, .mini-grid-headerCell-inner
{
    font-size:9pt;
    font-family:Tahoma, Verdana, 宋体;
    line-height:18px;
    padding:0px;
    padding-top:3px;
    padding-bottom:3px;
    width:100%;
    position:relative;
    overflow:hidden;
    white-space:normal;

    word-break:break-all;
}

.mini-grid-cell-nowrap
{
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
    word-break:keep-all;
}
body .mini-grid-headerCell-nowrap
{
    white-space:nowrap;

    word-break:keep-all;
}
.mini-grid-headerCell
{
    background:#E7EBEF url(images/grid/header.png) repeat-x 0 0;
    border-right:#A5ACB5 1px solid;
    border-bottom:#A5ACB5 1px solid;
    overflow:visible;
    padding:0;
}
.mini-grid-headerCell-outer
{
    position:relative;
    padding-left:4px;
    padding-right:2px;
}
.mini-grid-headerCell-inner
{
    word-break:break-all;

    padding-top:3px;
    padding-bottom:5px;
    padding-top:4px\9;
    padding-bottom:4px\9;
    overflow:hidden;
}
.mini-grid .mini-grid-bottomCell
{

}
.mini-grid


在显示区域中以水平方向完全显示时控制显示的数据部分。
     *
虽然 HScrollBar 控件可以单独使用，但通常将它与其他组件一起使用来提供滚动功能。

     *
     * @includeExample  extension/eui/components/HScrollBarExample.ts
     * @version Egret 2.4
     * @version eui 1.0
     * @platform Web,Native
     * @language zh_CN
     */
    var HScrollBar = (function (_super) {
        __extends(HScrollBar, _super);
        function HScrollBar() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * @inheritDoc
         *
         * @version Egret 2.4
         * @version eui 1.0
         * @platform Web,Native
         */
        HScrollBar.prototype.updateDisplayList = function (unscaledWidth, unscaledHeight) {
            _super.prototype.updateDisplayList.call(this, unscaledWidth, unscaledHeight);
            var thumb = this.thumb;
            var viewport = this.$viewport;
            if (!thumb || !viewport) {
                return;
            }
            var bounds = egret.$TempRectangle;
            thumb.getPreferredBounds(bounds);
            var thumbWidth = bounds.width;
            var thumbY = bounds.y;
            var hsp = viewport.scrollH;
            var contentWidth = viewport.contentWidth;
            var width = viewport.width;
            if (hsp <= 0) {
                var scaleWidth = thumbWidth * (1 - (-hsp) / (width * 0.5));
                scaleWidth = Math.max(5, Math.round(scaleWidth));
                thumb.setLayoutBoundsSize(scaleWidth, NaN);
                thumb.setLayoutBoundsPosition(0, thumbY);
            }
            else if (hsp >= contentWidth - width) {
                var scaleWidth = thumbWidth * (1 - (hsp - contentWidth + width) / (width * 0.5));
                scaleWidth = Math.max(5, Math.round(scaleWidth));
                thumb.setLayoutBoundsSize(scaleWidth, NaN);
                thumb.setLayoutBoundsPosition(unscaledWidth - scaleWidth, thumbY);
            }
            else {
                var thumbX = (unscaledWidth - thumbWidth) * hsp / (contentWidth - width);
                thumb.setLayoutBoundsSize(NaN, NaN);
                thumb.setLayoutBoundsPosition(thumbX, thumbY);
            }
        };
        /**
         * @inheritDoc
         *
         * @version Egret 2.4
         * @version eui 1.0
         * @platform Web,Native
         */
        HScrollBar.prototype.onPropertyChanged = function (event) {
            switch (event.property) {
                case "scrollH":
                case "contentWidth":
                    this.invalidateDisplayList();
                    break;
            }
        };
        return HScrollBar;
    }(eui.ScrollBarBase));
    eui.HScrollBar = HScrollBar;
    __reflect(HScrollBar.prototype, "eui.HScrollBar");
})(eui || (eui = {}));
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLU


数据，则将all_vals与final_vals进行垂直拼接

train_df = pd.DataFrame(final_vals)  # 将提取的特征final_vals转换为DataFrame格式，并赋值给train_df
train_df.columns = ['time','lat','lon'] + [f'feat_{i}' for i in range(210)] + ['t2m','u10','v10','msl','tp']
# 添加列名，分别为时间特征、经度特征、纬度特征、210个特征向量、目标变量t2m、u10、v10、msl和tp

cols = ['time','lat','lon'] + [f'feat_{i}' for i in range(210)]
# 创建列名列表，包括时间特征、经度特征、纬度特征和210个特征向量列名

def train_model(train_x, train_y, label, seed=2023):
    # 初始化交叉验证的变量和参数
    oof = np.zeros(train_x.shape[0])  # 存储交叉验证的预测结果
    kf = KFold(n_splits=5, shuffle=True, random_state=seed)  # 5折交叉验证
    cv_scores = []  # 存储每一折的验证集分数

    for i, (train_index, valid_index) in enumerate(kf.split(train_x, train_y)):
        print('************************************ {} {}************************************'.format(str(i+1), str(seed)))
        trn_x, trn_y, val_x, val_y = train_x.iloc[train_index], train_y[train_index], train_x.iloc[valid_index], train_y[valid_index]
        #trn_x, trn_y, val_x, val_y：根据索引划分出当前折的训练集和验证集。

        # 设置CatBoost模型的参数
        params = {'learning_rate': 0.5,
                  'depth': 5,
                  'bootstrap_type':'Bernoulli',
                  'random_seed':2023,
                  'od_type': 'Iter',
                  'od_wait': 100,
                  'random_seed': 11,
                  'allow_writing_files': False,
                  'task_type':"GPU",
                  'devices':'0:1'}

        model = CatBoostRegressor(iterations=100, **params)  # 创建CatBoost回归模型
        model.fit(trn_x, trn_y, eval_set=(val_x, val_y),
                  cat_features=[],
                  use_best_model=True,
                  verbose=1)  # 在训练集上拟合模型并在验证集上进行评估
        # model.save_model(f'catboost_{label}_fold{i}.model')  # 保存模型
        model.save_model(f'model/catboost_{label}_fold{i}.model')  # 保存模型到指定路径
        val_pred  = model.predict(val_x)  # 在验证集上进行预测
        oof[valid_index] = val_pred  # 将验证集的预测结果填充到oof数组中

        cv_scores.append(np.sqrt(mean_squared_error(val_y, val_pred)))  # 计算并存储验证集的均方根误差

        if i == 0: #如果是第一折（i==0），计算特征重要性并保存到CSV文件。
            fea_ = model.feature_importances_
            fea_name = model.feature_names_
            fea_score = pd.DataFrame({'fea_name':fea_name, 'score':fea_})
            fea_score = fea_score.sort_values('score', ascending=False)
            fea_score.to_csv('feature_importances.csv', index=False)

        print(cv_scores) #打印当前折的验证集分数。
    return oof

oofs = []  # 存储所有特征的交叉验证预测结果

# 对每个特征进行训练和预测
for label in ['t2m', 'u10', 'v10', 'msl', 'tp']:
    print(f'==================== {label} ====================')

    # 调用train_model函数进行训练，并将返回的交叉验证预测结果存储到cat_oof变量中
    cat_oof = train_model(train_df[cols], train_df[label], label)

    # 将交叉验证预测结果添加到oofs列表中
    oofs.append(cat_oof)

def inter_model(test_x, label, seed=2023):
    kf = KFold(n_splits=5, shuffle=True, random_state=seed)  # 5折交叉验证
    test = np.zeros(test_x.shape[0])  # 存储测试集的预测结果

    params = {'learning_rate': 0.5, 'depth': 6, 'bootstrap_type':'Bernoulli','random_seed':seed, 'metric_period': 300,
              'od_type': 'Iter', 'od_wait': 100, 'random_seed': 11, 'allow_writing_files': False, 'task_type': 'CPU',
              'task_type':"GPU", 'devices':'0:1'}

    for i in range(0, 5):
        # print('************************************ {} {}************************************'.format(str(i+1), str(seed)))
        model = CatBoostRegressor(**params)
        # model.load_model(f'catboost_{label}_fold{i}.model')
        model.load_model(f'model/catboost_{label}_fold{i}.model')  # 加载训练好的模型
        test_pred = model.predict(test_x)  # 在测试集上进行预测
        test += test_pred / kf.n_splits  # 将每一折的预测结果加权平均得到最终的测试集预测结果

    return test

def get_test_data(dat):
    # 第一时刻特征
    first_feat = dat[0,:,:,:].reshape(70,161*161).transpose() # 将第一时刻的特征数据从(70, 161, 161)转换为(161*161, 70)

    # 第二时刻特征
    second_feat = dat[1,:,:,:].reshape(70,161*161).transpose() # 将第二时刻的特征数据从(70, 161, 161)转换为(161*161, 70)

    # 两个时刻差分特征
    diff_feat = (dat[1,:,:,:] - dat[0,:,:,:]).reshape(70,161*161).transpose() # 计算两个时刻特征之间的差分，并将结果从(70, 161, 161)转换为(161*161, 70)

    # 构建测试样本
    for i in range(20): # 20个时刻
        # 时间特征、经纬特征
        time_vals = np.array([i]*161*161).reshape(161*161,1) # 创建一个形状为(161*161, 1)的数组，每个元素都是i
        sub_vals = np.concatenate((time_vals, latlon_vals), axis=1) # 将时间特征和经纬度特征按列进行拼接，形状为(161*161, 3)

        # 添加历史特征，第一时刻特征、第二时刻特征、两个时刻差分特征
        sub_vals = np.concatenate((sub_vals,


)

TEXT ·AddUint64(SB),NOSPLIT,$0
	B ·addUint64(SB)

TEXT ·SwapInt64(SB),NOSPLIT,$0
	B ·swapUint64(SB)

TEXT ·SwapUint64(SB),NOSPLIT,$0
	B ·swapUint64(SB)

TEXT ·LoadInt32(SB),NOSPLIT,$0
	B ·LoadUint32(SB)

TEXT ·LoadUint32(SB),NOSPLIT,$0-8
	MOVW addr+0(FP), R1
load32loop:
	LDREX (R1), R2		// loads R2
	STREX R2, (R1), R0	// stores R2
	CMP $0, R0
	BNE load32loop
	MOVW R2, val+4(FP)
	RET

TEXT ·LoadInt64(SB),NOSPLIT,$0
	B ·loadUint64(SB)

TEXT ·LoadUint64(SB),NOSPLIT,$0
	B ·loadUint64(SB)

TEXT ·LoadUintptr(SB),NOSPLIT,$0
	B ·LoadUint32(SB)

TEXT ·LoadPointer(SB),NOSPLIT,$0
	B ·LoadUint32(SB)

TEXT ·StoreInt32(SB),NOSPLIT,$0
	B ·StoreUint32(SB)

TEXT ·StoreUint32(SB),NOSPLIT,$0-8
	MOVW addr+0(FP), R1
	MOVW val+4(FP), R2
storeloop:
	LDREX (R1), R4		// loads R4
	STREX R2, (R1), R0	// stores R2
	CMP $0, R0
	BNE storeloop
	RET

TEXT ·StoreInt64(SB),NOSPLIT,$0
	B ·storeUint64(SB)

TEXT ·StoreUint64(SB),NOSPLIT,$0
	B ·storeUint64(SB)

TEXT ·StoreUintptr(SB),NOSPLIT,$0
	B ·StoreUint32(SB)


mory,
    .endianness = DEVICE_LITTLE_ENDIAN,
    .valid = {
        .min_access_size = 4,
        .max_access_size = 4,
    },
};

static void xram_ctrl_realize(DeviceState *dev, Error **errp)
{
    SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
    XlnxXramCtrl *s = XLNX_XRAM_CTRL(dev);

    switch (s->cfg.size) {
    case 64 * KiB:
        s->cfg.encoded_size = 0;
        break;
    case 128 * KiB:
        s->cfg.encoded_size = 1;
        break;
    case 256 * KiB:
        s->cfg.encoded_size = 2;
        break;
    case 512 * KiB:
        s->cfg.encoded_size = 3;
        break;
    case 1 * MiB:
        s->cfg.encoded_size = 4;
        break;
    default:
        error_setg(errp, "Unsupported XRAM size %" PRId64, s->cfg.size);
        return;
    }

    memory_region_init_ram(&s->ram, OBJECT(s),
                           object_get_canonical_path_component(OBJECT(s)),
                           s->cfg.size, &error_fatal);
    sysbus_init_mmio(sbd, &s->ram);
}

static void xram_ctrl_init(Object *obj)
{
    XlnxXramCtrl *s = XLNX_XRAM_CTRL(obj);
    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);

    s->reg_array =
        register_init_block32(DEVICE(obj), xram_ctrl_regs_info,
                              ARRAY_SIZE(xram_ctrl_regs_info),
                              s->regs_info, s->regs,
                              &xram_ctrl_ops,
                              XLNX_XRAM_CTRL_ERR_DEBUG,
                              XRAM_CTRL_R_MAX * 4);
    sysbus_init_mmio(sbd, &s->reg_array->mem);
    sysbus_init_irq(sbd, &s->irq);
}

static void xram_ctrl_finalize(Object *obj)
{
    XlnxXramCtrl *s = XLNX_XRAM_CTRL(obj);
    register_finalize_block(s->reg_array);
}

static const VMStateDescription vmstate_xram_ctrl = {
    .name = TYPE_XLNX_XRAM_CTRL,
    .version_id = 1,
    .minimum_version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_UINT32_ARRAY(regs, XlnxXramCtrl, XRAM_CTRL_R_MAX),
        VMSTATE_END_OF_LIST(),
    }
};

static Property xram_ctrl_properties[] = {
    DEFINE_PROP_UINT64("size", XlnxXramCtrl, cfg.size, 1 * MiB),
    DEFINE_PROP_END_OF_LIST(),
};

static void xram_ctrl_class_init(ObjectClass *klass, void *data)
{
    ResettableClass *rc = RESETTABLE_CLASS(klass);
    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = xram_ctrl_realize;
    dc->vmsd = &vmstate_xram_ctrl;
    device_class_set_props(dc, xram_ctrl_properties);

    rc->phases.enter = xram_ctrl_reset_enter;
    rc->phases.hold = xram_ctrl_reset_hold;
}

static const TypeInfo xram_ctrl_info = {
    .name              = TYPE_XLNX_XRAM_CTRL,
    .parent            = TYPE_SYS_BUS_DEVICE,
    .instance_size     = sizeof(XlnxXramCtrl),
    .class_init        = xram_ctrl_class_init,
    .instance_init     = xram_ctrl_init,
    .instance_finalize = xram_ctrl_finalize,
};

static void xram_ctrl_register_types(void)
{
    type_register_static(&xram_ctrl_info);
}

type_init(xram_ctrl_register_types)


因素只有一个：用户体验。 这是一本来源于实战的书。 《华尔街日报》移动版和雅虎财经频道的用户体验设计师卢克·米勒用自己近10年的实战经验，从专业的视角用生动活泼的语言提炼了提升用户体验的5大黄金法则。从获得灵感到创设原型，本书对用户体验设计的各个阶段都有涉及，集案例分析、应用研究、个人经验于一身，为产品经理提供了各种实用的工具和实操的方法。 超预期用户体验5要素： 易学（Learnability）：第一次使用某个功能时，用户能否很容易完成基本任务？ 高效（Efficiency）：一旦用户学会了这个功能，他们能否很快完成任务？ 易记（Memorability）：若有一段时间不使用程序了，再重新使用时，用户能否很快恢复到原来的使用水平？ 纠错力（Errors）：使用某个功能时，用户会犯多少错误？他们能否快速地纠正错误？ 愉悦度（Satisfaction）：使用这个功能时，用户的愉快程度如何？

### 推荐序 怎样才算是好的用户体验

第一，用户体验的核心是用户需求。 c:400

### 序

大多数成功的公司都没有从改进供应链或终结复杂的交易形式做起，而是着手研究如何以超越客户预期的方式改进用户体验，这也正是用户体验设计的使命。 c:75

没经验找不到工作，没工作怎么能有经验 c:30

### 引言

用户体验的核心使命是让用户获得超预期的数字体验，用户不仅能通过这些体验增长才干，同时也会乐在其中。 c:162

用户体验开发工作是个集大成的工种，是前端编码技术和用户体验研究与设计技能二者的结合。 c:61

用户体验既是名词也是动词；它既是一个产品所具有的终极成果体验，又是创造这些体验的一套方法。这些方法包括用户研究技巧，如：如何进行用户访谈和调研？如何创设能代表用户的形象人物？如何对竞争产品优势进行分析？这些技巧还包括一套用于设计完美网址和应用程序导航路径（也称用户路径）的核心标准。 c:142

用户体验设计还是一种思维


:reverse}">

             {{friend.name}}
             {{friend.phone}}
             {{friend.age}}

     </file>
     <file name="script.js">
       angular.module('orderByExample', [])
         .controller('ExampleController', ['$scope', function($scope) {
           $scope.friends =
               [{name:'John', phone:'555-1212', age:10},
                {name:'Mary', phone:'555-9876', age:19},
                {name:'Mike', phone:'555-4321', age:21},
                {name:'Adam', phone:'555-5678', age:35},
                {name:'Julie', phone:'555-8765', age:29}];
           $scope.predicate = 'age';
           $scope.reverse = true;
           $scope.order = function(predicate) {
             $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
             $scope.predicate = predicate;
           };
         }]);
      </file>
     <file name="style.css">
       .sortorder:after {
         content: '\25b2';
       }
       .sortorder.reverse:after {
         content: '\25bc';
       }
     </file>
   </example>
 *
 * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
 * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
 * desired parameters.
 *
 * Example:
 *
 * @example
  <example module="orderByExample">
    <file name="index.html">

Sorting predicate = {{predicate}}; reverse = {{reverse}}

              <button ng-click="order('name')">Name</button>

              <button ng-click="order('phone')">Phone Number</button>

              <button ng-click="order('age')">Age</button>

          {{friend.name}}
          {{friend.phone}}
          {{friend.age}}

    </file>

    <file name="script.js">
      angular.module('orderByExample', [])
        .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
          var orderBy = $filter('orderBy');
          $scope.friends = [
            { name: 'John',    phone: '555-1212',    age: 10 },
            { name: 'Mary',    phone: '555-9876',    age: 19 },
            { name: 'Mike',    phone: '555-4321',    age: 21 },
            { name: 'Adam',    phone: '555-5678',    age: 35 },
            { name: 'Julie',   phone: '555-8765',    age: 29 }
          ];
          $scope.order = function(predicate) {
            $scope.predicate = predicate;
            $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
            $scope.friends = orderBy($scope.friends, predicate, $scope.reverse);
          };
          $scope.order('age', true);
        }]);
    </file>

    <file name="style.css">
       .sortorder:after {
         content: '\25b2';
       }


unlink(ABackupName);
        }
    }
    return 1;
fail:
    fclose(fp);
    unlink(AFileName);
    if (rename(ABackupName, AFileName) == -1) {
        View->MView->Win->Choice(GPC_ERROR, "Error", 1, "O&K", "Error renaming backup file to original!");
    } else {
        View->MView->Win->Choice(GPC_ERROR, "Error", 1, "O&K", "Error writing file, backup restored.");
    }
    return 0;
erroropen:
    View->MView->Win->Choice(GPC_ERROR, "Error", 1, "O&K", "Error writing %s (errno=%d).", AFileName, errno);
    return 0;
}
/* TcpSocket.cpp

   Copyright (C) 2014 - 2026 Marc Postema (mpostema09 -at- gmail.com)

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

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
   Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*/
#include <socket/TcpSocket.h>

#include <socket/SocketClient.h>
#include <Log.h>
#include <Utils.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/socket.h>
#include <arpa/inet.h>

// =============================================================================
//  -- Constructors and destructor ---------------------------------------------
// =============================================================================

TcpSocket::TcpSocket(int maxClients, const std::string &protocol) :
		_MAX_CLIENTS(maxClients),
		_MAX_POLL(maxClients + 1),
		_pfd(new pollfd[maxClients + 1]),
		_client(new SocketClient[maxClients]),
		_protocolString(protocol) {}

TcpSocket::~TcpSocket() {
	_server.closeFD();
	for (std::size_t j = 0; j < _MAX_CLIENTS; ++j) {
		_client[j].closeFD();
	}
	DELETE_ARRAY(_pfd);
	DELETE_ARRAY(_client);
}

// =============================================================================
//  -- Other member functions --------------------------------------------------
// =============================================================================

void TcpSocket::initialize(const std::string &ipAddr, int port, bool nonblock) {
	for (std::size_t i = 0; i < _MAX_CLIENTS; ++i) {
		_client[i].setProtocol(_protocolString);
	}
	if (initServerSocket(ipAddr, port, _MAX_CLIENTS, nonblock)) {
		_pfd[0].fd = _server.getFD();
		_pfd[0].events = POLLIN | POLLHUP | POLLRDNORM | POLLERR;
		_pfd[0].revents = 0;

		for (std::size_t i = 1; i < _MAX_POLL; ++i) {
			_pfd[i].fd = -1;
			_pfd[i].events = POLLIN | POLLHUP | POLLRDNORM | POLLERR;
			_pfd[i].revents = 0;
		}
	}
}

int TcpSocket::poll(int timeout) {
	if (::poll(_pfd, _MAX_POLL, timeout) > 0) {
		// Check who is sending data, so iterate over pfd


0 10000004 */  beq     $zero, $zero, .L808881A4
/* 00154 80888194 00001025 */  or      $v0, $zero, $zero          ## $v0 = 00000000
.L80888198:
/* 00158 80888198 1635FFD8 */  bne     $s1, $s5, .L808880FC
/* 0015C 8088819C 02201025 */  or      $v0, $s1, $zero            ## $v0 = 00000001
/* 00160 808881A0 24020001 */  addiu   $v0, $zero, 0x0001         ## $v0 = 00000001
.L808881A4:
/* 00164 808881A4 8FBF006C */  lw      $ra, 0x006C($sp)
/* 00168 808881A8 D7B40030 */  ldc1    $f20, 0x0030($sp)
/* 0016C 808881AC D7B60038 */  ldc1    $f22, 0x0038($sp)
/* 00170 808881B0 D7B80040 */  ldc1    $f24, 0x0040($sp)
/* 00174 808881B4 D7BA0048 */  ldc1    $f26, 0x0048($sp)
/* 00178 808881B8 8FB00054 */  lw      $s0, 0x0054($sp)
/* 0017C 808881BC 8FB10058 */  lw      $s1, 0x0058($sp)
/* 00180 808881C0 8FB2005C */  lw      $s2, 0x005C($sp)
/* 00184 808881C4 8FB30060 */  lw      $s3, 0x0060($sp)
/* 00188 808881C8 8FB40064 */  lw      $s4, 0x0064($sp)
/* 0018C 808881CC 8FB50068 */  lw      $s5, 0x0068($sp)
/* 00190 808881D0 03E00008 */  jr      $ra
/* 00194 808881D4 27BD0088 */  addiu   $sp, $sp, 0x0088           ## $sp = 00000000


   राघवस्य मनोह्लादमभिज्ञानमयाचिषम् ।। ५.५८.१०० ।।।।

###Slōka 101 / श्लोक १०१###

    अथ मामब्रवीत् सीता गृह्यतामयमुत्तमः ।
    मणिर्येन महाबाहू रामस्त्वां बहुमन्यते ।। ५.५८.१०१ ।।।।

###Slōka 102 / श्लोक १०२###

    इत्यक्त्वा तु वरारोहा मणिप्रवरमद्भुतम् ।
    प्रायच्छत् परमोद्विग्ना वाचा मां संदिदेश ह ।। ५.५८.१०२ ।।।।

###Slōka 103 / श्लोक १०३###

    ततस्तस्यै प्रणम्याहं राजपुत्र्यैः समाहितः ।
    प्रदक्षिणं परिक्राममिहाभ्युद्गतमानसः ।। ५.५८.१०३ ।।।।

###Slōka 104 / श्लोक १०४###

    उत्तरं पुनरेवेदं निश्चित्य मनसा तया ।
    हनुमन् मम वृत्तान्तं वक्तुमर्हसि राघवे ।। ५.५८.१०४ ।।।।

###Slōka 105 / श्लोक १०५###

    यथा श्रुत्वैव नचिरात्तावुभौ रामलक्ष्मणौ ।
    सुग्रीवसहितौ वीरावुपेयातां तथा कुरु ।। ५.५८.१०५ ।।।।

###Slōka 106 / श्लोक १०६###

    यद्यन्यथा भवेदेतद्द्वौ मासौ जीवितं मम ।
    न मां द्रक्ष्यति काकुत्स्थो म्रिये सा ऽहमनाथवत् ।। ५.५८.१०६ ।।।।

###Slōka 107 / श्लोक १०७###

    तच्छ्रुत्वा करुणं वाक्यं क्रोधो मामभ्यवर्तत ।
    उत्तरं च मया दृष्टं कार्यशे


bel input[type=checkbox][disabled] + .toggle:active:after {
  box-shadow: 0 1px 3px 1px rgba(0, 0, 0, 0.4), 0 0 0 15px rgba(0, 0, 0, 0.1);
}
.togglebutton label input[type=checkbox]:checked + .toggle:after {
  left: 15px;
}
.togglebutton label input[type=checkbox]:checked + .toggle {
  background-color: rgba(156, 39, 176, 0.7);
}
.togglebutton label input[type=checkbox]:checked + .toggle:after {
  border-color: #9c27b0;
}
.togglebutton label input[type=checkbox]:checked + .toggle:active:after {
  box-shadow: 0 1px 3px 1px rgba(0, 0, 0, 0.4), 0 0 0 15px rgba(156, 39, 176, 0.1);
}

.withripple {
  position: relative;
}

.ripple-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: inherit;
  pointer-events: none;
}
.disabled .ripple-container {
  display: none;
}

.ripple {
  position: absolute;
  width: 20px;
  height: 20px;
  margin-left: -10px;
  margin-top: -10px;
  border-radius: 100%;
  background-color: #000;
  background-color: rgba(0, 0, 0, 0.05);
  transform: scale(1);
  transform-origin: 50%;
  opacity: 0;
  pointer-events: none;
}

.ripple.ripple-on {
  transition: opacity 0.15s ease-in 0s, transform 0.5s cubic-bezier(0.4, 0, 0.2, 1) 0.1s;
  opacity: 0.1;
}

.ripple.ripple-out {
  transition: opacity 0.1s linear 0s !important;
  opacity: 0;
}

.section-dark .nav-pills > li > a, .section-image .nav-pills > li > a {
  color: #999999;
}
.section-dark .nav-pills > li > a:hover,
.section-dark .nav-pills > li > a:focus, .section-image .nav-pills > li > a:hover,
.section-image .nav-pills > li > a:focus {
  background-color: #EEEEEE;
}
.nav-pills > li > a {
  line-height: 24px;
  text-transform: uppercase;
  font-size: 12px;
  font-weight: 500;
  min-width: 100px;
  text-align: center;
  color: #555555;
  transition: all .3s;
}
.nav-pills > li > a:hover {
  background-color: rgba(200, 200, 200, 0.2);
}
.nav-pills > li i {
  display: block;
  font-size: 30px;
  padding: 15px 0;
}
.nav-pills > li.active > a, .nav-pills > li.active > a:focus, .nav-pills > li.active > a:hover {
  background-color: #9c27b0;
  color: #FFFFFF;
  box-shadow: 0 12px 20px -10px rgba(156, 39, 176, 0.28), 0 4px 20px 0px rgba(0, 0, 0, 0.12), 0 7px 8px -5px rgba(156, 39, 176, 0.2);
}
.nav-pills:not(.nav-pills-icons) > li > a {
  border-radius: 30px;
}
.nav-pills.nav-stacked > li + li {
  margin-top: 5px;
}
.nav-pills.nav-pills-info > li.active > a, .nav-pills.nav-pills-info > li.active > a:focus, .nav-pills.nav-pills-info > li.active >


fp = -uFogScale.s + uFogScale.t;							\n"
			"    else														\n"
			"      fp = aPosition.z/aPosition.w*uFogScale.s + uFogScale.t;	\n"
			"    fp = clamp(fp, 0.0, 1.0);									\n"
			"    if (uFogUsage == 1)										\n"
			"      vShadeColor.a = fp;										\n"
			"    else														\n"
			"      vShadeColor.rgb = vec3(fp);								\n"
			"  }															\n"
			"  vBaryCoords = vec4(aBaryCoords, 1.0 - aBaryCoords.x - aBaryCoords.y, 0.5); \n"
			"  vShadeColorNoperspective = vShadeColor;							\n"
			;
	}
};

class VertexShaderRect : public ShaderPart
{
public:
	VertexShaderRect(const opengl::GLInfo & _glinfo)
	{
		m_part =
			"IN highp vec4 aRectPosition;						\n"
			"IN highp vec2 aBaryCoords;							\n"
			"													\n"
			"OUT lowp vec4 vShadeColor;							\n"
			"OUT highp vec4 vBaryCoords; \n"
			;
		if (!_glinfo.isGLESX || _glinfo.noPerspective)
			m_part += "noperspective OUT lowp vec4 vShadeColorNoperspective;\n";
		else
			m_part += "OUT lowp vec4 vShadeColorNoperspective;				\n";
		m_part +=
			"uniform lowp vec4 uRectColor;						\n"
			"void main()										\n"
			"{													\n"
			"  gl_Position = aRectPosition;						\n"
			"  vShadeColor = uRectColor;						\n"
			"  vShadeColorNoperspective = uRectColor;			\n"
			"  vBaryCoords = vec4(aBaryCoords, vec2(1.0) - aBaryCoords);\n"
			;
	}
};

class VertexShaderEnd : public ShaderPart
{
public:
	VertexShaderEnd(const opengl::GLInfo & _glinfo)
	{
		if (!_glinfo.isGLESX) {
			m_part =
				"  gl_ClipDistance[0] = gl_Position.w - gl_Position.z;	\n"
				;
		} else if (config.generalEmulation.enableFragmentDepthWrite != 0 && _glinfo.noPerspective) {
			m_part =
				"  vZCoord = gl_Position.z / gl_Position.w;	\n"
				"  if (uClampMode > 0)	\n"
				"    gl_Position.z = 0.0;	\n"
				;
		} else if (config.generalEmulation.enableClipping != 0) {
			// Move the near plane towards the camera.
			// It helps to avoid issues with near-plane clipping in games, which do not use it.
			// Z must be scaled back in fragment shader.
			m_part = "  gl_Position.z /= 8.0;	\n";
		}
		m_part +=
			" gl_Position.xy += uVertexOffset * vec2(gl_Position.w);		\n"
			" gl_Position.xy -= vec2(0.5*screenSizeDims) * gl_Position.ww;	\n"
			" gl_Position.xy /= vec2(0.5*screenSizeDims);					\n"
			"} \n"
			;
	}
};

class FragmentShaderHeader : public ShaderPart
{
public:
	FragmentShaderHeader(const opengl::GLInfo & _glinfo)
	{
		if (_glinfo.isGLES2) {
			m_part = "#version 100 \n";
			if (config.generalEmulation.enableLOD) {
				m_part += "#extension GL_EXT_shader_texture_lod : enable \n";
				m_part += "#extension GL_OES_stand


.
 * @param paint_b Auxiliary paint channel B. See `paint_a`.
 * @param paint_c Auxiliary paint channel C. See `paint_a`.
 */
class SinaMapping(
    override var x: Any? = null,
    override var y: Any? = null,
    override var violinWidth: Any? = null,
    override var alpha: Any? = null,
    override var color: Any? = null,
    override var fill: Any? = null,
    override var shape: Any? = null,
    override var size: Any? = null,
    override var stroke: Any? = null,
    override var width: Any? = null,
    override var group: Any? = null,
    override var paint_a: Any? = null,
    override var paint_b: Any? = null,
    override var paint_c: Any? = null
) : SinaAesthetics, WithGroupOption, PaintAesthetics {
    override fun seal() = super<SinaAesthetics>.seal() +
            groupOption() +
            super<PaintAesthetics>.seal()
}/*
 * Copyright (c) 2021. JetBrains s.r.o.
 * Use of this source code is governed by the MIT license that can be found in the LICENSE file.
 */

package org.jetbrains.letsPlot.intern.layer.geom

import org.jetbrains.letsPlot.core.plot.base.Aes
import org.jetbrains.letsPlot.intern.Options
import org.jetbrains.letsPlot.intern.OptionsCapsule

/**
 * Aesthetic properties supported by [geomTextRepel()][org.jetbrains.letsPlot.geom.geomTextRepel].
 *
 * @property x X-axis value.
 * @property y Y-axis value.
 * @property label Text label to display.
 * @property alpha Transparency level of a layer. Understands numbers between 0 and 1.
 * @property color Color of the geometry.
 * @property size Font size.
 * @property family Font family.
 * @property fontface Font face.
 * @property hjust horizontal text alignment relative to the x-coordinate.
 * @property vjust vertical text alignment relative to the y-coordinate.
 * @property angle Text rotation angle in degrees.
 * @property lineheight Line height multiplier applied to the font size in the case of multi-line text.
 * @property shape Shape of the point.
 * @property pointSize A value representing the visual size of the point associated with the label.
 * @property pointStroke Width of the point border.
 * @property segmentColor Color of the line segment connecting the label to the point.
 * @property segmentSize Width of the line segment connecting the label to the point.
 * @property segmentAlpha Transparency level of the line segment. Understands numbers between 0 and 1.
 * @property linetype Type of the line.
 */
interface TextRepelAesthetics : OptionsCapsule {
    val x: Any?
    val y: Any?
    val label: Any?
    val alpha: Any?
    val color: Any?
    val size: Any?
    val family: Any?
    val fontface: Any?
    val hjust: Any?
    val vjust: Any?
    val angle: Any?
    val lineheight: Any?
    val shape: Any?
    val pointSize: Any?
    val pointStroke: Any?
    val segmentColor: Any?
    val segmentSize: Any?
    val segmentAlpha: Any?
    val linetype: Any?

    override fun seal() = Options.of(
        Aes.X.name to x,
        Aes.Y.name to y,
        Aes.LABEL.name to label,
        Aes.ALPHA.name to alpha,
        Aes.COLOR.name to color,
        Aes.SIZE.name to size,
        Aes.FAMILY.name to family,
        Aes.FONTFACE.name to fontface,
        Aes.HJUST.name to hjust,
        Aes.VJUST.name to vjus


    code: '{\na();\n}',
    output: '{\n\na();\n\n}',
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0
      }
    ])
  },
  {
    code: '{\r\na();\r\n}',
    output: '{\n\r\na();\r\n\n}',
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0
      }
    ])
  },
  {
    code: '{\na();}',
    output: '{\n\na();\n}',
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0
      }
    ])
  },
  {
    code: '{a();\n}',
    output: '{\na();\n\n}',
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0
      }
    ])
  },
  {
    code: '{a();\n}',
    output: '{\na();\n\n}',
    options: [{ blocks: 'always' }],
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0
      }
    ])
  },
  {
    code: 'switch (a) {\ncase 0: foo();\ncase 1: bar();\n}',
    output: 'switch (a) {\n\ncase 0: foo();\ncase 1: bar();\n\n}',
    options: ['always'],
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0,
        column: 11
      }
    ])
  },
  {
    code: 'switch (a) {\ncase 0: foo();\ncase 1: bar();\n}',
    output: 'switch (a) {\n\ncase 0: foo();\ncase 1: bar();\n\n}',
    options: [{ switches: 'always' }],
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0,
        column: 11
      }
    ])
  },
  {
    code: 'switch (a) {\n//comment\ncase 0: foo();//comment\n}',
    output: 'switch (a) {\n\n//comment\ncase 0: foo();//comment\n\n}',
    options: [{ switches: 'always' }],
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 1,
        column: 0
      }
    ])
  },
  {
    code: 'class A {\nconstructor(){}\n}',
    output: 'class A {\n\nconstructor(){}\n\n}',
    options: ['always'],
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0,
        column: 8
      }
    ])
  },
  {
    code: 'class A {\nconstructor(){}\n}',
    output: 'class A {\n\nconstructor(){}\n\n}',
    options: [{ classes: 'always' }],
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0,
        column: 8
      }
    ])
  },
  {
    code: '{a();}',
    output: '{\na();\n}',
    errors: expecting([
      {
        message: FAILURE_STRING.always,
        line: 0
      }
    ])
  },
  {
    code: '{\na()\n//comment\n\n}',
    output: '{\na()\n//comment\n}',
    options: ['never'],
    errors: expecting([
      {
        message: FAILURE_STRING.never,
        line: 2
      }
    ])
  },
  {
    code: '{\n\na();\n\n}',


ll;
  environments: ProjectEnvironment[];
  projectType: ProjectType;
}

export default class Project {
  public id: ProjectConstructorParams['id'];

  public name: ProjectConstructorParams['name'];

  public lastEnv: ProjectConstructorParams['lastEnv'];

  public environments: ProjectConstructorParams['environments'];

  public projectType: ProjectConstructorParams['projectType'];

  constructor(params: ProjectConstructorParams) {
    this.id = params.id;
    this.name = params.name;
    this.lastEnv = params.lastEnv;
    this.environments = params.environments;
    this.projectType = params.projectType;
  }
}
import Component, { tracked } from '@glimmer/component';

export default class StarRating extends Component {

  /*
  args: {
    todo: Todo;
    onEdit: (Todo, string) => void;
    onToggle: (Todo) => void;
    onDestroy: (Todo) => void;
  };
   */

  @tracked('args')
  get stars() {
    console.log(this.args.rating, this.args.maxRating);
    let rating = Math.round(this.args.rating);
    let fullStars = this.starRange(1, rating, 'full');
    let emptyStars = this.starRange(rating + 1, this.args.maxRating, 'empty');
    return fullStars.concat(emptyStars);
  };

  starRange: function(start, end, type) {
    let starsData = [];
    for (var i = start; i <= end; i++) {
      starsData.push({ rating: i, full: type === 'full' });
    }
    return starsData;
  };

  setRating(rating) {
    this.args.update(rating);
  };

};
import createGauge from './Gauges';
import { createElement } from '../utils/utils';

//elementID - element ID to append the tile to
function generateGoalTile(name: string, elementID:string, currentValue:number, minValue:number, maxValue:number, unit:string, isReversed:boolean){
        const goalTile = createElement('div', "goaltile");
        const header = createElement('span', "goalheader", name.toUpperCase());
        const gauge = createElement('div', "goalgauge");
        gauge.id = `${name}gauge`;

        goalTile.append(header, gauge);
        const parentElement = document.querySelector(`#${elementID}`);
        parentElement.appendChild(goalTile);

        //create the gauge
        createGauge(`${name}gauge`, currentValue, minValue, maxValue, isReversed);

        //adding an unit to the texts
        document.querySelectorAll(`#${elementID} .goalgauge > svg > text > tspan`).forEach(text =>{
                if(text.innerHTML) text.innerHTML += ` ${unit}`;
        })

        //replacing the value with percentage
        //percentage for calories
        let percentage = Math.floor((currentValue/maxValue)*100);

        //percentage for weight
        if (unit === "kg" && isReversed) percentage = Math.floor(((maxValue-currentValue)/(maxValue-minValue))*100);
        if (unit === "kg" && !isReversed) percentage = Math.floor(((currentValue-minValue)/(maxValue-minValue))*100);

        let currentGaugeValue = document.querySelector(`#${elementID} .goalgauge > svg > text:nth-child(5) > tspan`);

        if(currentGaugeValue){
                currentGaugeValue.innerHTML = `${percentage}%`;
        }
}

export default generateGoalTile;import { action, payload } from 'ts-action';

export interface IAddPostUsingUrlPayload {
  name: 'ADD_URL_POST';
  data: {
    url: string;
  };
}

export interface IPostNewPostPayload {


=' + object[key];
    }

    return results.slice(1);
}import {IFormula} from "../../_types/IFormula";
import {createCNFConverter} from "../utils/convertToCnf";
import {createFormula} from "../createFormula";
import {createSMTLIBFormulaCombiner} from "../utils/combineSMTLIBFormulas";
import {createFormatter} from "../utils/format";
import {OperatorParser} from "../parsing/OperatorParser";
import {createOperatorFactory} from "../createOperatorFactory";

/** A factory to create AND operators, with different precedences and sub-parsers */
export const AndFactory = createOperatorFactory(({precedence}) => {
    /**
     * Creates a new formula by getting the conjunction of the given formulas
     * @param formulas The formulas to be conjuncted
     * @returns The formula representing the conjunction of the given formulas
     */
    const operator = (...formulas: IFormula<boolean>[]) =>
        createFormula({
            data: {children: formulas},
            precedence,
            execute: context => formulas.every(formula => formula.execute(context)),
            toCNF: createCNFConverter(
                {
                    name: "And",
                    arity: 2,
                    truthTable: [
                        false, // false && false
                        false, // false && true
                        false, // true && false
                        true, // true && true
                    ],
                },
                formulas
            ),
            format: createFormatter({
                formulas,
                precedence,
                combine: (left, right) => `${left} && ${right}`,
            }),
            toSMTLIB2: createSMTLIBFormulaCombiner({
                combine: SMTformulas => ({formula: `(and ${SMTformulas.join(" ")})`}),
                formulas,
            }),
        });

    return {
        operator,
        associativity: "left",
        infixParser: OperatorParser("&&").map(() => operator),
    };
});
import { TelegramClient } from "telegram";
import { NewMessage, NewMessageEvent } from "telegram/events";
// import * as appConfig from "../providers/app-config";
import * as moduleConfig from "../providers/module-config";
import modules from "../modules";
import Client from "./Client";
import IonHandler from "./IonHandler";

const defaultPrefixes = ["."];

const escapeForRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

export interface ModuleMeta {
  slug: string; // may be used for identification of that module
  name: string;
  description: string;
}

export interface Module {
  handlers: IonHandler | IonHandler[];
  meta: ModuleMeta;
  config?: object;
}

export interface LoadedModule {
  meta: ModuleMeta;
  config: object;
}

export default class extends Client {
  private prefixes: string[] = defaultPrefixes; //todo: load from database
  public loadedModules: LoadedModule[] = [];

  constructor() {
    super();
  }

  match(event: NewMessageEvent, commands: string | string[]): boolean {
    const message = event.message.message;

    if (!message) {
      return false;
    }

    commands = Array.isArray(commands) ? commands : [commands];

    for (let k in this.prefixes) {
      const prefix = this.prefixes[k];

      if (message.startsWith(prefix)) {
        for (let k in commands) {
          const command = commands[k];
          const withoutPrefix = message.slice(1, message.length);

          if (withoutPrefix.match(new RegExp(`^(?:${command})(?:\\s|$)`))) {
            return true;
          }
        }
      }
    }

    return false;
  }

  loadModules() {
    /**
     * Loads Each Module by mapp


t
			-- - max_width  maximal width of floating window
			-- - max_height maximal height of floating window
			-- - pad_left   number of columns to pad contents at left
			-- - pad_right  number of columns to pad contents at right
			-- - pad_top    number of lines to pad contents at top
			-- - pad_bottom number of lines to pad contents at bottom
			-- - offset_x   x-axis offset of the floating window
			-- - offset_y   y-axis offset of the floating window
			-- - anchor     Corner of float to place at the cursor (NW, NE, SW, SE)
		},
		status_text = {
			enabled = true,
			-- Text to provide when code actions are available
			text = '💡',
			-- Text to provide when no actions are available
			text_unavailable = '',
		},
	})
end


_progressStartDrag = false;
            _progressDragNewValue = -1.0f;
        }
    }

    private void SetLibraryBtnIsLiked(bool isLiked)
    {
        _currentItemIsInLibrary = isLiked;


cal palette of length n, choosing the best palette based on n."""
    palettes = get_categorical_palettes()
    if n <= len(palettes["vega_10_scanpy"]):
        base = palettes["vega_10_scanpy"]
    elif n <= len(palettes["vega_20_scanpy"]):
        base = palettes["vega_20_scanpy"]
    elif n <= len(palettes["zeileis_28"]):
        base = palettes["zeileis_28"]
    else:
        base = palettes["godsnot_102"]
    if n <= len(base):
        return base[:n]
    # If n > base, repeat and cycle through palettes
    return list(itertools.islice(itertools.cycle(base), n))


sys.pickBool(tbl.onGhosts, false)

   self._tmEvalMom = 0.0
end

function Ionization:ionizationTemp(elcVtSq, vtSqIz)
   local tmEvalMomStart = Time.clock()
   local grid           = self._onGrid

   local confIndexer = elcVtSq:genIndexer()
   local elcVtSqItr  = elcVtSq:get(1)
   local vtSqIzItr   = vtSqIz:get(1)

   local confRange = elcVtSq:localRange()
   if self.onGhosts then confRange = elcVtSq:localExtRange() end

   -- Configuration space loop
   for cIdx in confRange:rowMajorIter() do
      grid:setIndex(cIdx)

      elcVtSq:fill(confIndexer(cIdx), elcVtSqItr)
      vtSqIz:fill(confIndexer(cIdx), vtSqIzItr)

      self._IonizationTempCalc(self._elemCharge, self._elcMass, elcVtSqItr:data(), self._E, vtSqIzItr:data())

   end
   self._tmEvalMom = self._tmEvalMom + Time.clock() - tmEvalMomStart
end

function Ionization:reactRateCoef(neutM0, neutVtSq, elcVtSq, coefIz) --, cflRateByCell)
   local tmEvalMomStart = Time.clock()
   local grid = self._onGrid
   local vDim = self._pDim - self._cDim

   local confIndexer = elcVtSq:genIndexer()
   local neutM0Itr   = neutM0:get(1)
   local neutVtSqItr = neutVtSq:get(1)
   local elcVtSqItr  = elcVtSq:get(1)
   local coefIzItr   = coefIz:get(1)

   local confRange = elcVtSq:localRange()
   if self.onGhosts then confRange = elcVtSq:localExtRange() end

   -- Get the interface for setting global CFL frequencies
   local cflRateByCell     = self._cflRateByCell
   local cflRateByCellIdxr = cflRateByCell:genIndexer()
   local cflRateByCellPtr  = cflRateByCell:get(1)
   local cflRange = cflRateByCell:localRange()
   local velRange = cflRange:selectLast(vDim)

   local cflRate
   -- Configuration space loop
   for cIdx in confRange:rowMajorIter() do
      grid:setIndex(cIdx)

      neutM0:fill(confIndexer(cIdx), neutM0Itr)
      neutVtSq:fill(confIndexer(cIdx), neutVtSqItr)
      elcVtSq:fill(confIndexer(cIdx), elcVtSqItr)
      coefIz:fill(confIndexer(cIdx), coefIzItr)

      cflRate = self._VoronovReactRateCalc(self._elemCharge, self._elcMass, neutM0Itr:data(), neutVtSqItr:data(), elcVtSqItr:data(), self._E, self._A, self._K, self._P, self._X, coefIzItr:data())
      for vIdx in velRange:rowMajorIter() do
      	 -- Construct the phase space index ot of the configuration
      	 -- space and velocity space indices
         cIdx:copyInto(self.idxP)
         for d = 1, vDim do self.idxP[self._cDim+d] = vIdx[d] end
      	 cflRateByCell:fill(cflRateByCellIdxr(self.idxP), cflRateByCellPtr)
      	 cflRateByCellPtr:data()[0] = cflRateByCellPtr:data()[0] + cflRate
      end

   end
   self._tmEvalMom = self._tmEvalMom + Time.clock() - tmEvalMomStart
end

----------------------------------------------------------------------
-- Updater Advance ---------------------------------------------------
function Ionization:_advance(tCurr, inFld, outFld)

   if not self._reactRate then
      local elcVtSq = inFld[1]
      local vtSqIz  = outF


testCase{repeat, "", ""},

		testCase{New("a", "11", "a", "22"), "brad", "br11d"},
	)

	// The remaining test cases have variable length old strings.

	testCases = append(testCases,
		testCase{htmlUnescaper, "&amp;", "&"},
		testCase{htmlUnescaper, "HTML's neat", "HTML's neat"},
		testCase{htmlUnescaper, "", ""},

		testCase{New("a", "1", "a", "2", "xxx", "xxx"), "brad", "br1d"},

		testCase{New("a", "1", "aa", "2", "aaa", "3"), "aaaa", "1111"},

		testCase{New("aaa", "3", "aa", "2", "a", "1"), "aaaa", "31"},
	)

	// gen1 has multiple old strings of variable length. There is no
	// overall non-empty common prefix, but some pairwise common prefixes.
	gen1 := New(
		"aaa", "3[aaa]",
		"aa", "2[aa]",
		"a", "1[a]",
		"i", "i",
		"longerst", "most long",
		"longer", "medium",
		"long", "short",
		"xx", "xx",
		"x", "X",
		"X", "Y",
		"Y", "Z",
	)
	testCases = append(testCases,
		testCase{gen1, "fooaaabar", "foo3[aaa]b1[a]r"},
		testCase{gen1, "long, longerst, longer", "short, most long, medium"},
		testCase{gen1, "xxxxx", "xxxxX"},
		testCase{gen1, "XiX", "YiY"},
		testCase{gen1, "", ""},
	)

	// gen2 has multiple old strings with no pairwise common prefix.
	gen2 := New(
		"roses", "red",
		"violets", "blue",
		"sugar", "sweet",
	)
	testCases = append(testCases,
		testCase{gen2, "roses are red, violets are blue...", "red are red, blue are blue..."},
		testCase{gen2, "", ""},
	)

	// gen3 has multiple old strings with an overall common prefix.
	gen3 := New(
		"abracadabra", "poof",
		"abracadabrakazam", "splat",
		"abraham", "lincoln",
		"abrasion", "scrape",
		"abraham", "isaac",
	)
	testCases = append(testCases,
		testCase{gen3, "abracadabrakazam abraham", "poofkazam lincoln"},
		testCase{gen3, "abrasion abracad", "scrape abracad"},
		testCase{gen3, "abba abram abrasive", "abba abram abrasive"},
		testCase{gen3, "", ""},
	)

	// foo{1,2,3,4} have multiple old strings with an overall common prefix
	// and 1- or 2- byte extensions from the common prefix.
	foo1 := New(
		"foo1", "A",
		"foo2", "B",
		"foo3", "C",
	)
	foo2 := New(
		"foo1", "A",
		"foo2", "B",
		"foo31", "C",
		"foo32", "D",
	)
	foo3 := New(
		"foo11", "A",
		"foo12", "B",
		"foo31", "C",
		"foo32", "D",
	)
	foo4 := New(
		"foo12", "B",
		"foo32", "D",
	)
	testCases = append(testCases,
		testCase{foo1, "fofoofoo12foo32oo", "fofooA2C2oo"},
		testCase{foo1, "", ""},

		testCase{foo2, "fofoofoo12foo32oo", "fofooA2


WN"
      NOT_LEAKING -> "NO ($leakingStatusReason)"
      LEAKING -> "YES ($leakingStatusReason)"
    }

    var result = ""
    result += "$firstLinePrefix$className $typeName"
    if (showLeakingStatus) {
      result += "\n${additionalLinesPrefix}Leaking: $leakStatus"
    }

    if (retainedHeapByteSize != null) {
      val humanReadableRetainedHeapSize =
        humanReadableByteCount(retainedHeapByteSize.toLong())
      result += "\n${additionalLinesPrefix}Retaining $humanReadableRetainedHeapSize in $retainedObjectCount objects"
    }
    for (label in labels) {
      result += "\n${additionalLinesPrefix}$label"
    }
    return result
  }

  enum class ObjectType {
    CLASS,
    ARRAY,
    INSTANCE
  }

  enum class LeakingStatus {
    /** The object was needed and therefore expected to be reachable. */
    NOT_LEAKING,

    /** The object was no longer needed and therefore expected to be unreachable. */
    LEAKING,

    /** No decision can be made about the provided object. */
    UNKNOWN;
  }

  companion object {
    private const val serialVersionUID = -3616216391305196341L

    // https://stackoverflow.com/a/3758880
    private fun humanReadableByteCount(bytes: Long): String {
      val unit = 1000
      if (bytes < unit) return "$bytes B"
      val exp = (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt()
      val pre = "kMGTPE"[exp - 1]
      return String.format("%.1f %sB", bytes / unit.toDouble().pow(exp.toDouble()), pre)
    }
  }
}package shark

import shark.ReferencePattern.Companion.instanceField

sealed interface HeapTraversalInput {
  val traversalCount: Int

  /**
   * How many times a scenario that might cause heap growth is repeated in between each
   * dump and traversal. This leads the traversal algorithm to only look at objects that are
   * growing at least [scenarioLoopsPerGraph] times since the previous traversal.
   */
  val scenarioLoopsPerGraph: Int
}

class InitialState(
  override val scenarioLoopsPerGraph: Int = DEFAULT_SCENARIO_LOOPS_PER_GRAPH,
) : HeapTraversalInput {
  override val traversalCount = 0

  init {
    check(scenarioLoopsPerGraph >= 1) {
      "There should be at least 1 scenario loop per heap dump"
    }
  }

  companion object {
    const val DEFAULT_SCENARIO_LOOPS_PER_GRAPH = 1
  }
}

sealed interface HeapTraversalOutput : HeapTraversalInput {
  /**
   * A representation of the heap as a tree of shortest path from roots to each
   * object in the heap, where:
   * - object identity is lost
   * - objects are grouped by identical path into a single node
   * - Path element names are determined using the node & edge name to reach them (e.g. class name
   * + field name) as well as the class name of the reached object.
   */
  val shortestPathTree: ShortestPathObjectNode

  companion object {

    /**
     * When running a heap growth analysis in the same process as where the scenario runs,
     * we should ignore the part of the graph used to keep track of the tree in the previous
     * iteration of the scenario.
     */
    val ignoredReferences: List<IgnoredReferenceMatcher>
      get() {
        val shortestPathNodeClass = ShortestPathObjectNode::class.java
        return shortestPathNodeClass.declaredFields.map { classField ->
          instanceField(
            className = shortestPathNodeClass.name,
            fieldName = classField.name
          ).ignored()
        }
      }
  }
}

class FirstHeapTraversal constructor(
  override val shortestPathTree: ShortestPathObjectNode,
  previousTraversal: InitialState
) : HeapTraversalOutput {
  override val traversal


",
  [23188] = "Unk Item #151 - Quest",
  [23189] = "Unk Item #152 - Quest",
  [23190] = "Unk Item #153 - Quest",
  [23191] = "水晶控制寶珠",
  [23192] = "血色十字軍外袍",
  [23193] = "Skeletal Steed Reins",
  [23194] = "次級黎明印記",
  [23195] = "黎明印記",
  [23196] = "高級黎明印記",
  [23197] = "月光塑像",
  [23198] = "蠻橫塑像",
  [23199] = "風暴圖騰",
  [23202] = "Unk Item #154 - Armor - Librams - Relic (Increased Flash of Light Healing)",
  [23204] = "Unk Item #155 - Armor - Librams - Relic (Increased Flash of Light Healing)",
  [23205] = "地獄火骨葉",
  [23206] = "勇士印記",
  [23207] = "勇士印記",
  [23208] = "Unk Item #156 - Armor - Miscellaneous - Trinket (Champion of the Dawn)",
  [23209] = "Unk Item #157 - Consumable",
  [23210] = "Unk Item #158 - Consumable",
  [23212] = "Scrapper\'s Vest",
  [23213] = "Scrapper\'s Pants",
  [23214] = "鼓起的地獄野豬屍體",
  [23215] = "史馬克的材料包",
  [23216] = "Pulsating Voidwalker Essence",
  [23217] = "劫毀者蛋",
  [23218] = "濃縮的虛無行者精華",
  [23219] = "啟發者束腰",
  [23222] = "Clefthoof Hide",
  [23223] = "Clefthoof Bones",
  [23224] = "Summer Gift Package",
  [23225] = "Monster - Sword, 1H Blood Elf A02 Red",
  [23226] = "食屍鬼皮外套",
  [23227] = "iCoke Gift Box Voucher",
  [23228] = "老白樹墜飾",
  [23229] = "Sword of Sockety Goodness",
  [23230] = "Dagger of Sockety Goodness",
  [23231] = "Clefthoof Sinew",
  [23232] = "Huge Sword of Sockety Goodness",
  [23233] = "Red Bryanite of Strength stuff",
  [23234] = "Blue Bryanite of Agility",
  [23235] = "Yellow Bryanite


oku Tachi (Arrange Mode version 1.51, hack by Trap15)\0", NULL, "hack / Trap15", "PolyGameMaster based",
	L"Ketsui Kizuna Jigoku Tachi\0\u30B1\u30C4\u30A4~\u7D46\u5730\u7344\u305F\u3061 (Arrange Mode version 1.51, hack by Trap15)\0", NULL, NULL, NULL,
	BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL | BDF_HACK, 4, HARDWARE_IGS_PGM | HARDWARE_IGS_JAMMAPCB/* | HARDWARE_IGS_USE_ARM_CPU*/, GBF_VERSHOOT, 0,
	NULL, ketarr151RomInfo, ketarr151RomName, NULL, NULL, pgmInputInfo, jammaDIPInfo,
	ketsuiInit, pgmExit, pgmFrame, pgmDraw, pgmScan, &nPgmPalRecalc, 0x900,
	224, 448, 3, 4
};

// Ketsui Kizuna Jigoku Tachi (MR. Stoic version 1.5, hack by Trap15)

static struct BurnRomInfo ketarrs15RomDesc[] = {
	{ "ketarrs15_v100.u38",		0x200000, 0xa95e71e0, 1 | BRF_PRG | BRF_ESS },	//  0 68K Code

	{ "t04701w064.u19", 		0x800000, 0x2665b041, 2 | BRF_GRA },			//  1 Tile data

	{ "a04701w064.u7", 			0x800000, 0x5ef1b94b, 3 | BRF_GRA },			//  2 Sprite Color Data
	{ "a04702w064.u8", 			0x800000, 0x26d6da7f, 3 | BRF_GRA },			//  3

	{ "b04701w064.u1",			0x800000, 0x1bec008d, 4 | BRF_GRA },			//  4 Sprite Masks & Color Indexes

	{ "m04701b032.u17",			0x400000, 0xb46e22d1, 5 | BRF_SND },			//  5 Samples

	{ "ket_igs027a.bin",		0x004000, 0x00000000, 7 | BRF_PRG | BRF_ESS | BRF_NODUMP },	//  6 Internal ARM7 Rom

	{ "ket_defaults.nv",		0x020000, 0x3ca892d8, 0 | BRF_OPT },			//  7 NV RAM
};

STDROMPICKEXT(ketarrs15, ketarrs15, ketsuiBios) // custom bios
STD_ROM_FN(ketarrs15)

struct BurnDriver BurnDrvketarrs15 = {
	"ketarrs15", "ket", NULL, NULL, "2012",
	"Ketsui Kizuna Jigoku Tachi (MR. Stoic version 1.5, hack by Trap15)\0", NULL, "hack / Trap15", "PolyGameMaster based",
	L"Ketsui Kizuna Jigoku Tachi\0\u30B1\u30C4\u30A4~\u7D46\u5730\u7344\u305F\u3061 (MR. Stoic version 1.5, hack by Trap15)\0", NULL, NULL, NULL,
	BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL | BDF_HACK, 4, HARDWARE_IGS_PGM | HARDWARE_IGS_JAMMAPCB/* | HARDWARE_IGS_USE_ARM_CPU*/, GBF_VERSHOOT, 0,
	NULL, ketarrs15RomInfo, ketarrs15RomName, NULL, NULL, pgmInputInfo, jammaDIPIn


*****************************************************************

/**
 * Parses the given string to a number. Uses the default locale for thousands and decimal separators.
 * - Returns null, if invalid characters are found.
 * - Also returns null, for negative values
 */
fun CharSequence.toNumber(): Number? {
    if (this.isBlank())
        return null
    // allow 0-9 , . whitespace
    if (!this.matches("[0-9,.\\s]+".toRegex()))
        return null
    return NumberFormat.getNumberInstance().parse(
        toString()
            .replace("\\s+".toRegex(), "")
    )
}
package de.salomax.currencies.model.provider

import android.content.Context
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.github.kittinunf.fuel.core.awaitResult
import com.github.kittinunf.result.Result
import de.salomax.currencies.R
import de.salomax.currencies.model.ApiProvider
import de.salomax.currencies.model.Currency
import de.salomax.currencies.model.ExchangeRates
import de.salomax.currencies.model.Timeline
import de.salomax.currencies.model.adapter.NorgesBankRatesXmlParser
import de.salomax.currencies.model.adapter.NorgesBankTimelineXmlParser
import java.io.InputStream
import java.time.LocalDate
import java.time.format.DateTimeFormatter

class NorgesBank: ApiProvider.Api() {

    override val name = "Norges Bank"

    override fun descriptionShort(context: Context) =
        context.getText(R.string.api_norgesBank_descriptionShort)

    override fun getDescriptionLong(context: Context) =
        context.getText(R.string.api_norgesBank_descriptionFull)

    override fun descriptionUpdateInterval(context: Context) =
        context.getText(R.string.api_norgesBank_descriptionUpdateInterval)

    override fun descriptionHint(context: Context) =
        context.getText(R.string.api_norgesBank_hint)

    override val baseUrl = "https://data.norges-bank.no/api"

    override suspend fun getRates(context: Context?, date: LocalDate?): Result<ExchangeRates, FuelError> {
        // As this API doesn't return results for non-work days, get the last seven days.
        // The latest available values will be used.
        val formattedDateStart = date?.minusDays(7)?.format(DateTimeFormatter.ISO_LOCAL_DATE)
        val formattedDateEnd = date?.format(DateTimeFormatter.ISO_LOCAL_DATE)
        val dateString =
            // latest
            if (date == null) "?lastNObservations=1"
            // historical
            else "?StartPeriod=$formattedDateStart&EndPeriod=$formattedDateEnd"

        return Fuel.get(
            baseUrl +
                    "/data" +
                    "/EXR" +
                    "/B..NOK.SP" +
                    dateString +
                    "&format=sdmx-compact-2.1"
        ).awaitResult(
            object : ResponseDeserializable<ExchangeRates> {
                override fun deserialize(inputStream: InputStream): ExchangeRates {
                    return NorgesBankRatesXmlParser().parse(inputStream, date ?: LocalDate.now())
                }
            }
        )
    }

    override suspend fun getTimeline(
        context: Context?,
        base: Currency,
        symbol: Currency,
        startDate: LocalDate,
        endDate: LocalDate
    ): Result<Timeline, FuelError> {
        val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        // can't search for FOK - have to use DKK instead
        val parameterBase = if (base == Currency.FOK) "DKK" else base.iso4217Alpha()
        val parameterSymbol = if (symbol == Currency.FOK) "DKK" else symbol.iso4217Alpha()

        // if we request NOK


od|N|From Clerk Daltry.|
T The Rotting Orchard|QID|26689|M|75.33,48.01|Z|1431;Duskwood|N|To Calor.|
A Vile and Tainted|QID|26690|PRE|26689|M|75.33,48.01|Z|1431;Duskwood|N|From Calor.|
T Classy Glass|QID|26685|M|79.53,47.41|Z|1431;Duskwood|N|To Viktori Prism'Antras.|
T Ogre Thieves|QID|26680|M|87.43,35.21|Z|1431;Duskwood|N|To Abercrombie at Beggar's Haunt.|
A Ghoulish Effigy|QID|26677|PRE|26680|M|87.43,35.21|Z|1431;Duskwood|N|From Abercrombie.|
C Ghoulish Effigy|QID|26677|M|76.83,33.72|Z|1431;Duskwood|L|884 7|ITEM|884|N|Fetid Corpses at Manor Mistmantle.|
T Ghoulish Effigy|QID|26677|M|87.43,35.21|Z|1431;Duskwood|N|To Abercrombie.|
A Note to the Mayor|QID|26681|PRE|26677|M|87.43,35.21|Z|1431;Duskwood|N|From Abercrombie.|
T Note to the Mayor|QID|26681|M|71.93,46.44|Z|1431;Duskwood|N|To Lord Ello Ebonlocke.|
A The Embalmer's Revenge|QID|26727|PRE|26681|M|71.93,46.44|Z|1431;Duskwood|N|From Lord Ello Ebonlocke.|
C The Embalmer's Revenge|QID|26727|M|73.84,46.62|Z|1431;Duskwood|N|Kill Stitches, he spawns in the middle of town.\n[color=FF0000]NOTE: [/color]If you die, come back quickly as you can still finish him.|
T The Embalmer's Revenge|QID|26727|M|71.93,46.44|Z|1431;Duskwood|N|To Lord Ello Ebonlocke.|
C The Jitters-Bugs|QID|26721|M|73.63,79.19|Z|1431;Duskwood|L|60207 8|ITEM|60207|N|Black Widows.|S|
C Vile and Tainted|QID|26690|M|73.63,79.19|Z|1431;Duskwood|N|Kill Nightbane Vile Fangs and Tainted Ones.\n[color=FF0000]NOTE: [/color]As long as they are fighting each other, you don't exist.|S|
C Roland's Doom|QID|26670|M|73.63,79.19|Z|1431;Duskwood|L|938|N|Head to the back of the cave and pick up the Muddy Journal Page.|
C Vile and Tainted|QID|26690|M|72.76,73.26|Z|1431;Duskwood|N|Finish killing Worgen.\n[color=FF0000]NOTE: [/color]If they are fighting each other, you must land the killing blow to get credit for the kill.|US|
T Vile and Tainted|QID|26690|M|75.33,48.01|Z|1431;Duskwood|N|To Calor.|
A Worgen in the Woods|QID|26691|PRE|26690|M|75.33,48.01|Z|1431;Duskwood|N|From Calor.|
T Worgen in the Woods|QID|26691|M|75.35,48.93|Z|1431;Duskwood|N|To Jonathan Carevin.|
T Roland's Doom|QID|26670|M|72.45,46.91|Z|1431;Duskwood|N|


 GetLastError() as u32 }))?;

        let graphic_offsets = graphic_offsets::load_graphic_offsets().map_err(ObsError::LoadGraphicOffsets)?;
        unsafe { (**hook_info).graphics_offsets = graphic_offsets };
        unsafe { (**hook_info).capture_overlay = self.config.capture_overlays };
        unsafe { (**hook_info).force_shmem = false };
        unsafe { (**hook_info).unused_use_scale = false };

        log::info!("Hook info: {:?}", unsafe { &**hook_info });

        Ok(())
    }

    fn init_events(&mut self) -> Result<(), ObsError> {
        macro_rules! open_event {
            ($var_name:tt, $event_name:expr) => {
                // if self.context.$var_name.is_none() {
                if let Some(event) = Event::open(format!("{}{}", $event_name, self.context.pid)) {
                    self.context.$var_name = Some(event)
                } else {
                    log::warn!("Couldn't find {:?} ({:?}).", $event_name, unsafe {
                        GetLastError()
                    });
                    return Err(ObsError::CreateEvent);
                }
                // }
            };
        }

        open_event!(hook_restart, EVENT_CAPTURE_RESTART);
        open_event!(hook_stop, EVENT_CAPTURE_STOP);
        open_event!(hook_init, EVENT_HOOK_INIT);
        open_event!(hook_ready, EVENT_HOOK_READY);
        open_event!(hook_exit, EVENT_HOOK_EXIT);

        Ok(())
    }

    /// Tries to launch the capture.
    pub fn try_launch(&mut self) -> Result<(), ObsError> {
        let hwnd = utils::process::get_hwnd(&*self.config.window_name).ok_or(ObsError::ProcessNotFound)?;
        let (pid, thread_id) = utils::process::get_window_thread_pid(hwnd).ok_or(ObsError::ProcessNotFound)?;

        log::info!(
            "Found the process. pid = {}, thread id = {}, hwnd = {}",
            pid,
            thread_id,
            hwnd
        );

        self.context.hwnd = hwnd;
        self.context.pid = pid;
        self.context.thread_id = thread_id;

        self.init_keepalive()?;
        self.init_pipe()?;

        if !self.attempt_existing_hook() {
            log::info!(
                "Trying to inject the graphics hook into the thread {}.",
                self.context.thread_id
            );
            inject_helper::inject_graphics_hook(self.context.thread_id, true).map_err(ObsError::Inject)?;
        }

        self.init_hook_info()?;
        self.init_events()?;

        // Create and signal the hook init event
        //
        let event = Event::open(format!("{}{}", EVENT_HOOK_INIT, self.context.pid)).ok_or(ObsError::CreateEvent)?;
        if event.signal().is_none() {
            log::warn!("Failed to signal the hook init event");
        };

        // Extract the handle
        //
        let hook_info = FileMapping::<HookInfo>::open(format!("{}{}", SHMEM_HOOK_INFO, self.context.pid))
            .ok_or_else(|| ObsError::CreateFileMapping(unsafe { GetLastError() as u32 }))?;

        let texture_data = FileMapping::<SharedTextureData>::open(format!(
            "{}_{}_{}",
            SHMEM_TEXTURE,
            unsafe { (**hook_info).window },
            unsafe { (**hook_info).map_id }
        ))
        .ok_or_else(|| ObsError::CreateFileMapping(unsafe { GetLastError() as u32 }))?;

        let texture_handle = unsafe { (**texture_data).tex_handle };
        self.context.texture_handle = texture_handle;

        // Initialize the d3d11 variables
        //

        let (device, device_context) = d3d11::create_


import streamlit as st
import requests

# Set Streamlit app configuration
st.set_page_config(page_title="Clarity Coach Chat", layout="centered")

# API endpoint for backend chat processing
API_URL = "http://localhost:8000"

# Reset the session if page refreshed or reloaded
if "reset_done" not in st.session_state:
    requests.post(f"{API_URL}/reset")
    st.session_state["reset_done"] = True

# Custom CSS for improved styling
st.markdown("""

""", unsafe_allow_html=True)

# Initialize session state and add starter assistant message
if "messages" not in st.session_state:
    st.session_state["messages"] = [
        {"role": "assistant", "content": "👋 Hello! What brings you here today?"}
    ]

# Title
st.title("🧠 AI Feature Clarity Coach")
st.caption("Guiding you step-by-step to build something amazing.")

# Render past messages in chat history
for msg in st.session_state["messages"]:
    role_class = "user-message" if msg["role"] == "user" else "assistant-message"
    st.markdown(f'
{msg["content"]}
', unsafe_allow_html=True)

# Chat input field
user_input = st.chat_input("What's on your mind?")

# Handle new user input
if user_input:
    # Append user's message
    st.session_state["messages"].append({"role": "user", "content": user_input})
    st.markdown(f'
{user_input}
', unsafe_allow_html=True)

    # Show thinking animation
    thinking_placeholder = st.empty()
    thinking_placeholder.markdown("💭 Thinking...")

    # Send input to FastAPI backend and get assistant response
    try:
        response = requests.post(f"{API_URL}/chat", params={"user_input": user_input})
        response.raise_for_status()
        data = response.json()
        bot_msg = data["response"]

        # Append assistant's response to session
        st.session_state["messages"].append({"role": "assistant", "content": bot_msg})
        thinking_placeholder.empty()
        st.markdown(f'
{bot_msg}
', unsafe_allow_html=True)
    except Exception as e:
        thinking_placeholder.empty()
        st.error(f"Failed to get response: {e}")

# Reset the entire coaching session
if st.button("🔄 Reset Conversation"):
    try:
        requests.post(f"{API_URL}/reset")
        st.session_state["messages"] = [{"role": "assistant", "content": "👋 Hello! What brings you here today?"}]
        st.session_state["current_phase"] = "core_problem"
        st.success("Conversation reset.")
        st.rerun()
    except Exception as e:
        st.error(f"Failed to reset conversation: {e}")


evice object fail, error: %v, condition [%#v], rid: %s", err, objectCond,
			rid)
		return nil, nil, defErr.Error(common.CCErrObjectSelectInstFailed)
	}

	if 0 == len(objResult.Info) {
		return nil, nil, nil
	}

	objIDs := make([]string, 0)
	objIDMapobjName := map[string]objShowField{}
	for _, obj := range objResult.Info {
		objIDs = append(objIDs, obj.ObjectID)
		objIDMapobjName[obj.ObjectID] = objShowField{obj.ObjectName}
	}

	return objIDs, objIDMapobjName, nil
}

// getDeviceIDsAndShowFields TODO
// get device ID list and get field to show by map (device_id --> bk_device_name, ...)
// add obj show field into device show fields
func (lgc *Logics) getDeviceIDsAndShowFields(
	pHeader http.Header, deviceCond map[string]interface{}, objIDMapShowFields map[string]objShowField) ([]uint64,
	map[uint64]deviceShowField, error) {

	rid := util.ExtractRequestIDFromContext(lgc.ctx)
	defErr := lgc.Engine.CCErr.CreateDefaultCCErrorIf(httpheader.GetLanguage(pHeader))

	deviceCond[common.BKOwnerIDField] = httpheader.GetSupplierAccount(pHeader)
	deviceField := []string{common.BKDeviceIDField, common.BKDeviceNameField, common.BKDeviceModelField,
		common.BKObjIDField}
	deviceResult := make([]meta.NetcollectDevice, 0)

	if err := lgc.findDevice(deviceField, deviceCond, &deviceResult, "", 0, 0); nil != err {
		blog.Errorf("[NetProperty] search net device fail by condition [%#v], error: %v, rid: %s", deviceCond, err, rid)
		if !lgc.db.IsNotFoundError(err) {
			return nil, nil, nil
		}
		return nil, nil, defErr.Error(common.CCErrCollectNetDeviceGetFail)
	}

	deviceIDs, deviceIDMapDeviceShowFields := lgc.assembleDeviceShowFieldValue(deviceResult, objIDMapShowFields)

	if 0 == len(deviceIDs) {
		return nil, nil, nil
	}

	return deviceIDs, deviceIDMapDeviceShowFields, nil
}

// assembleDeviceShowFieldValue TODO
// get device IDs from device list
// assemble value of device list: [deviceID] map [deviceName, deviceModel, objID, objName]
// objName is taken from objIDMapShowFields
func (lgc *Logics) assembleDeviceShowFieldValue(deviceData []meta.NetcollectDevice,
	objIDMapShowFields map[string]objShowField) (
	deviceIDs []uint64, deviceIDMapDeviceShowFields map[uint64]deviceShowField) {

	if nil == deviceData || 0 == len(deviceData) {
		return deviceIDs, deviceIDMapDeviceShowFields
	}

	deviceIDMapDeviceShowFields = map[uint64]deviceShowField{}

	for _, device := range deviceData {
		// get device IDs from device list
		deviceIDs = append(deviceIDs, device.DeviceID)
		// assemble value of device list: [deviceID] map [deviceName, deviceModel, objID, objName]
		deviceIDMapDeviceShowFields[device.DeviceID] = deviceShowField{
			deviceName:  device.DeviceName,
			deviceModel: device.DeviceModel,
			objID:       device.ObjectID,
			objName:     objIDMapShowFields[device.ObjectID].objName,
		}
	}

	return deviceIDs, deviceIDMapDeviceShowFields
}

// getPropertyIDsAndShowFields TODO
// get objectID, property ID list and get field to show by map (bk_property_id --> bk_property_name, ...)
func (lgc *Logics) getPropertyIDsAndShowFields(pHeader http.Header, propertyCond map[string]interface{}) ([]string,
	[]string, map[string]propertyShowField, error) {

	defErr := lgc.Engine.CCErr.CreateDefaultCC


onfig["MS_GRAPH_PERMISSIONS_SCOPE"])
        return redirect(session["flow"]["auth_uri"]), 302
    return render_template("common/auth/sign_in_sso.html", form=form, magic_link_redirect=magic_link_redirect)

@auth_blueprint.route("/sso/get-token", methods=["GET"])
@redirect_if_authenticated
@auto_commit_after_request
def sso_get_token() -> ResponseReturnValue:
    result = build_msal_app().acquire_token_by_auth_code_flow(session.get("flow", {}), request.args)
    if "error" in result:
        return abort(500, "Azure AD get-token flow failed with: {}".format(result))

    sso_user = result["id_token_claims"]

    # Does the user exist already?
    user = interfaces.user.get_user_by_azure_ad_subject_id(azure_ad_subject_id=sso_user["sub"])

    # Platform admin route
    if "FSD_ADMIN" in sso_user.get("roles", []):
        user = interfaces.user.upsert_user_and_set_platform_admin_role(
            azure_ad_subject_id=sso_user["sub"], email_address=sso_user["preferred_username"], name=sso_user["name"]
        )

    # Invitations route
    elif user is None:
        user_invites = interfaces.user.get_usable_invitations_by_email(email=sso_user["preferred_username"])
        # TODO: We should remove these 403s - MHCLG people should be able to login but not see anything if no roles
        if not user_invites:
            return render_template(
                "common/auth/mhclg-user-not-authorised.html",
                service_desk_url=current_app.config["SERVICE_DESK_URL"],
                invite_expired=True,
            ), 403
        user = interfaces.user.create_user_and_claim_invitations(
            azure_ad_subject_id=sso_user["sub"],
            email_address=sso_user["preferred_username"],
            name=sso_user["name"],
        )

    # Existing User with roles route
    elif user and user.roles:
        user = interfaces.user.upsert_user_by_azure_ad_subject_id(
            azure_ad_subject_id=sso_user["sub"],
            email_address=sso_user["preferred_username"],
            name=sso_user["name"],
        )
        if AuthorisationHelper.is_platform_admin(user):
            interfaces.user.remove_platform_admin_role_from_user(user)
            # TODO: We should remove these 403s - MHCLG people should be able to login but not see anything if no roles
            if not user.roles:
                return render_template(
                    "common/auth/mhclg-user-not-authorised.html",
                    service_desk_url=current_app.config["SERVICE_DESK_URL"],
                ), 403

    # No user user and no roles means they should 403 for now
    else:
        # TODO: We should remove these 403s - MHCLG people should be able to login but not see anything if no roles
        return render_template(
            "common/auth/mhclg-user-not-authorised.html", service_desk_url=current_app.config["SERVICE_DESK_URL"]
        ), 403

    # For all other valid users with roles after the above, finish the flow and redirect
    redirect_to_path = sanitise_redirect_url(session.pop("next", url_for("index")))
    session.pop("flow", None)

    if not login_user(user):
        return abort(400)

    session["auth"] = AuthMethodEnum.SSO

    return redirect(redirect_to_path)

@auth_blueprint.get("/sign-out")
def sign_out() -> ResponseReturnValue:
    logout_user()

    return redirect(url_for("index"))


con{display:none}#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row-container{background-color:#fff;border-top:1px solid #c3c4c7;bottom:0;position:absolute;width:100%}#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row{display:flex;flex-direction:column;justify-content:space-between;margin:24px;position:relative;text-align:left}@media screen and (min-width:661px){#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row{flex-direction:row}}#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row p{font-size:13px;line-height:1.5;margin-bottom:0;margin-top:0;padding-top:0}@media screen and (min-width:661px){#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row p{padding-top:5px}}#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row .jetpack_deactivation_dialog_content__buttons button{-webkit-appearance:none;appearance:none;background:#f6f7f7;border:1px solid #2271b1;border-radius:3px;box-sizing:border-box;color:#2271b1;cursor:pointer;display:inline-block;font-size:14px;font-size:13px;margin:0 0 18px;outline:0;overflow:hidden;padding:7px 14px 9px;text-decoration:none;text-overflow:ellipsis;vertical-align:top;width:100%}@media screen and (min-width:661px){#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row .jetpack_deactivation_dialog_content__buttons button{margin-bottom:0;margin-left:18px;width:auto}}#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row .jetpack_deactivation_dialog_content__buttons button#jetpack_deactivation_dialog_content__button-deactivate{background:#d94f4f;border-color:#a02222;color:#fff;margin-bottom:0}#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row .jetpack_deactivation_dialog_content__buttons button#jetpack_deactivation_dialog_content__button-deactivate:disabled,#TB_window.jetpack-disconnect-modal .jetpack_deactivation_dialog_content__buttons-row .jetpack_deactivation_dialog_content__buttons button#jetpack_deactivation_dialog_content__button-deactivate[disabled]{background:#eba3a3;border-color:#e48484}#jetpack_deactivation_dialog{display:none}@charset "UTF-8";
:root {
  --font-title-large: 36px;
  --font-title-small: 24px;
  --font-body: 16px;
  --font-label: 12px;
  --jp-black: #000000;
  --jp-black-80: #2c3338;
  --jp-white: #ffffff;
  --jp-white-off: #f9f9f6;
  --jp-gray: #dcdcde;
  --jp-gray-0: #F6F7F7;
  --jp-gray-5: #dcdcde;
  --jp-gray-10: #c3c4c7;
  --jp-gray-20: #A7AAAD;
  --jp-gray-30: #8c8f94;
  --jp-gray-40: #787C82;
  --jp-gray-50: #646970;
  --jp-gray-60: #50575E;
  --jp-gray-70: #3c434a;
  --jp-gray-80: #2C3338;
  --jp-gray-90: #1d2327;
  --jp-gray-100: #101517;
  --jp-gray-off: #e2e2df;
  --jp-yellow-5: #f5e6b3;
  --jp-yellow-10