# -*- coding: utf-8 -*-
"""Location: ./tests/unit/mcpgateway/plugins/framework/test_errors.py
Copyright 2025
SPDX-License-Identifier: Apache-2.0
Authors: Mihai Criveti

Tests for errors module.
"""

# Third-Party
import pytest
import re
from mcpgateway.plugins.framework.errors import convert_exception_to_error
from mcpgateway.plugins.framework import (
    GlobalContext,
    PluginError,
    PluginMode,
    PluginManager,
    PromptPrehookPayload,
)

@pytest.mark.asyncio
async def test_convert_exception_to_error():
    error_model = convert_exception_to_error(ValueError("This is some error."), "SomePluginName")
    assert error_model.message == "ValueError('This is some error.')"
    assert error_model.plugin_name == "SomePluginName"

    plugin_error = PluginError(error_model)

    assert plugin_error.error.message == "ValueError('This is some error.')"
    assert plugin_error.error.plugin_name == "SomePluginName"

@pytest.mark.asyncio
async def test_error_plugin():
    plugin_manager = PluginManager(config="tests/unit/mcpgateway/plugins/fixtures/configs/error_plugin.yaml")
    await plugin_manager.initialize()
    payload = PromptPrehookPayload(name="test_prompt", args={"arg0": "This is a crap argument"})
    global_context = GlobalContext(request_id="1")
    escaped_regex = re.escape("ValueError('Sadly! Prompt prefetch is broken!')")
    with pytest.raises(PluginError, match=escaped_regex):
        await plugin_manager.prompt_pre_fetch(payload, global_context)

    await plugin_manager.shutdown()

async def test_error_plugin_raise_error_false():
    plugin_manager = PluginManager(config="tests/unit/mcpgateway/plugins/fixtures/configs/error_plugin_raise_error_false.yaml")
    await plugin_manager.initialize()
    payload = PromptPrehookPayload(name="test_prompt", args={"arg0": "This is a crap argument"})
    global_context = GlobalContext(request_id="1")
    with pytest.raises(PluginError):
        result, _ = await plugin_manager.prompt_pre_fetch(payload, global_context)
    #assert result.continue_processing
    #assert not result.modified_payload

    await plugin_manager.shutdown()
    plugin_manager.config.plugins[0].mode = PluginMode.ENFORCE_IGNORE_ERROR
    await plugin_manager.initialize()
    result, _ = await plugin_manager.prompt_pre_fetch(payload, global_context)
    assert result.continue_processing
    assert not result.modified_payload
    await plugin_manager.shutdown()


ck';
import { TypeRegistry } from '@polkadot/types/create';

import { RpcCore } from './index.js';

describe('Cached Observables', (): void => {
  const registry = new TypeRegistry();
  let rpc: RpcCore & RpcInterface;
  let provider: MockProvider;
  const keyring = createTestPairs();

  beforeEach((): void => {
    provider = new MockProvider(registry);
    rpc = new RpcCore('123', registry, { provider }) as (RpcCore & RpcInterface);
  });

  afterEach(async () => {
    await provider.disconnect();
  });

  it('creates a single observable for subscriptions (multiple calls)', (): void => {
    const observable1 = rpc.state.subscribeStorage([123]);
    const observable2 = rpc.state.subscribeStorage([123]);

    expect(observable2).toBe(observable1);
  });

  it('creates a single observable for subscriptions (multiple calls, no arguments)', (): void => {
    const observable1 = rpc.chain.subscribeNewHeads();
    const observable2 = rpc.chain.subscribeNewHeads();

    expect(observable2).toBe(observable1);
  });

  it('creates a single observable (multiple calls, different arguments that should be cached together)', (): void => {
    const observable1 = rpc.state.subscribeStorage([keyring.alice.address]);
    const observable2 = rpc.state.subscribeStorage([registry.createType('AccountId', keyring.alice.address)]);

    expect(observable2).toBe(observable1);
  });

  it('creates multiple observables for different values', (): void => {
    const observable1 = rpc.chain.getBlockHash(123);
    const observable2 = rpc.chain.getBlockHash(456);

    expect(observable2).not.toBe(observable1);
  });

  it('subscribes to the same one if within the period (unbsub delay)', async (): Promise<void> => {
    const observable1 = rpc.chain.subscribeNewHeads();
    const sub1 = observable1.subscribe();

    sub1.unsubscribe();

    await new Promise<boolean>((resolve) => {
      setTimeout((): void => {
        const observable2 = rpc.chain.subscribeNewHeads();
        const sub2 = observable2.subscribe();

        expect(observable1).toBe(observable2);

        sub2.unsubscribe();
        resolve(true);
      }, 500);
    });
  });

  it('clears cache if there are no more subscribers', async (): Promise<void> => {
    const observable1 = rpc.chain.subscribeNewHeads();
    const observable2 = rpc.chain.subscribeNewHeads();
    const sub1 = observable1.subscribe();
    const sub2 = observable2.subscribe();

    expect(observable1).


sta"
L["settings.visuals.vm_cambob.title"] = "Balanceo al Esprintar"
L["settings.visuals.vm_cambob.desc"] = "Hace que tu cámara se mueva cuando esprintas"
L["settings.visuals.vm_cambobwalk.title"] = "Balanceo de Vista al Caminar"
L["settings.visuals.vm_cambobwalk.desc"] = "Hace que tu cámara se mueva ligeramente cuando caminas (requiere balanceo al esprintar)"
L["settings.visuals.vm_cambobintensity.title"] = "Intensidad"
L["settings.visuals.vm_cambobintensity.desc"] = "Qué tan intenso será el balanceo"

L["settings.visuals.tpik"] = "TPIK"
L["settings.visuals.tpik.title"] = "Habilitar TPIK"
L["settings.visuals.tpik.desc"] = "TPIK (Third Person Inverse Kinematics) es un sistema que permite que la mayoría de las armas se muestren detalladas e igual que en primera persona, posiciones de manos, recarga y animaciones de disparo en tercera persona."
L["settings.visuals.tpik_others.title"] = "TPIK de otros jugadores"
L["settings.visuals.tpik_others.desc"] = "Mostrar TPIK para otros jugadores que no seas tú. Impacta negativamente en el rendimiento."
L["settings.visuals.tpik_framerate.title"] = "TPIK FPS"
L["settings.visuals.tpik_framerate.desc"] = "Velocidad de fotogramas máxima a la que puede funcionar TPIK. Establecer a 0 para ilimitado."

////////////////////// Bullet Physics
L["settings.tabname.bullets"] = "Balas Fisicas"

L["settings.bullets.bullets"] = "Balas Físicas"
L["settings.bullets.bullet_physics.title"] = "Balas Físicas"
L["settings.bullets.bullet_physics.desc"] = "Las armas que admitan esta característica dispararán balas físicas, que tienen caída, tiempo de recorrido y arrastre.\n\nEsta es una variable del servidor."
L["settings.bullets.bullet_gravity.title"] = "Gravedad"
L["settings.bullets.bullet_gravity.desc"] = "Multiplicador para la gravedad de la bala.\n\nEsta es una variable del servidor."
L["settings.bullets.bullet_drag.title"] = "Arrastre"
L["settings.bullets.bullet_drag.desc"] = "Multiplicador para el arrastre de balas.\n\nEsta es una variable del servidor."
L["settings.bullets.ricochet.title"] = "Rebote"
L["settings.bullets.ricochet.desc"] = "Las balas disparadas con armas seleccionadas a veces pueden rebotar en las superficies y seguir viajando y causando daño.\n\nEsta es una variable del servidor."
L["settings.bullets.mod_penetration.title"] = "Penetracion"
L["settings.bullets.mod_penetration.desc"] = "Las balas disparadas desde armas seleccionadas pueden penetrar superficies e infligir daño a lo que haya al otro lado.\n\nEsta es una variable del servidor."
L["settings.bullets.bullet_lifetime.title"] = "Tiempo De Vida"
L["settings.bullets.bullet_lifetime.desc"] = "Tiempo en segundos tras el cual se borrará una bala.\n\nEsta es una variable del servidor."
L["settings.bullets.bullet_imaginary.title"] = "Balas Imaginarias"
L["settings.bullets.bullet_imaginary.desc"] = "Las balas parecerán viajar hacia


using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System.Linq;

namespace Terraria.ModLoader.Setup.Formatting
{
	public static class SyntaxUtils
	{
		//public static bool SpansSingleLine(this SyntaxNode node) {
		//	var lineSpan = node.SyntaxTree.GetLineSpan(node.Span);
		//	return lineSpan.StartLinePosition.Line == lineSpan.EndLinePosition.Line;
		//}

		public static bool SpansSingleLine(this SyntaxNode node) => !node.DescendantTrivia(node.Span).Any(t => t.IsKind(SyntaxKind.EndOfLineTrivia));

		public static bool IsWhitespace(this SyntaxTrivia trivia) => trivia.IsKind(SyntaxKind.WhitespaceTrivia) || trivia.IsKind(SyntaxKind.EndOfLineTrivia);

		public static string GetIndentation(this SyntaxNode node) => GetIndentation(node.SyntaxTree, node.SpanStart);
		public static string GetIndentation(this SyntaxToken node) => GetIndentation(node.SyntaxTree, node.SpanStart);

		public static string GetIndentation(Synta


/*
===============================================================================

 Support:
    __agbabi_atan2

 Taken from https://www.coranac.com/documents/arctangent/ by Jasper "cearn" Vijn
 Modified for libagbabi

===============================================================================
*/

#define BAM_BITS    ( 16 )

    .arm
    .align 2

    .section .iwram.__agbabi_atan2, "ax", %progbits
    .global __agbabi_atan2
__agbabi_atan2:
    subs    r3, r1, #0
    mov     r1, r0
    bne     .Latan2_octantify

    // Convert sign bit to pi
    lsr     r1, r0, #31
    lsl     r0, r1, #(BAM_BITS - 1)
    bx      lr

.Latan2_octantify:
    push    {r4, lr}

    // Fallthough flags from previous subs
    rsblt   r1, r0, #0 // x = -x
    rsblt   r3, r3, #0 // y = -y
    movlt   r2, #6
    movge   r2, #2

    movlt   r4, #4
    movge   r4, #0

    cmp     r1, #0
    rsble   r0, r1, #0 // t = -x
    movle   r1, r3 // x = y
    movle   r3, r0 // y = t

    movle   r4, r2

    cmp     r1, r3
    suble   r2, r3, r1 // t = y - x
    addl


from typing import Any, Dict, Iterator, List, Optional, Set, Tuple

from pydantic import BaseModel, ConfigDict

SEARCH_RESULT = Tuple[Dict[str, Any], Dict, float, Optional[Dict]]

class DuckDBSearchResult(BaseModel):

    model_config = ConfigDict(protected_namespaces=())

    ids: Optional[str] = None
    metadatas: Optional[Dict[str, Any]] = None
    embeddings: Optional[List[float]] = None
    documents: Optional[str] = None
    distances: Optional[float] = 0  # TODO: technically this is simple cosim similarity
    include: Optional[Set[str]] = None

    def to_json(self, indent: int = 2):
        return self.model_dump_json(include=self.include, indent=indent)

    def to_dict(self):
        if self.include:
            return self.model_dump(include=self.include)
        return self.model_dump()

    def __repr__(self, indent: int = 2):
        return self.model_dump_json(include=self.include, indent=indent)

    def __iter__(self) -> Iterator[SEARCH_RESULT]:
        # TODO vocab.py for 'VARIABLES', but circular import
        metadata_include = "metadatas" in self.include if self.include else True
        embeddings_include = "embeddings" in self.include if self.include else True
        documents_include = "documents" in self.include if self.include else True
        similarity_include = "distances" in self.include if self.include else True

        obj = self.metadatas if metadata_include else {}
        meta = {
            "_embeddings": self.embeddings if embeddings_include else None,
            "documents": self.documents if documents_include else None,
        }
        distance = self.distances if similarity_include else None

        yield obj, distance, meta


import requests
import time
from api_secrets import API_KEY_ASSEMBLYAI

upload_endpoint = "https://api.assemblyai.com/v2/upload"
transcription_endpoint = "https://api.assemblyai.com/v2/transcript"

headers = {'authorization': API_KEY_ASSEMBLYAI}

# upload
def upload(filename):
    def read_file(filename):
        with open(filename, 'rb') as f:
            while True:
                data = f.read(5242880)
                if not data:
                    break
                yield data

    upload_response = requests.post(upload_endpoint, headers=headers, data=read_file(filename))
    # print(upload_response.json())
    audio_url = upload_response.json()['upload_url']

    return audio_url

# start transcription
def transcribe(audio_url):
    json = {
        'audio_url': audio_url
    }

    transcript_response = requests.post(transcription_endpoint, json=json, headers=headers)
    job_id = transcript_response.json()['id']
    return job_id

# transcript_id = transcribe(audio_url=audio_url)
# print(transcript_id)

# poll for transcription

def poll(transcript_id):
    polling_endpoint = transcription_endpoint + '/' + transcript_id
    polling_res = requests.get(polling_endpoint, headers=headers)
    # print(polling_res.json())
    return polling_res.json()

def get_transcription_result_url(audio_url):
    transcribe_id = transcribe(audio_url)

    # loop until transcription is completed
    while True:
        data = poll(transcribe_id)
        if data['status'] == 'completed':
            # print("completed")
            return data, None
        elif data['status'] == 'error':
            return data, data['error']

        # wait 30 seconds before polling again
        print("waiting 10 seconds...")
        time.sleep(10)

# save transcription
def save_transcript(audio_url, filename):
    data, error = get_transcription_result_url(audio_url)
    if data:
        text_filename = filename + '.txt'
        with open(text_filename, 'w') as f:
            f.write(data['text'])

        print(f"Transcription saved to {text_filename}")

    elif error:
        print(f"Error: {error}")


', '']);
      expect(Array.from(Rope.leaf('Hello world\r\n').lines())).to.deep.equal(['Hello world', '']);
      expect(Array.from(Rope.leaf('Hello,\nworld\n').lines())).to.deep.equal(['Hello,', 'world', '']);
      expect(Array.from(Rope.leaf('Hello,\nworld\r\n').lines())).to.deep.equal(['Hello,', 'world', '']);
      expect(Array.from(Rope.leaf('Hello,\r\nworld\n').lines())).to.deep.equal(['Hello,', 'world', '']);
      expect(Array.from(Rope.leaf('Hello,\r\nworld\r\n').lines())).to.deep.equal(['Hello,', 'world', '']);
    });
  });

  describe('#lineIndices', () => {
    it('should iterate over lines with character index/offset', () => {
      expect(Array.from(Rope.leaf('').lineIndices())).to.deep.equal([[0, '']]);
      expect(Array.from(Rope.leaf('\n').lineIndices())).to.deep.equal([[0, ''], [1, '']]);
      expect(Array.from(Rope.leaf('\r\n').lineIndices())).to.deep.equal([[0, ''], [2, '']]);
      expect(Array.from(Rope.leaf('\n\n').lineIndices())).to.deep.equal([[0, ''], [1, ''], [2, '']]);
      expect(Array.from(Rope.leaf('\n\r\n').lineIndices())).to.deep.equal([[0, ''], [1, ''], [3, '']]);
      expect(Array.from(Rope.leaf('\r\n\r\n').lineIndices())).to.deep.equal([[0, ''], [2, ''], [4, '']]);
      expect(Array.from(Rope.leaf('a\n').lineIndices())).to.deep.equal([[0, 'a'], [2, '']]);
      expect(Array.from(Rope.leaf(' \r\n').lineIndices())).to.deep.equal([[0, ' '], [3, '']]);
      expect(Array.from(Rope.leaf('Hello world\n').lineIndices())).to.deep.equal([[0, 'Hello world'], [12, '']]);
      expect(Array.from(Rope.leaf('Hello world\r\n').lineIndices())).to.deep.equal([[0, 'Hello world'], [13, '']]);
      expect(Array.from(Rope.leaf('Hello,\nworld\n').lineIndices())).to.deep.equal([[0, 'Hello,'], [7, 'world'], [13, '']]);
      expect(Array.from(Rope.leaf('Hello,\nworld\r\n').lineIndices())).to.deep.equal([[0, 'Hello,'], [7, 'world'], [14, '']]);
      expect(Array.from(Rope.leaf('Hello,\r\nworld\n').lineIndices())).to.deep.equal([[0, 'Hello,'], [8, 'world'], [14, '']]);
      expect(Array.from(Rope.leaf('Hello,\r\nworld\r\n').lineIndices())).to.deep.equal([[0, 'Hello,'], [8, 'world'], [15, '']]);
    });
  });

  describe('#charToLine', () => {
    it('should return line index of given char', () => {
      expect(Rope.leaf('').charToLine(0)).to.equal(0);
      expect(Rope.leaf('\n').charToLine(0)).to.equal(0);
      expect(Rope.leaf('\n').charToLine(1)).to.equal(1);
      expect(Rope.leaf('\r\n').charToLine(


let stringTabla:string="
";
                        let stringCiudadano:string="";
                        objeto.forEach(ciudadano =>
                        {
                            if(objeto._pais==pais)
                            {
                                stringCiudadano="
"+objeto._nombre+"-"+objeto._apellido+"-"+objeto._edad+"-"+objeto._dni+"-"+objeto._pais+"	Eliminar	Modificar
";
                                stringTabla+=stringCiudadano;
                            }
                        });
                        stringTabla+="
";
                        (<HTMLDivElement>document.getElementById("divTabla")).innerHTML=stringTabla;

                    }
                }
                this.LimpiarForm();
        }

        public CargarPaisesJson():void
        {
            let xmlhttp : XMLHttpRequest = new XMLHttpRequest();

            xmlhttp.open("POST", "./BACKEND/administrar.php", true);
            xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
            xmlhttp.send("caso=paises");

                xmlhttp.onreadystatechange = function()
                {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                    {
                        let objeto =JSON.parse(xmlhttp.responseText);
                        objeto.forEach(paises => {
                            document.getElementById("cboPais").add(paises.descripcion);
                        });
                    }
                }
                this.LimpiarForm();
        }

        public LimpiarForm():void
        {
            (<HTMLInputElement>document.getElementById("txtNombre")).value="";
            (<HTMLInputElement>document.getElementById("txtApellido")).value="";
            (<HTMLInputElement>document.getElementById("txtEdad")).value="";
            (<HTMLInputElement>document.getElementById("txtDni")).value="";
            (<HTMLInputElement>document.getElementById("cboPais")).value=(<HTMLInputElement>document.getElementById("cboPais")).option[0].text;
        }
    }
}import { Socket } from 'socket.io';
import ControllerEvents from '../constants/controller-events';
import * as jwtService from '../services/jwt-service';
import UserRepository from '../repositories/user-repository';

export interface IAuthParams {
    token: string;
}

export interface ITokenData {
    username: string;
}

const userRepository = new UserRepository();

export default function auth<TParams extends IAuthParams>(fn: (params: TParams, tokenData: ITokenData) => void) {
    return function (this: Socket, params: TParams): void {
        const tokenData = jwtService.verify<ITokenData>(params.token);

        if (tokenData && userRepository.updateLastRequestAt(tokenData.username)) {
            fn(params, tokenData);
        } else {
            this.emit(ControllerEvents.Unauthorized);
        }
    };
}
import {Injectable} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import { throwError } from 'rxjs';
import {map, catchError} from 'rxjs/operators';

@Injectable() // Es necesario para que este servicio pueda utilizar otros servicios (en este caso el HttpService).

export class ServerService {

  constructor(private http: Http) {
  }

  getServers() {
    return this.http.get('https://udemy


tr  $4, $5, 1, 2, 0         # encoding: [0x41,0x84,0x28,0x22]
  mtthc1 $4, $f5         # CHECK: mttr  $4, $5, 1, 2, 1         # encoding: [0x41,0x84,0x28,0x32]
  cttc1  $4, $f9         # CHECK: mttr  $4, $9, 1, 3, 0         # encoding: [0x41,0x84,0x48,0x23]


.GetCapacity(name)
		checkErr("GetCapacity", cap, err)
		accessModes, err := handler.GetAccessModes(name)
		checkErr("GetAccessModes", accessModes, err)
		sc, err := handler.GetStorageClass(name)
		checkErr("GetStorageClass", sc, err)
		age, err := handler.GetAge(name)
		checkErr("GetAge", age, err)
		volumeMode, err := handler.GetVolumeMode(name)
		checkErr("GetVolumeMode", volumeMode, err)

		end := time.Now()
		log.Println("===== Get PersistentVolumeClaim By Name Cost Time:", end.Sub(begin))
		log.Println()
	}

	getByObj := func() {
		log.Println("===== Get PersistentVolumeClaim By Object")
		begin := time.Now()

		status, err := handler.GetStatus(pvc)
		checkErr("GetStatus", status, err)
		pv, err := handler.GetVolume(pvc)
		checkErr("GetVolume", pv, err)
		cap, err := handler.GetCapacity(pvc)
		checkErr("GetCapacity", cap, err)
		accessModes, err := handler.GetAccessModes(pvc)
		checkErr("GetAccessModes", accessModes, err)
		sc, err := handler.GetStorageClass(pvc)
		checkErr("GetStorageClass", sc, err)
		age, err := handler.GetAge(pvc)
		checkErr("GetAge", age, err)
		volumeMode, err := handler.GetVolumeMode(pvc)
		checkErr("GetVolumeMode", volumeMode, err)

		end := time.Now()
		log.Println("===== Get PersistentVolumeClaim By Object Cost Time:", end.Sub(begin))
	}

	getByName()
	getByObj()

	// Output:

	//2022/07/10 20:40:08 ===== Get PersistentVolumeClaim By Name
	//2022/07/10 20:40:08 GetStatus success: Bound
	//2022/07/10 20:40:08 GetVolume success: mypv
	//2022/07/10 20:40:08 GetCapacity success: 8000000000
	//2022/07/10 20:40:08 GetAccessModes success: [ReadWriteOnce ReadWriteMany ReadOnlyMany]
	//2022/07/10 20:40:08 GetStorageClass success: nfs-sc
	//2022/07/10 20:40:08 GetAge success: 37m11.057548s
	//2022/07/10 20:40:08 GetVolumeMode success: Filesystem
	//2022/07/10 20:40:08 ===== Get PersistentVolumeClaim By Name Cost Time: 19.274162ms
	//2022/07/10 20:40:08
	//2022/07/10 20:40:08 ===== Get PersistentVolumeClaim By Object
	//2022/07/10 20:40:08 GetStatus success: Bound
	//2022/07/10 20:40:08 GetVolume success: mypv
	//2022/07/10 20:40:08 GetCapacity success: 8000000000
	//2022/07/10 20:40:08 GetAccessModes success: [ReadWriteOnce ReadWriteMany ReadOnlyMany]
	//2022/07/10 20:40:08 GetStorageClass success: nfs-sc
	//2022/07/10 20:40:08 GetAge success: 37m11.059772s
	//2022/07/10 20:40:08 GetVolumeMode success: Filesystem
	//2022/07/10 20:40:08 ===== Get PersistentVolumeClaim By Object Cost Time: 15.368µs
}
package main

import (
	"context"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/forbearing/k8s/ingress"
)

var (
	ctx, cancel = context.WithTimeout(context


//---------------------------------------------------------------------
// <copyright file="CsdlSemanticsAnnotationPathExpression.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

using Microsoft.OData.Edm.Csdl.Parsing.Ast;

namespace Microsoft.OData.Edm.Csdl.CsdlSemantics
{
    /// <summary>
    /// Provides seman


  @Column()
  image!: string;

  @Column()
  @Field(() => Int)
  creatorId!: number;

  @ManyToOne(() => User, (creator) => creator.posts)
  @Field(() => User)
  creator!: User;

  @OneToMany(() => Upvote, (upvote) => upvote.user)
  upvotes!: Upvote[];

  @OneToMany(() => Comment, (comment) => comment.user)
  comments!: Comment[];

}import { head } from '../../../utils/array/head'
import { Renderer2d } from '../../game-utils/renderer2d'
import { Player } from './player'
import { Point } from './point'
import { Game } from './game'
import { Level } from './level'
import { Food } from './food'

export class Renderer extends Renderer2d {
  drawGame(_game: Game): void {
    this.clearScreen()
  }

  drawLevel(level: Level): void {
    for (let i = 0; i < level.walls.length; i++) {
      this.drawWallPiece(level.walls[i])
    }
  }

  private drawWallPiece({ x, y }: Point): void {
    this.context.fillRect(x * 10, y * 10, 10, 10)
  }

  drawPlayer(player: Player): void {
    for (let i = 0; i < player.tail.length; i++) {
      this.drawPlayerBodyPart(player.tail[i])
    }

    if (!player.alive) {
      this.context.fillStyle = '#ff0000'
      this.drawPlayerBodyPart(head(player))
      this.context.fillStyle = '#000000'
    }
  }

  private drawPlayerBodyPart({ x, y }: Point): void {
    this.context.fillRect(x * 10 + 1, y * 10 + 1, 8, 8)
  }

  drawFood({ x, y }: Food): void {
    this.context.fillRect(x * 10 + 3, y * 10 + 3, 4, 4)
  }
}
/*
 * Copyright (C) 2011, 2014 Josh A. Beam
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *   1. Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *   2. Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS


// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace WebSockets.Server
{
    using System;
    using System.Diagnostics;
    using System.Text;
    using System.Threading.Tasks;
    using DotNetty.Buffers;
    using DotNetty.Codecs.Http;
    using DotNetty.Codecs.Http.WebSockets;
    using DotNetty.Common.Utilities;
    using DotNetty.Transport.Channels;
    using Examples.Common;

    using static DotNetty.Codecs.Http.HttpVersion;
    using static DotNetty.Codecs.Http.HttpResponseStatus;

    public sealed class WebSocketServerHandler : SimpleChannelInboundHandler<object>
    {
        const string WebsocketPath = "/websocket";

        WebSocketServerHandshaker handshaker;

        protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
        {
            if (msg is IFullHttpRequest request)
            {
                this.HandleHttpRequest(ctx, request);
            }
            else if (msg is WebSocketFrame frame)
            {
                this.HandleWebSocketFrame(ctx, frame);
            }
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        void HandleHttpRequest(IChannelHandlerContext ctx, IFullHttpRequest req)
        {
            // Handle a bad request.
            if (!req.Result.IsSuccess)
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, BadRequest));
                return;
            }

            // Allow only GET methods.
            if (!Equals(req.Method, HttpMethod.Get))
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, Forbidden));
                return;
            }

            // Send the demo page and favicon.ico
            if ("/".Equals(req.Uri))
            {
                IByteBuffer content = WebSocketServerBenchmarkPage.GetContent(GetWebSocketLocation(req));
                var res = new DefaultFullHttpResponse(Http11, OK, content);

                res.Headers.Set(HttpHeaderNames.ContentType, "text/html; charset=UTF-8");
                HttpUtil.SetContentLength(res, content.ReadableBytes);

                SendHttpResponse(ctx, req, res);
                return;
            }
            if ("/favicon.ico".Equals(req.Uri))
            {
                var res = new DefaultFullHttpResponse(Http11, NotFound);
                SendHttpResponse(ctx, req, res);
                return;
            }

            // Handshake
            var wsFactory = new WebSocketServerHandshakerFactory(
                GetWebSocketLocation(req), null, true, 5 * 1024 * 1024);
            this.handshaker = wsFactory.NewHandshaker(req);


");
				map = new Map(div, options);
				map.fitTo([-160, 70, 160, -70]);

			});

		});
</script>

<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta name="viewport" content="user-scalable=no, width=device-width" />
		<meta name="apple-mobile-web-app-capable" content="yes" />

		<title>Simple Maps,support pan and zoom navigation</title>

Keyboard Tips: Use TAB to focus the map, then use up/down/left/right to go around the map, zoom in by SPACE and zoom out by ESC.

<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Chart: Map&Chart</title>


	total := int64(0)
	err := db.Count(&total).Error
	if err != nil || total == 0 {
		err = errors.Wrap(err, "Count customer_event failed")
		return nil, 0, err
	}

	sorter.SetDefault()
	db = db.Order(clause.OrderByColumn{Column: clause.Column{Name: string(sorter.SortField)}, Desc: sorter.SortType == constants.SortTypeDesc})

	pager.SetDefault()
	db = db.Offset(pager.GetOffset()).Limit(pager.GetLimit())

	err = db.Find(&items).Error
	if err != nil {
		err = errors.Wrap(err, "Find customer event failed")
		return nil, 0, err
	}

	return items, total, nil
}

// Create 支持前端创建 模板记录、跟进记录和提醒事件
func (c CustomerEvent) Create(ce CustomerEvent) error {
	return DB.Model(&CustomerEvent{}).Create(&ce).Error
}

func (c CustomerEvent) CreateInBatches(ce []CustomerEvent) error {
	return DB.Model(&CustomerEvent{}).CreateInBatches(&ce, 100).Error
}

func (c CustomerEvent) Update(ce CustomerEvent) (CustomerEvent, error) {
	customerEvent := CustomerEvent{}
	err := DB.Model(CustomerEvent{ExtCorpModel: ExtCorpModel{ID: ce.ID}}).First(&customerEvent).Error
	if err == gorm.ErrRecordNotFound {
		err = errors.WithStack(ecode.ItemNotFoundError)
		return customerEvent, err
	}
	if err != nil {
		err = errors.Wrap(err, "find CustomerEvent failed")
		return customerEvent, err
	}

	err = DB.Model(CustomerEvent{ExtCorpModel: ExtCorpModel{ID: ce.ID}}).Updates(&ce).Error
	if err != nil {
		err = errors.Wrap(err, "Update CustomerEvent failed")
		return customerEvent, err
	}

	return ce, err
}

func (c CustomerEvent) Delete(ids []string, extCorpID string) (int64, error) {
	result := DB.Where("ext_corp_id = ?", extCorpID).Where("id in (?)", ids).Delete(&ContactWayGroup{})
	err := result.Error
	if err != nil {
		err = errors.Wrap(err, "Delete ContactWayGroup failed")
		return 0, err
	}

	return result.RowsAffected, err
}

func (c CustomerEvent) Get(id string) (CustomerEvent, error) {
	var ce CustomerEvent
	err := DB.Model(&CustomerEvent{}).Where("id = ?", id).First(&ce).Error
	if err != nil {
		log.Sugar.Errorw("get customer event failed", "id", id)
		return ce, err
	}
	return ce, err
}
package models

import (
	"github.com/pkg/errors"
	"gorm.io/gorm/clause"
	"openscrm/app/constants"
	"openscrm/common/app"
)

type MaterialLibTag struct {
	ExtCorpModel
	Name string `json:"name"`
	Timestamp
}

func (o MaterialLibTag) Create(tag []MaterialLibTag) error {
	return DB.CreateInBatches(&tag, 100).Error
}

func (o MaterialLibTag) Delete(ids []string) (int64, error) {
	res := DB.Model(&MaterialLibTag{}).Where("id in (?)", ids).Delete(&MaterialLibTag{})
	return res.RowsAffected, res.Error
}
func (o MaterialLibTag) Query(tag MaterialLibTag, sorter *app.Sorter, pager *app.P


="mat4x4"&&x!=="mat4x4f"&&x!=="mat4x4h")return void console.error(`Invalid assignment to ${n}. Line ${e.line}`);if(!(p<4&&a.data.length===4))return void console.error(`Invalid assignment to ${n}. Line ${e.line}`);i.data[4*p]=a.data[0],i.data[4*p+1]=a.data[1],i.data[4*p+2]=a.data[2],i.data[4*p+3]=a.data[3]}}}}}else if(s instanceof zh){let h=s.value;if(!(i instanceof ze))return void console.error(`Invalid assignment to ${h}. Variable ${n} is not a vector. Line ${e.line}`);if(a instanceof ht){if(h.length>1)return void console.error(`Invalid assignment to ${h} for variable ${n}. Line ${e.line}`);if(h==="x")i.data[0]=a.value;else if(h==="y"){if(i.data.length<2)return void console.error(`Invalid assignment to ${h} for variable ${n}. Line ${e.line}`);i.data[1]=a.value}else if(h==="z"){if(i.data.length<3)return void console.error(`Invalid assignment to ${h} for variable ${n}. Line ${e.line}`);i.data[2]=a.value}else if(h==="w"){if(i.data.length<4)return void console.error(`Invalid assignment to ${h} for variable ${n}. Line ${e.line}`);i.data[3]=a.value}}else{if(!(a instanceof ze))return void console.error(`Invalid assignment to ${n}. Line ${e.line}`);if(h.length!==a.data.length)return void console.error(`Invalid assignment to ${h} for variable ${n}. Line ${e.line}`);for(let p=0;p<h.length;++p){let x=h[p];if(x==="x"||x==="r")i.data[0]=a.data[p];else if(x==="y"||x==="g"){if(a.data.length<2)return void console.error(`Invalid assignment to ${x} for variable ${n}. Line ${e.line}`);i.data[1]=a.data[p]}else if(x==="z"||x==="b"){if(a.data.length<3)return void console.error(`Invalid assignment to ${x} for variable ${n}. Line ${e.line}`);i.data[2]=a.data[p]}else{if(x!=="w"&&x!=="a")return void console.error(`Invalid assignment to ${x} for variable ${n}. Line ${e.line}`);if(a.data.length<4)return void console.error(`Invalid assignment to ${x} for variable ${n}. Line ${e.line}`);i.data[3]=a.data[p]}}}}}else i instanceof ht&&a instanceof ht?i.value=a.value:i instanceof ze&&a instanceof ze||i instanceof Xr&&a instanceof Xr?i.data.set(a.data):console.error(`Invalid assignment to ${n}. Line ${e.line}`);else{let h=i.getSubData(this,s,r);if(h instanceof ze&&a instanceof ht){let p=h.data,x=a.value;if(c==="+=")for(let T=0;T<p.length;++T)p[T]+=x;else if(c==="-=")for(let T=0;T<p.length;++T)p[T]-=x;else if(c==="*=")for(let T=


'cerchio | cerchio rosso grande | geometria | rosso | stop',
    ),
    Emoji(
      '🔵',
      'blu | cerchio | geometria | grande',
    ),
    Emoji(
      '⚫',
      'cerchio | cerchio nero grande | geometria | nero',
    ),
    Emoji(
      '⚪',
      'bianco | cerchio | cerchio bianco grande | geometria',
    ),
    Emoji(
      '⬛',
      'geometria | quadrato | quadrato nero grande',
    ),
    Emoji(
      '⬜',
      'geometria | quadrato | quadrato bianco grande',
    ),
    Emoji(
      '◼',
      'geometria | quadrato | quadrato nero medio ',
    ),
    Emoji(
      '◻',
      'geometria | quadrato | quadrato bianco medio | quadrato vuoto ',
    ),
    Emoji(
      '◾',
      'geometria | quadrato | quadrato nero medio-piccolo',
    ),
    Emoji(
      '◽',
      'geometria | quadrato | quadrato bianco medio-piccolo',
    ),
    Emoji(
      '▪',
      'geometria | quadratino | quadrato | quadrato nero piccolo ',
    ),
    Emoji(
      '▫',
      'geometria | quadratino vuoto | quadrato | quadrato bianco piccolo ',
    ),
    Emoji(
      '🔶',
      'arancione | forma | geometria | grande | quadrato | rombo',
    ),
    Emoji(
      '🔷',
      'blu | diamante | grande | rombo',
    ),
    Emoji(
      '🔸',
      'arancione | piccolo | rombo',
    ),
    Emoji(
      '🔹',
      'blu | piccolo | rombo',
    ),
    Emoji(
      '🔺',
      'alto | forma | geometria | rosso | triangolo | triangolo rosso con punta verso l’alto | triangolo rosso punta in alto',
    ),
    Emoji(
      '🔻',
      'basso | geometria | rosso | triangolo | triangolo rosso con punta verso il basso | triangolo rosso punta in basso',
    ),
    Emoji(
      '💠',
      'carino | decorazione | diamante | emozione | fiore | forma di diamante | geometria | petalo di fiore',
    ),
    Emoji(
      '🔳',
      'contorno | geometria | pulsante | pulsante quadrato con contorno | tasto quadrato nero con bordo bianco',
    ),
    Emoji(
      '🔲',
      'geometria | pulsante | pulsante quadrato pieno | quadrato | quadrato nero | simbolo | tasto | tasto quadrato bianco con bordo nero',
    ),
  ]),

// ======================================================= Category.FLAGS
  CategoryEmoji(Category.FLAGS, [
    Emoji(
      '🏁',
      'bandiera | bandiera a scacchi | circuito | corsa | gara | podio | scacchi | sport | vittoria',
    ),
    Emoji(
      '🚩',
      'bandiera | bandiera rossa | bandiera rossa triangolare | bandierina | bandierina rossa | bandierina rossa triangolare | golf',
    ),


_PRE_SIZE]

	fmul	v28.4s, v0.4s, v10.s[1]
	OP_ii	v28.4s, v1.4s, v11.s[1]
#if defined(NR) || defined(NC) || defined(TR) || defined(TC) || \
    defined(RR) || defined(RC) || defined(CR) || defined(CC)
	eor	v29.16b, v29.16b, v29.16b
	fmls	v29.4s, v0.4s, v11.s[1]
#else
	fmul	v29.4s, v0.4s, v11.s[1]
#endif
	OP_ir	v29.4s, v1.4s, v10.s[1]

	prfm	PLDL1KEEP, [pA, #A_PRE_SIZE+64]

	fmul	v30.4s, v2.4s, v10.s[1]
	OP_ii	v30.4s, v3.4s, v11.s[1]
#if defined(NR) || defined(NC) || defined(TR) || defined(TC) || \
    defined(RR) || defined(RC) || defined(CR) || defined(CC)
	eor	v31.16b, v31.16b, v31.16b
	fmls	v31.4s, v2.4s, v11.s[1]
#else
	fmul	v31.4s, v2.4s, v11.s[1]
#endif
	OP_ir	v31.4s, v3.4s, v10.s[1]
.endm

.macro KERNEL8x4_M1
	OP_rr	v16.4s, v0.4s, v8.s[0]
	OP_ii	v16.4s, v1.4s, v9.s[0]
	OP_ri	v17.4s, v0.4s, v9.s[0]
	OP_ir	v17.4s, v1.4s, v8.s[0]

	ld2	{v12.2s, v13.2s}, [pB]
	add	pB, pB, #16

	OP_rr	v18.4s, v2.4s, v8.s[0]
	OP_ii	v18.4s, v3.4s, v9.s[0]
	OP_ri	v19.4s, v2.4s, v9.s[0]
	OP_ir	v19.4s, v3.4s, v8.s[0]

	ld2	{v4.4s, v5.4s}, [pA]
	add	pA, pA, #32

	OP_rr	v20.4s, v0.4s, v8.s[1]
	OP_ii	v20.4s, v1.4s, v9.s[1]
	OP_ri	v21.4s, v0.4s, v9.s[1]
	OP_ir	v21.4s, v1.4s, v8.s[1]

	ld2	{v6.4s, v7.4s}, [pA]
	add	pA, pA, #32

	OP_rr	v22.4s, v2.4s, v8.s[1]
	OP_ii	v22.4s, v3.4s, v9.s[1]
	OP_ri	v23.4s, v2.4s, v9.s[1]
	OP_ir	v23.4s, v3.4s, v8.s[1]

	ld2	{v1


ird-party AJAX requests from getting hold of a CSRF token.
	// See also https://michaelzanggl.com/articles/csrf-tokens-for-spas/.
	[HttpGet("token")]
	[EnableCors(AuthenticationConstants.AuthenticatedCorsApiPolicy)]
	[IgnoreAntiforgeryToken]
	[ApiExplorerSettings(IgnoreApi = true)]
	public IActionResult GetToken()
	{
		// Code from: https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-6.0#javascript-1.
		var tokenSet = _antiforgery.GetAndStoreTokens(HttpContext);
		Response.Cookies.Append("XSRF-TOKEN", tokenSet.RequestToken!, new CookieOptions { HttpOnly = false });

		return NoContent();
	}
}


null
				</style>
<button class="sc-1b3blmr-0 gPfFta" font-size="16px" font-weight="bold" style="margin:0 12px;font-size:16px;font-style:normal;font-weight:500;background-color-hover:#F5F5F5;line-height:40px" width="auto">Publicar</button>
<button class="sc-1b3blmr-0 fSRRlE" data-qa="HEADER_LOGIN" font-size="16px" font-weight="normal" style="font-size:16px;font-style:normal;font-weight:600">Iniciar sesión</button>

4

Ubicaciones

<input class="sc-hd4j3y-10 jmfPLX" id="search-location-input" name="searchBox" placeholder="Ingresá ciudades o barrios" value=""/>

Comprar

Propiedad

</


ightBlack
Stem up: noteShapeTriangleLeftBlack

so (or sol)
noteShapeRoundWhite
noteShapeRoundBlack

la (or law)
noteShapeSquareWhite
noteShapeSquareBlack

ti (or si)
noteShapeIsoscelesTriangleWhite
noteShapeIsoscelesTriangleBlack

Perhaps the most commonly-used seven-shape system, however, is that
devised by Jesse B. Aikin, though his system is sometimes incorrectly
referred to as the “Aiken” system due to an error made by the
musicologist George Pullen Jackson. Aikin introduced his system in The
Christian Minstrel (1846), and after his shapes were adopted by the
influential Ruebush & Kieffer Publishing Company in the late 19th
century they have become increasingly widely used. Again using the same
solmization as both Funk and Walker, the note shapes for each syllable
are as follows:

Syllable
Half notes and longer
Quarter notes and shorter

do
noteShapeTriangleUpWhite
noteShapeTriangleUpBlack

re
noteShapeMoonWhite
noteShapeMoonBlack

mi
noteShapeDiamondWhite
noteShapeDiamondBlack

fa (or faw)
Stem down: noteShapeTriangleRightWhite
Stem up: noteShapeTriangleLeftWhite
Stem down: noteShapeTriangleRightBlack
Stem up: noteShapeTriangleLeftBlack

so (or sol)
noteShapeRoundWhite
noteShapeRoundBlack

la (or law)
noteShapeSquareWhite
noteShapeSquareBlack

ti (or si)
noteShapeTriangleRoundWhite
noteShapeTriangleRoundBlack

For practical use, scoring applications should provide a means of
automatically substituting regular noteheads for the appropriate shape
note notehead glyph according to the pitch of each note.

See also the implementation notes for noteheads.

<span class='search-results


 := toBot(line)
		bots = append(bots, bot)
		if bot.r > maxRange {
			maxRange = bot.r
			maxBot = bot
		}
	}

	sum := 0
	for _, bot := range bots {
		if maxBot.hasInRange(bot.pos) {
			sum++
		}
	}

	return sum
}

type Bot struct {
	pos Position
	r   int
}

type Position struct {
	x int
	y int
	z int
}

func (p Position) Delta(x, y, z int) Position {
	p.x += x
	p.y += y
	p.z += z
	return p
}

func distance(a, b Position) int {
	return lib.Abs(a.x-b.x) + lib.Abs(a.y-b.y) + lib.Abs(a.z-b.z)
}

func distanceDiv(a, b Position, div int) int {
	return lib.Abs(a.x/div-b.x) + lib.Abs(a.y/div-b.y) + lib.Abs(a.z/div-b.z)
}

func (b Bot) hasInRange(pos Position) bool {
	return distance(b.pos, pos) <= b.r
}

func (b Bot) hasInRangeDiv(pos Position, div int) bool {
	d := distanceDiv(b.pos, pos, div)
	return d <= b.r/div
}

func (b Bot) isInRange(b2 Bot) bool {
	return distance(b.pos, b2.pos) <= b2.r
}

func (b Bot) isInRangeDiv(b2 Bot, div int) bool {
	return distanceDiv(b.pos, b2.pos, div) <= b2.r/div
}

func toBot(s string) Bot {
	coords := s[5:strings.Index(s, ">")]
	cdel := lib.NewDelimiter(coords, ",")

	space := strings.Index(s, " ")
	r := s[space+3:]

	return Bot{
		pos: Position{
			x: cdel.GetInt(0),
			y: cdel.GetInt(1),
			z: cdel.GetInt(2),
		},
		r: lib.StringToInt(r),
	}
}

func fs2(input io.Reader) int {
	scanner := bufio.NewScanner(input)
	var bots []Bot

	minX := math.MaxInt
	minY := math.MaxInt
	minZ := math.MaxInt
	maxX := math.MinInt
	maxY := math.MinInt
	maxZ := math.MinInt
	for scanner.Scan() {
		line := scanner.Text()
		bot := toBot(line)
		bots = append(bots, bot)
		minX = lib.Min(minX, bot.pos.x-bot.r)
		minY = lib.Min(minY, bot.pos.y-bot.r)
		minZ = lib.Min(minZ, bot.pos.z-bot.r)
		maxX = lib.Max(maxX, bot.pos.x+bot.r)
		maxY = lib.Max(maxY, bot.pos.y+bot.r)
		maxZ = lib.Max(maxZ, bot.pos.z+bot.r)
	}

	var best Position
	max := 0
	div := 1_000_000
	for x := minX / div; x < maxX/div; x++ {
		fmt.Println(x)
		for y := minY / div; y < maxY/div; y++ {
			for z := minZ / div; z < maxZ/div; z++ {
				pos := Position{x, y, z}
				inRange := sumInRangeDiv(pos, bots, div)
				if inRange > max {
					fmt.Println(inRange)
					max = inRange
					best = pos
				}
			}
		}
	}

	div /= 10
	best = Position{12, 30, 42}
	for ; div > 0; div /= 10 {
		max = 0
		minX = (


);
	return (-1);
}

/*====================================================================*
 *
 *   signed write_gbl_reg (struct memmap *memmap, uint32_t address, uint8_t upper, uint16_t data, uint16_t mask);
 *
 *
 *
 *--------------------------------------------------------------------*/

static signed write_gbl_reg (struct memmap * memmap, uint32_t address, uint8_t upper, uint16_t data, uint16_t mask)

{
	unsigned i;
	for (i = 0; i < memmap->used; ++i)
	{
		if (memmap->reg [i].type != GBL_REGISTER)
		{
			continue;
		}
		if (memmap->reg [i].address != address)
		{
			continue;
		}
		if (upper)
		{
			memmap->reg [i].content &= (mask << 16) | 0x0000FFFF;
			memmap->reg [i].content |= (mask & data) << 16;
		}
		else
		{
			memmap->reg [i].content &= mask | 0xFFFF0000;
			memmap->reg [i].content |= mask & data;
		}
		return (0);
	}
	if (memmap->used < memmap->size)
	{
		memmap->reg [i].address = address;
		memmap->reg [i].content = mask & data;
		if (upper)
		{
			memmap->reg [i].content <<= 16;
		}
		memmap->reg [i].type = GBL_REGISTER;
		memmap->used++;
		return (0);
	}
	error (1, 0, "not enough registers to run simulation");
	return (-1);
}

#if 0

/*====================================================================*
 *
 *   signed read_phy_reg (struct memmap * memmap, uint8_t phy, uint8_t reg, uint32_t * data);
 *
 *
 *
 *--------------------------------------------------------------------*/

static signed read_phy_reg (struct memmap * memmap, uint8_t phy, uint8_t reg, uint32_t * data)

{
	unsigned i;
	for (i = 0; i < memmap->used; ++i)
	{
		if (memmap->reg [i].type != PHY_REGISTER)
		{
			continue;
		}
		if (memmap->reg [i].phy != phy)
		{
			continue;
		}
		if (memmap->reg [i].reg != reg)
		{
			continue;
		}
		*data = memmap->reg [i].content;
		return (0);
	}
	return (-1);
}

/*====================================================================*
 *
 *   signed read_gbl_reg (struct memmap * memmap, uint32_t address, uint32_t * content);
 *
 *
 *
 *--------------------------------------------------------------------*/

static signed read_gbl_reg (struct memmap * memmap, uint32_t address, uint32_t * content)

{
	unsigned i;
	for (i = 0; i < memmap->used; ++i)
	{
		if (memmap->reg [i].type != GBL_REGISTER)
		{
			continue;
		}
		if (memmap->reg [i].address != address)
		{
			continue;
		}
		* content = memmap->reg [i].content;
		return (0);
	}
	return (-1);
}

#endif

/*====================================================================*
 *
 *   void print_memmap (struct memmap *memmap);
 *
 *
 *
 *--------------------------------------------------------------------*/

static void print_memmap (struct memmap * memmap)

{
	unsigned i;
	for (i = 0; i &


_type) {
            // Replaces the original logic completely.
            return tot::party_mario::MakeSelectWeaponTable(
                battleWork, table_type);
        });

    // Hook to disable moves under special circumstances.
    g__btlcmd_UpdateSelectWeaponTable_trampoline = mod::hookFunction(
        ttyd::battle_seq_command::_btlcmd_UpdateSelectWeaponTable, [](
            BattleWork* battleWork, int32_t table_type) {
            // Run original logic.
            g__btlcmd_UpdateSelectWeaponTable_trampoline(battleWork, table_type);

            ttyd::battle::BattleWorkCommandCursor* cursor;
            ttyd::battle_seq_command::_btlcmd_GetCursorPtr(
                &battleWork->command_work, table_type, &cursor);
            if (!cursor) return;
            // Run extra logic to disable moves under special circumstances.
            for (int32_t i = 0; i < cursor->num_options; ++i) {
                auto& weapon = battleWork->command_work.weapon_table[i];
                if (!weapon.weapon || weapon.item_id) continue;
                switch (weapon.index) {
                    case MoveType::VIVIAN_INFATUATE: {
                        // Disable if there is already an Infatuated enemy.
                        bool disable = false;
                        for (int32_t i = 0; i < 64; ++i) {
                            auto* unit = battleWork->battle_units[i];
                            if (unit &&
                                unit->current_kind <= BattleUnitType::BONETAIL &&
                                unit->alliance == 0 && unit->current_hp > 0) {
                                disable = true;
                                break;
                            }
                        }
                        if (disable) {
                            weapon.unk_04 = 0;
                            weapon.unk_18 = 10;
                        }
                        break;
                    }
                    case MoveType::BOBBERY_MEGATON_BOMB: {
                        // Disable if there is already an active Megaton Bomb.
                        bool disable = false;
                        for (int32_t i = 0; i < 64; ++i) {
                            auto* unit = battleWork->battle_units[i];
                            if (unit &&
                                unit->current_kind == BattleUnitType::BOMB_SQUAD_BOMB &&
                                unit->unit_work[2] == 2) {
                                disable = true;
                                break;
                            }
                        }
                        if (disable) {
                            weapon.unk_04 = 0;
                            weapon.unk_18 = 11;
                        }
                        break;
                    }
                }
            }
        });

    // Handle additional "can't select move" message types.
    g_BattleSeqCmd_get_msg_trampoline = mod::hookFunction(
        ttyd::battle_seq_command::BattleSeqCmd_get_msg,
        [](EvtEntry* evt, bool isFirstCall) {
            // Check for new message types.
            auto* battleWork = ttyd::battle::g_BattleWork;
            switch (battleWork->command_work.selection_error_msg) {
                case 10:
                    evtSetValue(
                        evt, evt->evtArguments[0], PTR("tot_selerr_infatuate"));
                    return 2;
                case 11:
                    evtSetValue(
                        evt, evt->evtArguments[0], PTR("tot_selerr_megaton_bomb"));
                    return 2;
            }
            // Run vanilla logic.
            return g_BattleSeqCmd_get_msg_trampoline(evt, i


background-image:-o-linear-gradient(top,#00796b 0,#26a69a 100%);background-image:linear-gradient(to bottom,#00796b 0,#26a69a 100%);background-repeat:repeat-x}.bootstrap-switch .bootstrap-switch-container .bootstrap-switch-handle-off.bootstrap-switch-yellow,.bootstrap-switch .bootstrap-switch-container .bootstrap-switch-handle-on.bootstrap-switch-yellow{background-image:-webkit-gradient(linear,left top,left bottom,from(#fbc02d),to(#ffee58));background-image:-webkit-linear-gradient(top,#fbc02d 0,#ffee58 100%);background-image:-moz-linear-gradient(top,#fbc02d 0,#ffee58 100%);background-image:-o-linear-gradient(top,#fbc02d 0,#ffee58 100%);background-image:linear-gradient(to bottom,#fbc02d 0,#ffee58 100%);background-repeat:repeat-x}.bootstrap-switch .bootstrap-switch-container .bootstrap-switch-handle-off.bootstrap-switch-amber,.bootstrap-switch .bootstrap-switch-container .bootstrap-switch-handle-on.bootstrap-switch-amber{background-image:-webkit-gradient(linear,left top,left bottom,from(#ffa000),to(#ffca28));background-image:-webkit-linear-gradient(top,#ffa000 0,#ffca28 100%);background-image:-moz-linear-gradient(top,#ffa000 0,#ffca28 100%);background-image:-o-linear-gradient(top,#ffa000 0,#ffca28 100%);background-image:linear-gradient(to bottom,#ffa000 0,#ffca28 100%);background-repeat:repeat-x}.bootstrap-switch .bootstrap-switch-container .bootstrap-switch-handle-off.bootstrap-switch-blue-grey,.bootstrap-switch .bootstrap-switch-container .bootstrap-switch-handle-on.bootstrap-switch-blue-grey{background-image:-webkit-gradient(linear,left top,left bottom,from(#455a64),to(#78909c));background-image:-webkit-linear-gradient(top,#455a64 0,#78909c 100%);background-image:-moz-linear-gradient(top,#455a64 0,#78909c 100%);background-image:-o-linear-gradient(top,#455a64 0,#78909c 100%);background-image:linear-gradient(to bottom,#455a64 0,#78909c 100%);background-repeat:repeat-x}.bootstrap-switch .bootstrap-switch-container .bootstrap-switch-handle-off.bootstrap-switch-grey-blue,.bootstrap-switch .bootstrap-switch-container .bootstrap-switch-handle-on.bootstrap-switch-grey-blue{background-image:-webkit-gradient(linear,left top,left bottom,from(#2c303b),to(#78909c));background-image:-webkit-linear-gradient(top,#2c303b 0,#78909c 100%);background-image:-moz-linear-gradient(top,#2c303b 0,#78909c 100%);background-image:-o-linear-gradient(top,#2c303b 0,#78909c 100%);background-image:linear-gradient(to bottom,#2c303b 0,#78909c 100%);background-repeat:repeat-x}/*=========================================================================================
    File Name: vertical-menu.scss
    Description: A calssic vertical style menu with expand and collops support. It support
    light & dark version, filpped layout, right side icons, native scroll and borders menu
    item seperation.
    ----------------------------------------------------------------------------------------
    Item Name: Chameleon Admin - Modern Bootstrap 4 WebApp & Dashboard HTML Template + UI Kit
    Version: 1.0
    Author: ThemeSelection
    Author URL: https://themeselection.com/
==========================================================================================*/
@media (min-width: 576px)
{
    body.vertical-layout.vertical-menu.menu-flipped .main-menu


}

.valign {
  display: table;
  width: 100%;
}

.valign > div, .valign > article, .valign > section, .valign > figure {
  display: table-cell;
  vertical-align: middle;
}

/* Mobile */
@media only screen and (max-width: 767px) {
  body {
    -webkit-text-size-adjust: none;
    -ms-text-size-adjust: none;
    width: 100%;
    min-width: 0;
  }
  .container {
    min-width: 0;
    margin-left: 0;
    margin-right: 0;
  }
  .row {
    width: 100%;
    min-width: 0;
    margin-left: 0;
    margin-right: 0;
  }
  .row .row .column, .row .row .columns {
    padding: 0;
  }
  .row .centered {
    margin-left: 0 !important;
  }
  .column, .columns {
    width: auto !important;
    float: none;
    margin-left: 0;
    margin-right: 0;
  }
  .column:last-child, .columns:last-child {
    margin-right: 0;
    float: none;
  }
  [class*="column"] + [class*="column"]:last-child {
    float: none;
  }
  [class*="column"]:before {
    display: table;
  }
  [class*="column"]:after {
    display: table;
    clear: both;
  }
  [class^="push_"],
  [class*="push_"],
  [class^="pull_"],
  [class*="pull_"] {
    margin-left: 0 !important;
  }
}

/*=====================================================
Navigation (with dropdowns)
======================================================*/
.navbar {
  width: 100%;
  min-height: 60px;
  display: block;
  margin-bottom: 20px;
  background: #4a4d50;
  position: relative;
}

@media only screen and (max-width: 767px) {
  .navbar {
    border: none;
  }
  .navbar .column, .navbar .columns {
    min-height: 0;
  }
}

.navbar.fixed {
  position: fixed;
  z-index: 99999;
}

.navbar.pinned {
  position: absolute;
}

.navbar a.toggle {
  display: none;
}

@media only screen and (max-width: 767px) {
  .navbar a.toggle {
    top: 18%;
    right: 4%;
    width: 46px;
    position: absolute;
    text-align: center;
    display: inline-block;
    color: white;
    background: #4a4d50;
    height: 40px;
    line-height: 38px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    -ms-border-radius: 4px;
    -o-border-radius: 4px;
    border-radius: 4px;
    font-size: 30px;
    font-size: 1.875rem;
  }
  .navbar a.toggle:hover {
    background: #565a5d;
  }
  .navbar a.toggle:active, .navbar a.toggle.active {
    background: #3e4043;
  }
}

.navbar .logo {
  display: inline-block;
  margin: 0 2.08333% 0 0;
  padding: 0;
  height: 60px;
  line-height: 58px;
}

.navbar .logo a {
  display: block;
  padding: 0;
  overflow: hidden;


6,r5,1
	beq	.Lcopy_finish

srcnr;	lbz	r6,0(r3)
	sldi	r9,r6,8			/* Pad the byte out to 16 bits */
	adde	r0,r0,r9
dstnr;	stb	r6,0(r4)

.Lcopy_finish:
	addze	r0,r0			/* add in final carry */
	rldicl	r4,r0,32,0		/* fold two 32 bit halves together */
	add	r3,r4,r0
	srdi	r3,r3,32
	blr

.Lsrc_error:
	ld	r14,STK_REG(R14)(r1)
	ld	r15,STK_REG(R15)(r1)
	ld	r16,STK_REG(R16)(r1)
	addi	r1,r1,STACKFRAMESIZE
.Lsrc_error_nr:
	cmpdi	0,r7,0
	beqlr
	li	r6,-EFAULT
	stw	r6,0(r7)
	blr

.Ldest_error:
	ld	r14,STK_REG(R14)(r1)
	ld	r15,STK_REG(R15)(r1)
	ld	r16,STK_REG(R16)(r1)
	addi	r1,r1,STACKFRAMESIZE
.Ldest_error_nr:
	cmpdi	0,r8,0
	beqlr
	li	r6,-EFAULT
	stw	r6,0(r8)
	blr


: var(--jp-inverse-layout-color0);
  padding: var(--jp-private-code-span-padding) 0;
}

.jp-RenderedText pre .ansi-bold {
  font-weight: bold;
}

.jp-RenderedText pre .ansi-underline {
  text-decoration: underline;
}

.jp-RenderedText[data-mime-type='application/vnd.jupyter.stderr'] {
  background: var(--jp-rendermime-error-background);
  padding-top: var(--jp-code-padding);
}

/*-----------------------------------------------------------------------------
| RenderedLatex
|----------------------------------------------------------------------------*/

.jp-RenderedLatex {
  color: var(--jp-content-font-color1);
  font-size: var(--jp-content-font-size1);
  line-height: var(--jp-content-line-height);
}

/* Left-justify outputs.*/
.jp-OutputArea-output.jp-RenderedLatex {
  padding: var(--jp-code-padding);
  text-align: left;
}

/*-----------------------------------------------------------------------------
| RenderedHTML
|----------------------------------------------------------------------------*/

.jp-RenderedHTMLCommon {
  color: var(--jp-content-font-color1);
  font-family: var(--jp-content-font-family);
  font-size: var(--jp-content-font-size1);
  line-height: var(--jp-content-line-height);

  /* Give a bit more R padding on Markdown text to keep line lengths reasonable */
  padding-right: 20px;
}

.jp-RenderedHTMLCommon em {
  font-style: italic;
}

.jp-RenderedHTMLCommon strong {
  font-weight: bold;
}

.jp-RenderedHTMLCommon u {
  text-decoration: underline;
}

.jp-RenderedHTMLCommon a:link {
  text-decoration: none;
  color: var(--jp-content-link-color);
}

.jp-RenderedHTMLCommon a:hover {
  text-decoration: underline;
  color: var(--jp-content-link-color);
}

.jp-RenderedHTMLCommon a:visited {
  text-decoration: none;
  color: var(--jp-content-link-color);
}

/* Headings */

.jp-RenderedHTMLCommon h1,
.jp-RenderedHTMLCommon h2,
.jp-RenderedHTMLCommon h3,
.jp-RenderedHTMLCommon h4,
.jp-RenderedHTMLCommon h5,
.jp-RenderedHTMLCommon h6 {
  line-height: var(--jp-content-heading-line-height);
  font-weight: var(--jp-content-heading-font-weight);
  font-style: normal;
  margin: var(--jp-content-heading-margin-top) 0
    var(--jp-content-heading-margin-bottom) 0;
}

.jp-RenderedHTMLCommon h1:first-child,
.jp-RenderedHTMLCommon h2:first-child,
.jp-RenderedHTMLCommon h3:first-child,
.jp-RenderedHTMLCommon h4:first-child,
.jp-RenderedHTMLCommon h5:first-child,
.jp-RenderedHTMLCommon h6:first-child {
  margin-top: calc(0.5 * var(--jp-content-heading-margin-top));
}

.jp-RenderedHTMLCommon h1:last-child,
.jp-RenderedHTMLCommon h2:last-child,
.jp-RenderedHTMLCommon h3:last-child,
.jp-RenderedHTMLCommon h4:last-child,
.jp-RenderedHTMLCommon h5:last-child,
.jp-RenderedHTMLCom


 {
	gdao.Table[Timoffline]

	ID      *base.Field[Timoffline]
	UUID      *base.Field[Timoffline]
	CHATID      *base.Field[Timoffline]
	STANZA      *base.Field[Timoffline]
	MID      *base.Field[Timoffline]
	TIMESERIES      *base.Field[Timoffline]
	_ID      *int64
	_UUID      *int64
	_CHATID      []byte
	_STANZA      []byte
	_MID      *int64
	_TIMESERIES      *int64
}

var _Timoffline_ID = &base.Field[Timoffline]{"id"}
var _Timoffline_UUID = &base.Field[Timoffline]{"uuid"}
var _Timoffline_CHATID = &base.Field[Timoffline]{"chatid"}
var _Timoffline_STANZA = &base.Field[Timoffline]{"stanza"}
var _Timoffline_MID = &base.Field[Timoffline]{"mid"}
var _Timoffline_TIMESERIES = &base.Field[Timoffline]{"timeseries"}

func (u *Timoffline) GetId() (_r int64){
	if u._ID != nil {
		_r = *u._ID
	}
	return
}

func (u *Timoffline) SetId(arg int64) *Timoffline{
	u.Put0(u.ID.FieldName, arg)
	u._ID = &arg
	return u
}

func (u *Timoffline) GetUuid() (_r int64){
	if u._UUID != nil {
		_r = *u._UUID
	}
	return
}

func (u *Timoffline) SetUuid(arg int64) *Timoffline{
	u.Put0(u.UUID.FieldName, arg)
	u._UUID = &arg
	return u
}

func (u *Timoffline) GetChatid() (_r []byte){
	_r = u._CHATID
	return
}

func (u *Timoffline) SetChatid(arg []byte) *Timoffline{
	u.Put0(u.CHATID.FieldName, arg)
	u._CHATID = arg
	return u
}

func (u *Timoffline) GetStanza() (_r []byte){
	_r = u._STANZA
	return
}

func (u *Timoffline) SetStanza(arg []byte) *Timoffline{
	u.Put0(u.STANZA.FieldName, arg)
	u._STANZA = arg
	return u
}

func (u *Timoffline) GetMid() (_r int64){
	if u._MID != nil {
		_r = *u._MID
	}
	return
}

func (u *Timoffline) SetMid(arg int64) *Timoffline{
	u.Put0(u.MID.FieldName, arg)
	u._MID = &arg
	return u
}

func (u *Timoffline) GetTimeseries() (_r int64){
	if u._TIMESERIES != nil {
		_r = *u._TIMESERIES
	}
	return
}

func (u *Timoffline) SetTimeseries(arg int64) *Timoffline{
	u.Put0(u.TIMESERIES.FieldName, arg)
	u._TIMESERIES = &arg
	return u
}

func (u *Timoffline) Scan(fieldname string, value any) {
	switch fieldname {
	case "id":
		u.SetId(base.AsInt64(value))
	case "uuid":
		u.SetUuid(base.AsInt64(value))
	case "chatid":
		u.SetChatid(base.AsBytes(value))
	case "stanza":
		u.SetStanza(base.AsBytes(value))
	case "mid":
		u.SetMid(base.AsInt64(value))
	case "tim


local JOBTYPE = require "game.raws.job_types"
local dbm = require "game.economy.diet-breadth-model"

---@class (exact) ProductionMethod
---@field __index ProductionMethod
---@field name string
---@field icon string
---@field description string
---@field r number
---@field g number
---@field b number
---@field jobs table<Job, number>
---@field job_weight number
---@field job_type JOBTYPE
---@field total_jobs fun(self:ProductionMethod):number
---@field inputs table<TradeGoodUseCaseReference, number>
---@field outputs table<TradeGoodReference, number>
---@field new fun(self:ProductionMethod, o:ProductionMethod):ProductionMethod
---@field foraging boolean If true, worktime counts towards the foragers count
---@field hydration boolean If true, worktime counts towards the foragers_water count
---@field nature_yield_dependence number How much does the local flora and fauna impact this buildings yield? Defaults to 0
---@field forest_dependence number Set to 1 if building consumes local forests
---@field crop boolean If true, the building will periodically change its yield for a season.
---@field temperature_ideal_min number
---@field temperature_ideal_max number
---@field temperature_extreme_min number
---@field temperature_extreme_max number
---@field rainfall_ideal_min number
---@field rainfall_ideal_max number
---@field rainfall_extreme_min number
---@field rainfall_extreme_max number
---@field clay_ideal_min number
---@field clay_ideal_max number
---@field clay_extreme_min number
---@field clay_extreme_max number
---@field get_efficiency fun(self:ProductionMethod, province:Province):number Returns a fraction describing efficiency on a given province (used for crops and gathering and such)

---@class ProductionMethod
local ProductionMethod = {}
ProductionMethod.__index = ProductionMethod
---Creates a new production method
---@param o ProductionMethod
---@return ProductionMethod
function ProductionMethod:new(o)
	if RAWS_MANAGER.do_logging then
		print("ProductionMethod: " .. o.name)
	end
	---@type ProductionMethod
	local r = {}

	r.name = "<production method>"
	r.icon = 'uncertainty.png'
	r.description = "<production method description>"
	r.r = 0
	r.g = 0
	r.b = 0
	r.jobs = {}
	r.inputs = {}
	r.outputs = {}
	r.job_weight = 1
	r.foraging = false
	r.nature_yield_dependence = 0
	r.forest_dependence = 0
	r.crop = false
	r.temperature_ideal_min = 10
	r.temperature_ideal_max = 30
	r.temperature_extreme_min = 0
	r.temperature_extreme_max = 50
	r.rainfall_ideal_min = 50
	r.rainfall_ideal_max = 100
	r.rainfall_extreme_min = 5
	r.rainfall_extreme_max = 350
	r.clay_ideal_min = 0
	r.clay_ideal_max = 1
	r.clay_extreme_min = 0
	r.clay_extreme_max = 1
	r.job_type = JOBTYPE.FORAGER

	for k, v in pairs(o) do
		r[k] = v
	end
	setmetatable(r, ProductionMethod)
	if RAWS_MANAGER.production_methods_by_name[r.name] ~= nil then
		local msg = "Failed to load a production method (" .. tostring(r.name) .. ")"
		print(msg)
		error(msg)
	end
	RAWS_MANAGER.production_methods_by_name[r.name] = r
	return r
end

---@return number


));
    doc.add(new FacetField("Publish Date", "2010", "10", "15"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("Author", "Lisa"));
    doc.add(new FacetField("Publish Date", "2010", "10", "20"));
    writer.addDocument(config.build(taxoWriter, doc));

    writer.commit();

    // 2nd segment has no Author:
    doc = new Document();
    doc.add(new FacetField("Foobar", "Lisa"));
    doc.add(new FacetField("Publish Date", "2012", "1", "1"));
    writer.addDocument(config.build(taxoWriter, doc));

    // NRT open
    IndexSearcher searcher = getNewSearcher(writer.getReader());

    // System.out.println("searcher=" + searcher);

    // NRT open
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);

    DrillDownQuery ddq = new DrillDownQuery(config);
    ddq.add("Author", "Lisa");
    DrillSidewaysResult r = getNewDrillSideways(searcher, config, taxoReader).search(null, ddq, 10);

    assertEquals(1, r.hits.totalHits.value());
    // Publish Date is only drill-down, and Lisa published
    // one in 2012 and one in 2010:
    assertEquals(
        "dim=Publish Date path=[] value=1 childCount=1\n  2010 (1)\n",
        r.facets.getTopChildren(10, "Publish Date").toString());
    // Author is drill-sideways + drill-down: Lisa
    // (drill-down) published once, and Bob
    // published once:
    assertEquals(
        "dim=Author path=[] value=2 childCount=2\n  Bob (1)\n  Lisa (1)\n",
        r.facets.getTopChildren(10, "Author").toString());

    writer.close();
    IOUtils.close(searcher.getIndexReader(), taxoReader, taxoWriter, dir, taxoDir);
  }

  public void testMultipleRequestsPerDim() throws Exception {
    Directory dir = newDirectory();
    Directory taxoDir = newDirectory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);

    // Writes facet ords to a separate directory from the
    // main index:
    DirectoryTaxonomyWriter taxoWriter =
        new DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE);

    FacetsConfig config = new FacetsConfig();
    config.setHierarchical("dim", true);

    Document doc = new Document();
    doc.add(new FacetField("dim", "a", "x"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "a", "y"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "a", "z"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "b"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "c"));
    writer.addDocument(config.build(taxoWriter, doc));

    doc = new Document();
    doc.add(new FacetField("dim", "d"));
    writer.addDocument(config.build(taxoWriter, doc));

    // NRT open
    IndexSearcher searcher = getNewSearcher(writer.getReader());

    // System.out.println("searcher=" + searcher);

    // NRT open
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);

    DrillDownQuery ddq = new DrillDownQuery(config);
    ddq.add("dim", "


            fs = 0;
            fz.ol(ch.aw, (byte)-71);
         }

         if (ni.fk == ch.aw) {
            if (kd.ip == null) {
               kd.ip = ap.ak(gp.gl, hi.gd * -760675889, 1111543422);
            }

            if (2 == kd.ip.aj) {
               throw new IOException();
            }

            if (kd.ip.aj == 1) {
               Socket var27 = (Socket)kd.ip.ae;
               sh var24 = new sh(var27, 40000, 5000);
               var1 = var24;
               in.aj(var24, (byte)60);
               kd.ip = null;
               fz.ol(ch.ak, (byte)-91);
            }
         }

         me var26;
         if (ni.fk == ch.ak) {
            in.ap((byte)104);
            var26 = mj.aw(868015187);
            var26.ak.bo(mv.ap.am * 1270591485, -1922570259);
            in.ak(var26, (short)486);
            in.aw(1799662414);
            var2.am = 0;
            fz.ol(ch.aj, (byte)-53);
         }

         int var28;
         if (ni.fk == ch.aj) {
            if (null != dr.te) {
               dr.te.aa(-1444050856);
            }

            if (((sw)var1).aw(1, (byte)-81)) {
               var28 = ((sw)var1).aj((byte)94);
               if (null != dr.te) {
                  dr.te.aa(-1218835737);
               }

               if (0 != var28) {
                  ej.hr(var28, -2091508374);
                  return;
               }

               var2.am = 0;
               fz.ol(ch.ai, (byte)-81);
            }
         }

         if (ch.ai == ni.fk) {
            if (var2.am * -1689308347 < 8) {
               var28 = ((sw)var1).ak((byte)4);
               if (var28 > 8 - var2.am * -1689308347) {
                  var28 = 8 - -1689308347 * var2.am;
               }

               if (var28 > 0) {
                  ((sw)var1).ai(var2.ae, -1689308347 * var2.am, var28, 323495247);
                  var2.am += var28 * -725588083;
               }
            }

            if (var2.am * -1689308347 == 8) {
               var2.am = 0;
               dm.ir = var2.ct((byte)-96) * -2327755559737671011L;
               fz.ol(ch.ay, (byte)-126);
            }
         }

         if (ch.ay == ni.fk) {
            in.ay.am = 0;
            in.ap((byte)98);
            vm var35 = new vm(500);
            int[] var29 = new int[]{me.hm.nextInt(), me.hm.nextInt(), me.hm.nextInt(), me.hm.nextInt()};
            var35.am = 0;
            var35.bo(1, 1415589294);
            var35.bw(var29[0], (byte)97);
            var35.bw(var29[1], (byte)80);
            var35.bw(var29[2], (byte)64);
            var35.bw(var29[3], (byte)111);
            var35.bf(8034133433281893301L * dm.ir);
            if (40 == da * -1869319151) {
               var35.bw(hl[0], (byte)58);
               var35.bw(hl[1], (byte)103);
               var35.bw(hl[


ips data"
    task :import => :environment do
      puts "start import ip txt file."

      total_count = 0
      file = "#{Rails.root}/tmp/cn88.net.ip20150305.txt"
      File.readlines(file).each_with_index do |line, index|

        if line.present?
          data = line.split(' ')
          if QqwryIp.build_qqwry_ip(data[0], data[1], data[2], data[3])
            total_count += 1
            puts "success line: #{index}, start_ip: #{data[0]}, end_ip: #{data[1]}"
          end
        end

        if index % 2000 == 0
          sleep(1)
        end

      end

      puts "finished, total_count: #{total_count}"
      puts "end import ip txt file."
    end

  end

  模型 QqwryIp 中计算 IP 对应的 Long 整形数值的方法：

  def build_qqwry_ip(start_ip, end_ip, country, location)
    create(start_long: ip2long(start_ip),
      end_long: ip2long(end_ip),
      country: country,
      location: location,
      start_ip: start_ip,
      end_ip: end_ip)
  end

  def ip2long(value)
    long = 0
    value.split(/\./).each_with_index do |b, i|
      long += b.to_i << 8*(3-i)
    end
    long
  end

3. 获取客户端请求的 IP

  由于项目的架构为： Nginx，Unicorn，Grape，为了在 Grape API 中，顺利取得客户端请求携带的 IP 数据。

  需要对 Nginx 做如下的配置：

    server {
       listen 80;
       client_max_body_size 10m;
       keepalive_timeout 5;
       server_name www.servername.com;
       root /path/tibet/public;

       location / {
          proxy_buffering    on;
          proxy_set_header  X-Forwarded-Host $host;
          proxy_set_header  X-Forwarded-Server $host;
          proxy_set_header  X-Real-IP        $remote_addr;
          proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
          proxy_set_header  Host             $host;
          proxy_redirect    off;
          proxy_pass        http://127.0.0.1:3000;
       }
    }

  Grape API 获取客户端请求的 IP 代码：
  <pre class="prettyprint lang-h


content",title:"MDN Reference page"},{url:"http://www.w3.org/TR/filter-effects/",title:"Filter Effects draft"}],categories:["SVG"],stats:{ie:{5.5:"n",6:"n",7:"n",8:"n",9:"a",10:"a",11:"a",TP:"y"},firefox:{2:"n",3:"a",3.5:"y",3.6:"y",4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y",28:"y",29:"y",30:"y",31:"y",32:"y",33:"y",34:"y",35:"y",36:"y",37:"y",38:"y",39:"y",40:"y"},chrome:{4:"a",5:"a",6:"a",7:"a",8:"a",9:"a",10:"a",11:"a",12:"a",13:"a",14:"a",15:"a",16:"a",17:"a",18:"a",19:"a",20:"a",21:"a",22:"a",23:"a",24:"a",25:"a",26:"a",27:"a",28:"a",29:"a",30:"a",31:"a",32:"a",33:"a",34:"a",35:"a",36:"a",37:"a",38:"a",39:"a",40:"a",41:"a",42:"a",43:"a",44:"a"},safari:{3.1:"n",3.2:"n",4:"a",5:"a",5.1:"a",6:"a",6.1:"a",7:"a",7.1:"a",8:"a"},opera:{9:"a","9.5-9.6":"a","10.0-10.1":"a",10.5:"a",10.6:"a",11:"a",11.1:"a",11.5:"a",11.6:"a",12:"a",12.1:"a",15:"a",16:"a",17:"a",18:"a",19:"a",20:"a",21:"a",22:"a",23:"a",24:"a",25:"a",26:"a",27:"a",28:"a",29:"a"},ios_saf:{3.2:"a","4.0-4.1":"a","4.2-4.3":"a","5.0-5.1":"a","6.0-6.1":"a","7.0-7.1":"a",8:"a","8.1-8.3":"a"},op_mini:{"5.0-8.0":"n"},android:{2.1:"n",2.2:"n",2.3:"n",3:"n",4:"n",4.1:"n","4.2-4.3":"n",4.4:"a","4.4.3-4.4.4":"a",40:"a"},bb:{7:"n",10:"y"},op_mob:{10:"a",11:"a",11.1:"a",11.5:"a",12:"a",12.1:"a",24:"a"},and_chr:{41:"a"},and_ff:{36:"y"},ie_mob:{10:"n",11:"n"},and_uc:{9.9:"n"}},notes:"Partial support refers to lack of filter support or buggy result from effects. A [CSS Filter Effects](http://www.w3.org/TR/filter-effects/) specification is in the works that would replace this method.",notes_by_num:{},usage_perc_y:12.34,usage_perc_a:71.95,ucprefix:!1,parent:"",keywords:"",ie_id:"",chrome_id:""},"svg-html5":{title:"Inline SVG in HTML5",description:"Method of using SVG tags directly in HTML documents. Requires HTML5 parser.",spec:"https://html


-extra/2.2.0/Result-Extra#mapBoth)
 * - Haskell: [Data.Either.either](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:either)
 */
public inline fun <V, E, U> Result<V, E>.flatMapBoth(
    success: (V) -> Result<U, E>,
    failure: (E) -> Result<U, E>,
): Result<U, E> {
    contract {
        callsInPlace(success, InvocationKind.AT_MOST_ONCE)
        callsInPlace(failure, InvocationKind.AT_MOST_ONCE)
    }

    return when {
        isOk -> success(value)
        else -> failure(error)
    }
}

/**
 * Maps this [Result<V, E>][Result] to [Result<U, F>][Result] by applying either the [success]
 * function if this result [is ok][Result.isOk], or the [failure] function if this result
 * [is an error][Result.isErr].
 *
 * Unlike [mapBoth], [success] and [failure] may either return [U] or [F] respectively.
 *
 * - Haskell: [Data.Bifunctor.Bimap](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Bifunctor.html#v:bimap)
 */
public inline fun <V, E, U, F> Result<V, E>.mapEither(
    success: (V) -> U,
    failure: (E) -> F,
): Result<U, F> {
    contract {
        callsInPlace(success, InvocationKind.AT_MOST_ONCE)
        callsInPlace(failure, InvocationKind.AT_MOST_ONCE)
    }

    return when {
        isOk -> Ok(success(value))
        else -> Err(failure(error))
    }
}

/**
 * Maps this [Result<V, E>][Result] to [Result<U, F>][Result] by applying either the [success]
 * function if this result [is ok][Result.isOk], or the [failure] function if this result
 * [is an error][Result.isErr].
 *
 * Unlike [mapBoth], [success] and [failure] may either return [U] or [F] respectively.
 *
 * - Haskell: [Data.Bifunctor.Bimap](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Bifunctor.html#v:bimap)
 */
public inline fun <V, E, U, F> Result<V, E>.flatMapEither(
    success: (V) -> Result<U, F>,
    failure: (E) -> Result<U, F>,
): Result<U, F> {
    contract {
        callsInPlace(success, InvocationKind.AT_MOST_ONCE)
        callsInPlace(failure, InvocationKind.AT_MOST_ONCE)
    }

    return when {
        isOk -> success(value)
        else -> failure(error)
    }
}

/**
 * Maps this [Result<V, E>][Result] to [Result<V, F>][Result] by either applying the [transform]
 * function to the [error][Result.error] if this result [is an error][Result.isErr], or returning
 * [this].
 *
 * - Elm: [Result.mapError](http://package.elm-lang.org/packages/elm-lang/core/latest/Result#mapError)
 * - Haskell: [Data.Bifunctor.right](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Bifunctor.html#v:second)
 * - Rust: [Result.map_err](https://doc.rust-lang.org/std/result/enum.Result.html#method.map_err)
 */
public inline infix fun <V, E, F> Result<V, E>.mapError(transform: (E) -> F): Result<V, F> {
    contract {
        callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
    }

    return when {
        isErr -> Err


.toList();
  list.replaceRange(start, end, iterable);
  List iterableList = iterable.toList();
  Expect.equals(copy.length + iterableList.length - (end - start), list.length);
  for (int i = 0; i < start; i++) {
    Expect.equals(copy[i], list[i]);
  }
  for (int i = 0; i < iterableList.length; i++) {
    Expect.equals(iterableList[i], list[i + start]);
  }
  int removedLength = end - start;
  for (int i = end; i < copy.length; i++) {
    Expect.equals(copy[i], list[i + iterableList.length - removedLength]);
  }
}

class MyList<T> extends ListBase<T> {
  List list;
  MyList(this.list);
  get length => list.length;
  set length(value) {
    list.length = value;
  }

  operator [](index) => list[index];
  operator []=(index, val) {
    list[index] = val;
  }

  void add(T element) {
    list.add(element);
  }

  toString() => list.toString();
}

main() {
  test([1, 2, 3], 0, 1, [4, 5]);
  test([1, 2, 3], 1, 1, [4, 5]);
  test([1, 2, 3], 2, 3, [4, 5]);
  test([1, 2, 3], 3, 3, [4, 5]);
  test([1, 2, 3], 0, 3, [4, 5]);
  test([1, 2, 3], 2, 3, [4]);
  test([1, 2, 3], 0, 3, []);
  test([1, 2, 3], 0, 1, [4, 5].map((x) => x));
  test([1, 2, 3], 1, 1, [4, 5].map((x) => x));
  test([1, 2, 3], 2, 3, [4, 5].map((x) => x));
  test([1, 2, 3], 3, 3, [4, 5].map((x) => x));
  test([1, 2, 3], 0, 3, [4, 5].map((x) => x));
  test([1, 2, 3], 2, 3, [4].map((x) => x));
  test([1, 2, 3], 0, 3, [].map((x) => x));
  test([1, 2, 3], 0, 1, const [4, 5]);
  test([1, 2, 3], 1, 1, const [4, 5]);
  test([1, 2, 3], 2, 3, const [4, 5]);
  test([1, 2, 3], 3, 3, const [4, 5]);
  test([1, 2, 3], 0, 3, const [4, 5]);
  test([1, 2, 3], 2, 3, const [4]);
  test([1, 2, 3], 0, 3, const []);
  test([1, 2, 3], 0, 1, new Iterable.generate(2, (x) => x + 4));
  test([1, 2, 3], 1, 1, new Iterable.generate(2, (x) => x + 4));
  test([1, 2, 3], 2, 3, new Iterable.generate(2, (x) => x + 4));
  test([1, 2, 3], 3, 3, new Iterable.generate(2, (x) => x + 4));
  test([1, 2, 3], 0, 3, new Iterable.generate(2, (x) => x + 4));
  test([1, 2, 3], 2, 3, new Iterable.generate(2, (x) => x + 4));
  test(new MyList([1, 2, 3]), 0, 1, [4, 5]);
  test(new MyList([1, 2, 3]), 1, 1, [4, 5]);
  test(new MyList([1, 2, 3]), 2, 3, [4, 5]);
  test(new MyList(


.iff1;
        regs.iff2 = this.iff2;
        regs.im = this.im;
        regs.halted = this.halted;

        return regs;
    }
}

/**
 * All real fields of RegisterSet, for enumeration.
 */
export const registerSetFields: Register[] = [
    "af", "bc", "de", "hl",
    "afPrime", "bcPrime", "dePrime", "hlPrime",
    "ix", "iy", "sp", "pc",
    "memptr", "i", "r", "iff1", "iff2", "im", "halted"];
import { Request, Response } from 'express';
import db from "../../models"

export async function update(req: Request, res: Response) {
    const { firstName, lastName, email } = req.body;

    var user = []
    console.log(email)
    if (email) {
        try {
            user = await db.User.update({firstName:firstName,lastName:lastName},{
                where: { email: email }
            });
            if(user[0]===0){
                res.send('email does not exist')
            } else {
                res.send('user updated')
            }
        } catch (error) {
            res.send(error)
        }
    } else res.send('email missing')

    res.status(500).send('Something broke!');
}
import { Controller } from '../../Decorators/Controller';
import { Get, Post, Patch, Put, Delete } from '../../Decorators/methods';
import { Request, Response } from 'express';

@Controller('/user')
export default class UserController {
  @Get('/')
  public index(_req: Request, res: Response) {
    return res.send('User overview');
  }

  @Post('/new')
  public setUser(req: Request, res: Response) {
    return res.send(`You are registering a new user: ${JSON.stringify(req.body)}`);
  }

  @Patch('/update/:id')
  public updateUser(req: Request, res: Response) {
    return res.send(`You are updating a user ${req.params.id}`);
  }

  @Put('/replace/:id')
  public replaceUser(req: Request, res: Response) {
    return res.send(`You are replacing user ${req.params.id}`);
  }

  @Delete('/delete/:id')
  public removeUser(req: Request, res: Response) {
    return res.send(`You are removing at the profile of ${req.params.id}`);
  }
}

/**
 * Counting sort algorithm is efficient when range of data to be sorted is fixed like sort string consisting of ASCII characters
 * linear time sorting algorithm
 * @paradiam: Divide and Conquer
 */
export default class CountingSort{

  /**
   * TimeComplexity:  O(n+k)
   * Auxiliary Space: O(n+k)
   * @static
   * @param {number[]} arr
   * @memberof CountingSort
   */
  public static sort(arr: number[]) {
    const max = Math.max(...arr);
    const counts = new Array(max + 1).fill(0);
    // store counts of each number
    for (let i = 0; i < arr.length; i++) {
      const number = arr[i];
      counts[number]++;
    }

    // calculate the prefix sums
    for (let i = 1; i <= max; i++) {
      counts[i] += counts[i - 1];
    }

    const sortedArray = new Array(arr.length);

    for (let i = arr.length - 1; i >= 0; i--) {
      const number = arr[i];
      const count = counts[number];
      sortedArray[count - 1] = number;
      counts[number]--;
    }
  }


lda [*.tmp],y
        iny
        tax
        lda [*.tmp],y
        sta .tmp+1
        stx .tmp
        lda font_first_free_tile
        clc
        adc [*.tmp],y   ; Number of tiles used
        sta font_first_free_tile
font_load_exit:
        ;; Turn the screen on
        jsr .display_on
        pla             ; Return font setup in A
        rts

        ; Copy the tiles from the current font into VRAM
font_copy_current::
        ; Find the current font data
        lda font_current+sfont_handle_font
        sta *.tmp
        lda font_current+sfont_handle_font+1
        sta *.tmp+1
        ldy #0
        lda [*.tmp],y
        iny
        pha
        lda [*.tmp],y
        iny
        tax
;
        pla
        pha
        and #3
        cmp #FONT_128ENCODING
        beq 1$
        cmp #FONT_NOENCODING
        beq 2$
        ; 256ENCODING - add #256 to .tmp -> inc .tmp+1
        inc .tmp+1
        jmp 2$
1$:
        ; 128ENCODING - add #128 to y
        tya
        ora #128
        tay
2$:
        tya
        clc
        adc *.tmp
        sta *_set_bkg_data_PARM_3
        sta *_set_bkg_1bpp_data_PARM_3
        lda *.tmp+1
        adc #0
        sta *_set_bkg_data_PARM_3+1
        sta *_set_bkg_1bpp_data_PARM_3+1
        pla
        and #FONT_COMPRESSED
        bne 3$
        lda font_current+sfont_handle_first_tile
        jsr _set_bkg_data
        jsr .display_on
        rts
3$:
        lda font_current+sfont_handle_first_tile
        jsr _set_bkg_1bpp_data
        jsr .display_on
        rts

        ; Set the current font to Y
font_set::
        lda font_table,y
        iny
        sta font_current
        lda font_table,y
        iny
        sta font_current+1
        lda font_table,y
        iny
        sta font_current+2
        dey
        dey
        dey
        rts

        ;; Print a character with interpretation
.put_char::
        ; See if it's a special char
        cmp #.CR
        bne 1$

; Now see if were checking special chars
        lda .mode
        and #.M_NO_INTERP
        bne 2$
        jsr .cr_curs
        rts

2$:
1$:
        jsr .set_char
        jmp .adv_curs

        ;; Print a character without interpretation
.out_char::
        jsr .set_char
        jmp .adv_curs

        ;; Delete a character
.del_char::
        jsr .rew_curs
        lda #.SPACE
        jmp .set_char

        ;; Print the character in A
.set_char:
        pha
        lda font_current+2
        ; Must be non-zero if the font system is setup (cant have a font in page zero)
        bne 3$

        ; Font system is not yet setup - init it and copy in the ibm font
        ; Kind of a compatibility mode
        jsr _font_init

        ; Need all of the tiles
        lda #0
        sta font_first_free_tile
        jsr _font_load_ibm
3$:
; Compute which tile maps to this character
        pla
        pha
        tax
        lda font_current+sfont_handle_font
        sta *.tmp
        lda font_current+sfont_handle_font+1
        sta *.tmp+1
        ldy #0
        lda [*.tmp],y
        and #3
        cmp #FONT_NOENCODING
        beq set_char_no_encoding
        iny


ayers.maghrib),
        '7/12/2015 8:32 PM');

    final tomorrowComponents = DateComponents(2015, 7, 13);
    final tomorrowPrayers = PrayerTimes(coordinates, tomorrowComponents, params,
        utcOffset: newYorkUtcOffset);

    expect(DateFormat.yMd().add_jm().format(tomorrowPrayers.fajr),
        '7/13/2015 4:43 AM');

    /*
     Night: 8:32 PM to 4:43 AM
     Duration: 8 hours, 11 minutes
     Middle = 8:32 PM + 4 hours, 5.5 minutes = 12:37:30 AM which rounds to 12:38 AM
     Last Third = 8:32 PM + 5 hours, 27.3 minutes = 1:59:20 AM which rounds to 1:59 AM
     */
    final sunnahTimes = SunnahTimes(todayPrayers);
    expect(DateFormat.yMd().add_jm().format(sunnahTimes.middleOfTheNight),
        '7/13/2015 12:38 AM');
    expect(DateFormat.yMd().add_jm().format(sunnahTimes.lastThirdOfTheNight),
        '7/13/2015 1:59 AM');
  });
}
import 'dart:math';

import '../coordinates.dart';
import 'double_util.dart';
import 'math.dart';

/// Astronomical equations
class Astronomical {
  /// The geometric mean longitude of the sun in degrees.
  /// @param T the julian century
  /// @return the geometric longitude of the sun in degrees
  static double meanSolarLongitude(double T) {
    /* Equation from Astronomical Algorithms page 163 */
    final term1 = 280.4664567;
    final term2 = 36000.76983 * T;
    final term3 = 0.0003032 * pow(T, 2);
    final L0 = term1 + term2 + term3;
    return DoubleUtil.unwindAngle(L0);
  }

  /// The geometric mean longitude of the moon in degrees
  /// @param T the julian century
  /// @return the geometric mean longitude of the moon in degrees
  static double meanLunarLongitude(double T) {
    /* Equation from Astronomical Algorithms page 144 */
    final term1 = 218.3165;
    final term2 = 481267.8813 * T;
    final Lp = term1 + term2;
    return DoubleUtil.unwindAngle(Lp);
  }

  /// The apparent longitude of the Sun, referred to the true equinox of the date.
  /// @param T the julian century
  /// @param L0 the mean longitude
  /// @return the true equinox of the date
  static double apparentSolarLongitude(double T, double L0) {
    /* Equation from Astronomical Algorithms page 164 */
    final longitude = L0 + solarEquationOfTheCenter(T, meanSolarAnomaly(T));
    final omega = 125.04 - (1934.136 * T);
    final lambda = longitude - 0.00569 - (0.00478 * sin(radians(omega)));
    return DoubleUtil.unwindAngle(lambda);
  }

  /// The ascending lunar node longitude
  /// @param T the julian century
  /// @return the ascending lunar node longitude
  static double ascendingLunarNodeLongitude(double T) {
    /* Equation from Astronomical Algorithms page 144 */
    final term1 = 125.04452;
    final term2 = 1934.136261 * T;
    final term3 = 0.0020708 * pow(T, 2);
    final term4 = pow(T, 3) / 450000;
    final omega = term1 - term2 + term3 + term4;
    return DoubleUtil.unwindAngle(omega);
  }

  /// The mean anomaly of the sun
  /// @param T the julian century


n	ymm3, ymm3, ymm1
	vpcmpeqd	ymm4, ymm0, ymmword ptr [rcx + 4*rsi + 64]
	vpcmpeqd	ymm5, ymm0, ymmword ptr [rcx + 4*rsi + 96]
	vpandn	ymm4, ymm4, ymm1
	vpandn	ymm5, ymm5, ymm1
	vmovdqu	ymmword ptr [r8 + 4*rsi], ymm2
	vmovdqu	ymmword ptr [r8 + 4*rsi + 32], ymm3
	vmovdqu	ymmword ptr [r8 + 4*rsi + 64], ymm4
	vmovdqu	ymmword ptr [r8 + 4*rsi + 96], ymm5
	add	rsi, 32
	cmp	rdx, rsi
	jne	.LBB4_871
# %bb.872:
	cmp	rdx, rax
	je	.LBB4_1351
	jmp	.LBB4_873
.LBB4_877:
	mov	edx, r11d
	and	edx, -32
	xor	esi, esi
	vpxor	xmm0, xmm0, xmm0
	vpcmpeqd	xmm8, xmm8, xmm8
	vbroadcastss	ymm2, dword ptr [rip + .LCPI4_8] # ymm2 = [1,1,1,1,1,1,1,1]
.LBB4_878:                              # =>This Inner Loop Header: Depth=1
	vmovq	xmm3, qword ptr [rcx + rsi]     # xmm3 = mem[0],zero
	vmovq	xmm4, qword ptr [rcx + rsi + 8] # xmm4 = mem[0],zero
	vmovq	xmm5, qword ptr [rcx + rsi + 16] # xmm5 = mem[0],zero
	vmovq	xmm6, qword ptr [rcx + rsi + 24] # xmm6 = mem[0],zero
	vpcmpgtb	xmm7, xmm3, xmm0
	vpmovsxbd	ymm9, xmm7
	vpcmpgtb	xmm1, xmm4, xmm0
	vpmovsxbd	ymm10, xmm1
	vpcmpgtb	xmm7, xmm5, xmm0
	vpmovsxbd	ymm7, xmm7
	vpcmpgtb	xmm1, xmm6, xmm0
	vpmovsxbd	ymm1, xmm1
	vpcmpeqb	xmm3, xmm3, xmm0
	vpxor	xmm3, xmm8, xmm3
	vpmovsxbd	ymm3, xmm3
	vpcmpeqb	xmm4, xmm4, xmm0
	vpxor	xmm4, xmm8, xmm4
	vpmovsxbd	ymm4, xmm4
	vpcmpeqb	xmm5, xmm5, xmm0
	vpxor	xmm5, xmm8, xmm5
	vpmovsxbd	ymm5, xmm5
	vpcmpeqb	xmm6, xmm6, xmm0
	vpxor	xmm6, xmm8, xmm6
	vpmovsxbd	ymm6, xmm6
	vblendvps	ymm3, ymm3, ymm2, ymm9
	vblendvps	ymm4, ymm4, ymm2, ymm10
	vblendvps	ymm5, ymm5, ymm2, ymm7
	vblendvps	ymm1, ymm6, ymm2, ymm1
	vmovups	ymmword ptr [r8 + 4*rsi], ymm3
	vmovups	ymmword ptr [r8 + 4*rsi + 32], ymm4
	vmovups	ymmword ptr [r8 + 4*rsi + 64], ymm5
	vmovups	ymmword ptr [r8 + 4*rsi + 96], ymm1
	add	rsi, 32
	cmp	r


用户：首要且最关键的行动是立即升级您的系统！
1. **立即修补漏洞**

**请火速检查您的Craft CMS版本，确保已升级至以下或更新的安全版本：**

这是抵御此类攻击最直接、最有效的防线。

1. **Craft CMS 3.x: 3.9.15 或更高版本**
1. **Craft CMS 4.x: 4.14.15 或更高版本**
1. **Craft CMS 5.x: 5.6.17 或更高版本**
1. **全面安全排查与加固**
1. **检查Web Shell**
仔细排查服务器Web目录下是否存在未知或可疑的脚本文件（如PHP, ASPX等Web Shell）。

1. **监控异常进程与文件**
留意系统中是否存在名为4l4md4r
、alamdar.so
的异常进程或文件，以及有无XMRig等挖矿特征。

1. **审查关键配置文件**
检查/etc/ld.so.preload
文件内容是否被恶意篡改。

1. **识别恶意脚本特征**
留意可疑Python脚本活动，特别是包含import urllib2 as fbi
这类独特指纹的代码。

1. **强化纵深防御**
1. **部署WAF/IPS**
使用Web应用防火墙（WAF）和入侵防御系统（IPS）拦截已知攻击特征和异常请求。

1. **严格访问控制**
遵循最小权限原则，限制不必要的网络端口和服务暴露。

1. **定期审计与监控**
定期审计服务器日志，监控异常网络连接、系统调用及文件变更。

Mimo组织的持续活跃、快速武器化漏洞的能力及其向勒索软件演进的趋势，对所有互联网服务提供者和用户都构成了严峻挑战。请务必保持高度警惕，迅速行动，修补漏洞，加强防御。

#  微软MSRC榜首赏金猎人带你来挖洞
 迪哥讲事   2025-06-09 12:05

![图片](https://mmbiz.qpic.cn/sz_mmbiz_gif/iaibvmyz4605OWlUh6bZx79ugMpDVGYEp3wDOaKj5EpU4P0n1ZFQgTxJzmfqf0jQn2W7k4E39icj4LTdSYTJfpAgA/640?wx_fmt=gif&tp=webp&wxfrom=5&wx_lazy=1 "")


That(algorithm.doSharding(availableTargetNames, shardingValueAsZonedDateTime).size(), is(expectSize));
        final RangeShardingValue<Comparable<?>> shardingValueAsUtilDate = createShardingValue(
                Date.from(lower.atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(upper.atZone(ZoneId.systemDefault()).toInstant()));
        assertThat(algorithm.doSharding(availableTargetNames, shardingValueAsUtilDate).size(), is(expectSize));
        final RangeShardingValue<Comparable<?>> shardingValueAsSqlDate = createShardingValue(
                new java.sql.Date(lower.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()),
                new java.sql.Date(upper.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
        assertThrows(UnsupportedTemporalTypeException.class, () -> algorithm.doSharding(availableTargetNames, shardingValueAsSqlDate),
                "SQL Date values do not have a time component.");
        assertThat(createAlgorithm("yyyy-MM-dd", "2021-06-01",
                "2021-07-31", "yyyyMMdd", stepAmount, null)
                .doSharding(availableTargetNames, shardingValueAsSqlDate).size(),
                is(expectSize));
        final RangeShardingValue<Comparable<?>> shardingValueAsString = createShardingValue(
                DateTimeFormatterFactory.getDatetimeFormatter().format(lower),
                DateTimeFormatterFactory.getDatetimeFormatter().format(upper));
        assertThat(algorithm.doSharding(availableTargetNames, shardingValueAsString).size(), is(expectSize));
        assertThat(shardingAlgorithmByDay.doSharding(availableTablesForDayDataSources, shardingValueAsString).size(), is(expectSize));
    }

    @Test
    void assertRangeDoShardingByDaysInLocalDate() {
        int stepAmount = 2;
        Collection<String> availableTargetNames = new LinkedList<>();
        for (int j = 6; j <= 7; j++) {
            for (int i = 1; j == 6 ? i <= 30 : i <= 31; i = i + stepAmount) {
                availableTargetNames.add(String.format("t_order_%04d%02d%02d", 2021, j, i));
            }
        }
        Collection<String> actualAsLocalDate = createAlgorithm("yyyy-MM-dd", "2021-06-01",
                "2021-07-31", "yyyyMMdd", stepAmount, null)
                .doSharding(availableTargetNames,
                        createShardingValue(LocalDate.of(2021, 6, 15), LocalDate.of(2021, 7, 31)));
        assertThat(actualAsLocalDate.size(), is(24));
    }

    @Test
    void assertRangeDoShardingByHours() {
        int stepAmount = 2;
        IntervalShardingAlgorithm algorithm = createAlgorithm("HH:mm:ss.SSS", "02:00:00.000",
                "13:00:00.000", "HHmm", stepAmount, "Hours");
        Collection<String> availableTablesForJDBCTimeDataSources = new LinkedList<>();
        for (int i = 2; i < 13; i++) {
            availableTablesForJDBCTimeDataSources.add(String.format("t_order_%02d%02d", i, 0));
        }
        Collection<String> actualAsLocalTime = algorithm.doSharding(availableTablesForJDBCTimeDataSources,
                createShardingValue(LocalTime.of(2, 25, 27), LocalTime.of(12, 25, 27)));
        assertThat(actualAsLocalTime.size(), is(6));
        Collection<String> actualAsOffsetTime = algorithm.doSharding(availableTablesForJDBCTimeDataSources,
                createShardingValue(OffsetTime.of(2, 25, 27, 0, OffsetDateTime.now().getOffset()),
                        OffsetTime.of(12, 25, 27, 0, OffsetDateTime.now().getOffset())));
        assertThat(actualAsOffsetTime.size(), is(6));
    }


.
        @param blockMatchingStep2 Block matching threshold for the second step of BM3D (Wiener filtering),
        i.e. maximum distance for which two blocks are considered similar.
        Value expressed in euclidean distance.
        @param groupSize Maximum size of the 3D group for collaborative filtering.
        @param slidingStep Sliding step to process every next reference block.
        @param beta Kaiser window parameter that affects the sidelobe attenuation of the transform of the
        window. Kaiser window is used in order to reduce border effects. To prevent usage of the window,
        set beta to zero.
        @param normType Norm used to calculate distance between blocks. L2 is slower than L1
        but yields more accurate results.
        @param step Step of BM3D to be executed. Allowed are only BM3D_STEP1 and BM3D_STEPALL.
        BM3D_STEP2 is not allowed as it requires basic estimate to be present.
        @param transformType Type of the orthogonal transform used in collaborative filtering step.
        Currently only Haar transform is supported.

        This function expected to be applied to grayscale images. Advanced usage of this function
        can be manual denoising of colored image in different colorspaces.

        @sa
        fastNlMeansDenoising
        */
        CV_EXPORTS_W void bm3dDenoising(
            InputArray src,
            OutputArray dst,
            float h = 1,
            int templateWindowSize = 4,
            int searchWindowSize = 16,
            int blockMatchingStep1 = 2500,
            int blockMatchingStep2 = 400,
            int groupSize = 8,
            int slidingStep = 1,
            float beta = 2.0f,
            int normType = cv::NORM_L2,
            int step = cv::xphoto::BM3D_STEPALL,
            int transformType = cv::xphoto::HAAR);
        //! @}
    }
}

#endif // __OPENCV_BM3D_IMAGE_DENOISING_HPP__
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html

#ifndef OPENCV_HAL_VSX_UTILS_HPP
#define OPENCV_HAL_VSX_UTILS_HPP

#include "opencv2/core/cvdef.h"

#ifndef SKIP_INCLUDES
#   include <assert.h>
#endif

//! @addtogroup core_utils_vsx
//! @{
#if CV_VSX

#define __VSX_S16__(c, v) (c){v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v}
#define __VSX_S8__(c, v)  (c){v, v, v, v, v, v, v, v}
#define __VSX_S4__(c, v)  (c){v, v, v, v}
#define __VSX_S2__(c, v)  (c){v, v}

typedef __vector unsigned char vec_uchar16;
#define vec_uchar16_set(...) (vec_uchar16){__VA_ARGS__}
#define vec_uchar16_sp(c)    (__VSX_S16__(vec_uchar16, (unsigned char)c))
#define vec_uchar16_c(v)     ((vec_uchar16)(v))
#define vec