      r.getKeyedNodes().put("a", k1);
                r.getKeyedNodesMany().put("a", k1);
                r.getKeyedNodesManyDuplicate().put("a", k1);

                r.getKeyedNodesElementCollection().put("a", new KeyedEmbeddable("a", "b"));

                em.persist(i1);
                em.persist(k1);
                em.persist(r);

                IndexedNode i2 = new IndexedNode(I2_ID);
                em.persist(i2);
                KeyedNode k2 = new KeyedNode(K2_ID);
                em.persist(k2);
                Sub1 sub1 = new Sub1();
                sub1.setNumber(123);
                sub1.setSub1Value(456);
                em.persist(sub1);
                p1Id = sub1.getId();
            }
        });
    }

    @Override
    protected Class<?>[] getEntityClasses() {
        return new Class<?>[]{
            Root.class,
            IndexedNode.class,
            KeyedNode.class,
            KeyedEmbeddable.class,
            IndexedEmbeddable.class,
            Parent.class,
            Sub1.class,
            Sub2.class,
            Sub1Sub1.class,
            Sub1Sub2.class,
            Sub2Sub1.class,
            Sub2Sub2.class
        };
    }

    private Root getRoot(EntityManager em) {
        return cbf.create(em, Root.class)
                .fetch("nodes")
                .fetch("indexedNodes", "indexedNodesMany", "indexedNodesManyDuplicate", "indexedNodesElementCollection")
                .fetch("keyedNodes", "keyedNodesMany", "keyedNodesManyDuplicate", "keyedNodesElementCollection")
                .where("id").eq(1)
                .getResultList()
                .get(0);
    }

    @Test
    public void insertIndexedAccessOtherAttributes() {
        InsertCriteriaBuilder<Root> criteria = cbf.insertCollection(em, Root.class, "indexedNodes");
        try {
            criteria.bind("name");
        } catch (IllegalArgumentException ex) {
            assertTrue(ex.getMessage().contains("The attribute [name] does not exist or can't be bound"));
        }
    }

    @Test
    public void insertNormal() {
        transactional(new TxVoidWork() {
            @Override
            public void work(EntityManager em) {
                InsertCriteriaBuilder<Root> criteria = cbf.insertCollection(em, Root.class, "nodes");
                criteria.fromIdentifiableValues(Sub1.class, "valuesAlias", 1);
                criteria.bind("id").select("1");
                criteria.bind("nodes.id").select("valuesAlias.id");
                criteria.setParameter("valuesAlias", Collections.singletonList(em.getReference(Sub1.class, p1Id)));

                assertEquals("INSERT INTO Root.nodes(id, nodes.id)\n"
                    + "SELECT 1, valuesAlias.id"
                    + " FROM Sub1(1 ID VALUES) valuesAlias", criteria.getQueryString());
                int updated = criteria.executeUpdate();
                Root r = getRoot(em);

                assertEquals(1, updated);
                assertEquals(1, r.getNodes().size());

                assertEquals(p1Id, r.getNodes().iterator().next().getId());
            }
        });
    }

    @Test
    public void insertIndexed() {
        transactional(new TxVoidWork() {
            @Override
            public void work(EntityManager em) {
                InsertCriteriaBuilder<Root> criteria = cbf.insertCollection(em, Root.class, "indexedNodes");
                criteria.fromValues(Integer.class, "valuesAlias", Collections.singletonList(


ingTub(FlatBufferBuilder builder, int Weight) {
    builder.Prep(4, 4);
    builder.PutInt(Weight);
    return new Offset<FallingTub>(builder.Offset);
  }
  public FallingTubT UnPack() {
    var _o = new FallingTubT();
    this.UnPackTo(_o);
    return _o;
  }
  public void UnPackTo(FallingTubT _o) {
    _o.Weight = this.Weight;
  }
  public static Offset<FallingTub> Pack(FlatBufferBuilder builder, FallingTubT _o) {
    if (_o == null) return default(Offset<FallingTub>);
    return CreateFallingTub(
      builder,
      _o.Weight);
  }
}

public class FallingTubT
{
  [Newtonsoft.Json.JsonProperty("weight")]
  public int Weight { get; set; }

  public FallingTubT() {
    this.Weight = 0;
  }
}


 {
    u: f32,
    v: f32,
}

mod std140 {
    pub struct AnyBlock {
        a: f32,
        _p1: [u8; 3 * 4],
        b: Anon,
        _p2: [u8; 2 * 4],
        c: f32,
        _p3: [u8; 3 * 4],
        d: [[f32; 4]; 3],
        // each array member has four byte padding at the end
        e: [[f32; 4]; 3],
        f: f32,
        _p4: [u8; 3 * 4],
    }

    struct Anon {
        u: f32,
        v: f32,
    }
}

mod std430 {

    #[repr(C)]
    pub struct AnyBlock {
        a: f32,
        b: Anon,
        c: f32,
        // d has four byte padding at the end
        d: [f32; 4],
        // each array member has four byte padding at the end
        e: [[f32; 4]; 3],
        f: f32,
        _p: [u8; 3 * 4],
    }

    struct Anon {
        u: f32,
        v: f32,
    }
}

fn main() {
    assert_eq!(std::mem::size_of::<AnyBlock>(), 68);
    assert_eq!(std::mem::size_of::<std140::AnyBlock>(), 160);
    assert_eq!(std::mem::size_of::<std430::AnyBlock>(), 96);
}
use crate::*;
use indexmap::IndexMap;
use bitcoin::{Txid, Script, Block, WScriptHash};
use crate::db::utxo::UtxoEntry;

#[derive(Debug, Clone, PartialEq)]
pub struct UtxoServerValue {
    pub txid: Txid,  // +32 = 32
    pub vout: u32,   // + 4 = 36
}

#[derive(Debug, Clone)]
pub struct UtxoServer {
    db: IndexMap<WScriptHash, Vec<UtxoServerValue>>,
}

impl Default for UtxoServer {
    fn default() -> Self {
        Self::new()
    }
}

impl UtxoServer {
    pub fn new() -> Self {
        Self {
            db: IndexMap::new(),
        }
    }
    pub fn is_empty(&self) -> bool {
        self.db.is_empty()
    }
    pub fn len(&self) -> usize {
        self.db.len()
    }
    pub fn capacity(&self) -> usize {
        self.db.capacity()
    }
    pub fn size(&self) -> usize {
        self.db.iter().map(|(script, value)| script.len() + 36 * value.len()).sum()
    }
    pub fn shrink_to_fit(&mut self) {
        self.db.shrink_to_fit();
    }
    pub fn iter(&self) -> indexmap::map::Iter<WScriptHash, Vec<UtxoServerValue>> {
        self.db.iter()
    }
    pub fn get(&self, script_pubkey: &Script) -> Vec<UtxoServerValue> {
        self.db.get(&script_pubkey.wscript_hash()).map_or_else(Vec::new, |values| (*values).clone())
    }
    pub fn push(&mut self, utxo: &UtxoEntry) {
        let v = UtxoServerValue {
            txid: utxo.txid,
            vout: utxo.vout,
        };
        let wscript_hash = utxo.script_pubkey.wscript_hash();
        match self.db.get_mut(&wscript_hash) {
            Some(values) => values.push(v),
            None => assert!(self.db.insert(wscript_hash, vec![v]).is_none()),
        }
    }
    fn remove(&mut self, script_pubkey: &Script, txid: &Txid, vout: u32) {
        let values = self.db.get_mut(&script_pubkey.wscript_hash()).unwrap();
        *values = values.iter().filter(|&utxo_value| {
            !(utxo_valu


n()
	return s.CSIPluginDenormalizeTxn(txn, ws, plug)
}

func (s *StateStore) CSIPluginDenormalizeTxn(txn Txn, ws memdb.WatchSet, plug *structs.CSIPlugin) (*structs.CSIPlugin, error) {
	if plug == nil {
		return nil, nil
	}

	// Get the unique list of allocation ids
	ids := map[string]struct{}{}
	for _, info := range plug.Controllers {
		ids[info.AllocID] = struct{}{}
	}
	for _, info := range plug.Nodes {
		ids[info.AllocID] = struct{}{}
	}

	for id := range ids {
		alloc, err := s.allocByIDImpl(txn, ws, id)
		if err != nil {
			return nil, err
		}
		if alloc == nil {
			continue
		}
		plug.Allocations = append(plug.Allocations, alloc.Stub(nil))
	}
	sort.Slice(plug.Allocations, func(i, j int) bool {
		return plug.Allocations[i].ModifyIndex > plug.Allocations[j].ModifyIndex
	})

	return plug, nil
}

// UpsertCSIPlugin writes the plugin to the state store. Note: there
// is currently no raft message for this, as it's intended to support
// testing use cases.
func (s *StateStore) UpsertCSIPlugin(index uint64, plug *structs.CSIPlugin) error {
	txn := s.db.WriteTxn(index)
	defer txn.Abort()

	existing, err := txn.First(TableCSIPlugins, "id", plug.ID)
	if err != nil {
		return fmt.Errorf("csi_plugin lookup error: %s %v", plug.ID, err)
	}

	plug.ModifyIndex = index
	if existing != nil {
		plug.CreateIndex = existing.(*structs.CSIPlugin).CreateIndex
		plug.CreateTime = existing.(*structs.CSIPlugin).CreateTime
	}

	err = txn.Insert(TableCSIPlugins, plug)
	if err != nil {
		return fmt.Errorf("csi_plugins insert error: %v", err)
	}
	if err := txn.Insert("index", &IndexEntry{TableCSIPlugins, index}); err != nil {
		return fmt.Errorf("index update failed: %v", err)
	}
	return txn.Commit()
}

// DeleteCSIPlugin deletes the plugin if it's not in use.
func (s *StateStore) DeleteCSIPlugin(index uint64, id string) error {
	txn := s.db.WriteTxn(index)
	defer txn.Abort()

	plug, err := s.CSIPluginByIDTxn(txn, nil, id)
	if err != nil {
		return err
	}

	if plug == nil {
		return nil
	}

	plug, err = s.CSIPluginDenormalizeTxn(txn, nil, plug.Copy())
	if err != nil {
		return err
	}

	jobIDs := set.New[structs.NamespacedID](1)
	for _, alloc := range plug.Allocations {
		jobIDs.Insert(structs.NamespacedID{Namespace: alloc.Namespace, ID: alloc.JobID})
	}

	// after denormalization of allocs, remove any ControllerJobs or NodeJobs
	// that no longer have allocations and have been either purged or updated to
	// no longer include the plugin
	removeInvalidJobs := func(jobDescs structs.JobDescriptions) {
		for ns, namespacedJobDescs := range jobDescs {
			for jobID := range namespacedJobDescs {
				if !jobIDs.Contains(structs.NamespacedID{Namespace: ns, ID: jobID}) {
					job, err := s.JobByID(nil, ns, jobID)
					if err != nil { // programmer


mbEstadoCivil.ShadowDecoration.Parent = this.cmbEstadoCivil;
            this.cmbEstadoCivil.Size = new System.Drawing.Size(235, 36);
            this.cmbEstadoCivil.TabIndex = 38;
            //
            // cmbCargo
            //
            this.cmbCargo.BackColor = System.Drawing.Color.Transparent;
            this.cmbCargo.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
            this.cmbCargo.BorderRadius = 5;
            this.cmbCargo.BorderThickness = 2;
            this.cmbCargo.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.cmbCargo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbCargo.FocusedColor = System.Drawing.Color.Empty;
            this.cmbCargo.FocusedState.Parent = this.cmbCargo;
            this.cmbCargo.Font = new System.Drawing.Font("Segoe UI", 10F);
            this.cmbCargo.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(68)))), ((int)(((byte)(88)))), ((int)(((byte)(112)))));
            this.cmbCargo.FormattingEnabled = true;
            this.cmbCargo.HoverState.Parent = this.cmbCargo;
            this.cmbCargo.ItemHeight = 30;
            this.cmbCargo.Items.AddRange(new object[] {
            "Chef do Departamento",
            "Médico Veterinário",
            "Administrativo",
            "Chef Administrativo",
            "Chef de Área Técnica",
            "Auxiliar de Limpeza"});
            this.cmbCargo.ItemsAppearance.Parent = this.cmbCargo;
            this.cmbCargo.Location = new System.Drawing.Point(14, 123);
            this.cmbCargo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
            this.cmbCargo.Name = "cmbCargo";
            this.cmbCargo.ShadowDecoration.Parent = this.cmbCargo;
            this.cmbCargo.Size = new System.Drawing.Size(235, 36);
            this.cmbCargo.TabIndex = 38;
            //
            // cmbTipoDocumento
            //
            this.cmbTipoDocumento.BackColor = System.Drawing.Color.Transparent;
            this.cmbTipoDocumento.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
            this.cmbTipoDocumento.BorderRadius = 5;
            this.cmbTipoDocumento.BorderThickness = 2;
            this.cmbTipoDocumento.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.cmbTipoDocumento.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbTipoDocumento.FocusedColor = System.Drawing.Color.Empty;
            this.cmbTipoDocumento.FocusedState.Parent = this.cmbTipoDocumento;
            this.cmbTipoDocumento.Font = new System.Drawing.Font("Segoe UI", 10F);
            this.cmbTipoDocumento.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(68)))), ((int)(((byte)(88)))), ((int)(((byte)(112)))));
            this.cmbTipoDocumento.FormattingEnabled = true;
            this.cmbTipoDocumento.HoverState.Parent = this.cmbTipoDocumento;
            this.cmbTipoDocumento.ItemHeight = 30;
            this.cmbTipoDocumento.Items.AddRange(new object[] {
            "BI",
            "Passaporte",
            "Cedul


blank" href="http://docs.gl/gl3/glGetPixelMap">Reference Page - This function is deprecated and unavailable in the Core profile
     */
    public static void glGetPixelMapuiv(@NativeType("GLenum") int map, @NativeType("GLuint *") long data) {
        nglGetPixelMapuiv(map, data);
    }

    // --- [ glGetPointerv ] ---

    /** Unsafe version of: {@link #glGetPointerv GetPointerv} */
    public static void nglGetPointerv(int pname, long params) {
        GL11C.nglGetPointerv(pname, params);
    }

    /**
     * Returns a pointer in the current GL context.
     *
     * @param pname  the pointer to return. One of:

{@link GL43#GL_DEBUG_CALLBACK_FUNCTION DEBUG_CALLBACK_FUNCTION}	{@link GL43#GL_DEBUG_CALLBACK_USER_PARAM DEBUG_CALLBACK_USER_PARAM}

     * @param params a buffer in which to place the returned pointer
     *
     * @see Reference Page
     */
    public static void glGetPointerv(@NativeType("GLenum") int pname, @NativeType("void **") PointerBuffer params) {
        GL11C.glGetPointerv(pname, params);
    }

    /**
     * Returns a pointer in the current GL context.
     *
     * @param pname the pointer to return. One of:

{@link GL43#GL_DEBUG_CALLBACK_FUNCTION DEBUG_CALLBACK_FUNCTION}	{@link GL43#GL_DEBUG_CALLBACK_USER_PARAM DEBUG_CALLBACK_USER_PARAM}

     *
     * @see Reference Page
     */
    @NativeType("void")
    public static long glGetPointer(@NativeType("GLenum") int pname) {
        return GL11C.glGetPointer(pname);
    }

    // --- [ glGetPolygonStipple ] ---

    /** Unsafe version of: {@link #glGetPolygonStipple GetPolygonStipple} */
    public static native void nglGetPolygonStipple(long pattern);

    /**
     * Obtains the polygon stipple.
     *
     * @param pattern a buffer in which to place the returned data
     *
     * @see Reference Page - This function is deprecated and unavailable in the Core profile
     */
    public static void glGetPolygonStipple(@NativeType("void *") ByteBuffer pattern) {
        if (CHECKS) {
            check(pattern, 128);
        }
        nglGetPolygonStipple(memAddress(pattern));
    }

    /**
     * Obtains the polygon stipple.
     *
     * @param pattern a buffer in which to place the returned data
     *
     * @see Reference Page - This function is deprecated and unavailable in the Core profile
     */
    public static void glGetPolygonStipple(@NativeType("void *") long pattern) {
        nglGetPolygonStipple(pattern);
    }

    // --- [ glGetString ] ---

    /** Unsafe version of: {@link #glGetString GetString} */


/*
 * Copyright (C) 2024-present, Guanyou.Chen. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CORE_RISCV64_CORE_H_
#define CORE_RISCV64_CORE_H_

#include "api/core.h"
#include "lp64/core.h"
#include "common/elf.h"

namespace riscv64 {

class Core : public CoreApi, lp64::Core {
public:
    Core(std::unique_ptr<MemoryMap>& map)
        : CoreApi(map) {}
    ~Core();
private:
    bool load();
    void unload();
    const char* getMachineName() { return "riscv64"; }
    int getMachine() { return EM_RISCV; }
    int bits() { return 64; }
    int getPointSize() { return 8; }
    uint64_t getVabitsMask() { return 0x7FFFFFFFFFULL; }
    void loadLinkMap() { loadLinkMap64(this); }
    bool exec(uint64_t phdr, const char* file) { return exec64(this, phdr, file); }
    bool sysroot(LinkMap* handle, const char* file, const char* subfile) { return dlopen64(this, handle, file, subfile); }
    api::MemoryRef& r_debug_ptr() { return GetDebug(); }
};

} // namespace riscv64

#endif // CORE_RISCV64_CORE_H_


TerminateEnclave\"")
#pragma comment(linker, "/export:NtTerminateJobObject=\"C:\\Windows\\SysWOW64\\ntdll.NtTerminateJobObject\"")
#pragma comment(linker, "/export:NtTerminateProcess=\"C:\\Windows\\SysWOW64\\ntdll.NtTerminateProcess\"")
#pragma comment(linker, "/export:NtTerminateThread=\"C:\\Windows\\SysWOW64\\ntdll.NtTerminateThread\"")
#pragma comment(linker, "/export:NtTestAlert=\"C:\\Windows\\SysWOW64\\ntdll.NtTestAlert\"")
#pragma comment(linker, "/export:NtThawRegistry=\"C:\\Windows\\SysWOW64\\ntdll.NtThawRegistry\"")
#pragma comment(linker, "/export:NtThawTransactions=\"C:\\Windows\\SysWOW64\\ntdll.NtThawTransactions\"")
#pragma comment(linker, "/export:NtTraceControl=\"C:\\Windows\\SysWOW64\\ntdll.NtTraceControl\"")
#pragma comment(linker, "/export:NtTraceEvent=\"C:\\Windows\\SysWOW64\\ntdll.NtTraceEvent\"")
#pragma comment(linker, "/export:NtTranslateFilePath=\"C:\\Windows\\SysWOW64\\ntdll.NtTranslateFilePath\"")
#pragma comment(linker, "/export:NtUmsThreadYield=\"C:\\Windows\\SysWOW64\\ntdll.NtUmsThreadYield\"")
#pragma comment(linker, "/export:NtUnloadDriver=\"C:\\Windows\\SysWOW64\\ntdll.NtUnloadDriver\"")
#pragma comment(linker, "/export:NtUnloadKey=\"C:\\Windows\\SysWOW64\\ntdll.NtUnloadKey\"")
#pragma comment(linker, "/export:NtUnloadKey2=\"C:\\Windows\\SysWOW64\\ntdll.NtUnloadKey2\"")
#pragma comment(linker, "/export:NtUnloadKeyEx=\"C:\\Windows\\SysWOW64\\ntdll.NtUnloadKeyEx\"")
#pragma comment(linker, "/export:NtUnlockFile=\"C:\\Windows\\SysWOW64\\ntdll.NtUnlockFile\"")
#pragma comment(linker, "/export:NtUnlockVirtualMemory=\"C:\\Windows\\SysWOW64\\ntdll.NtUnlockVirtualMemory\"")
#pragma comment(linker, "/export:NtUnmapViewOfSection=\"C:\\Windows\\SysWOW64\\ntdll.NtUnmapViewOfSection\"")
#pragma comment(linker, "/export:NtUnmapViewOfSectionEx=\"C:\\Windows\\SysWOW64\\ntdll.NtUnmapViewOfSectionEx\"")
#pragma comment(linker, "/export:NtUnsubscribeWnfStateChange=\"C:\\Windows\\SysWOW64\\ntdll.NtUnsubscribeWnfStateChange\"")
#pragma comment(linker, "/export:NtUpdateWnfStateData=\"C:\\Windows\\SysWOW64\\ntdll.NtUpdateWnfStateData\"")
#pragma comment(linker, "/export:NtVdmControl=\"C:\\Windows\\SysWOW64\\ntdll.NtVdmControl\"")
#pragma comment(linker, "/export:NtWaitForAlertByThreadId=\"C:\\Windows\\SysWOW64\\ntdll.NtWaitForAlertByThreadId\"")
#pragma comment(linker, "/export:NtWaitForDebugEvent=\"C:\\Windows\\SysWOW64\\ntdll.NtWaitForDebugEvent\"")
#pragma comment(linker, "/export:NtWaitForKeyedEvent=\"C:\\Windows\\SysWOW64\\ntdll.NtWaitForKeyedEvent\"")
#pragma comment(linker, "/export:NtWaitForMultipleObjects=\"C:\\Windows\\SysWOW64\\ntdll.NtWaitForMultipleObjects\"")
#pragma comment(linker, "/export:NtWaitForMultipleObjects32=\"C:\\Windows\\SysWOW64\\ntdll.NtWaitForMultipleObjects32\"")
#pragma comment(linker, "/expo


 + 0.375rem); }
  .bootstrap .form-control.is-valid:focus {
    border-color: #28a745;
    box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25); }

.bootstrap select.form-control.is-valid {
  padding-right: 3rem !important;
  background-position: right 1.5rem center; }

.bootstrap textarea.form-control.is-valid {
  padding-right: calc(1.5em + 0.75rem);
  background-position: top calc(0.375em + 0.1875rem) right calc(0.375em + 0.1875rem); }

.bootstrap .custom-select.is-valid {
  border-color: #28a745;
  padding-right: calc(0.75em + 2.3125rem) !important;
  background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e") right 0.75rem center/8px 10px no-repeat, #fff url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e") center right 1.75rem/calc(0.75em + 0.375rem) calc(0.75em + 0.375rem) no-repeat; }
  .bootstrap .custom-select.is-valid:focus {
    border-color: #28a745;
    box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25); }

.bootstrap .form-check-input.is-valid ~ .form-check-label {
  color: #28a745; }

.bootstrap .form-check-input.is-valid ~ .valid-feedback,
.bootstrap .form-check-input.is-valid ~ .valid-tooltip {
  display: block; }

.bootstrap .custom-control-input.is-valid ~ .custom-control-label {
  color: #28a745; }
  .bootstrap .custom-control-input.is-valid ~ .custom-control-label::before {
    border-color: #28a745; }

.bootstrap .custom-control-input.is-valid:checked ~ .custom-control-label::before {
  border-color: #34ce57;
  background-color: #34ce57; }

.bootstrap .custom-control-input.is-valid:focus ~ .custom-control-label::before {
  box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25); }

.bootstrap .custom-control-input.is-valid:focus:not(:checked) ~ .custom-control-label::before {
  border-color: #28a745; }

.bootstrap .custom-file-input.is-valid ~ .custom-file-label {
  border-color: #28a745; }

.bootstrap .custom-file-input.is-valid:focus ~ .custom-file-label {
  border-color: #28a745;
  box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25); }

.bootstrap .invalid-feedback {
  display: none;
  width: 100%;
  margin-top: 0


Dictionary,Set,(const string&,void*,int),void), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectMethod("dictionary", "bool get(const string &in, ?&out) const", asMETHODPR(CScriptDictionary,Get,(const string&,void*,int) const,bool), asCALL_THISCALL); assert( r >= 0 );

	r = engine->RegisterObjectMethod("dictionary", "void set(const string &in, const int64&in)", asMETHODPR(CScriptDictionary,Set,(const string&,const asINT64&),void), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectMethod("dictionary", "bool get(const string &in, int64&out) const", asMETHODPR(CScriptDictionary,Get,(const string&,asINT64&) const,bool), asCALL_THISCALL); assert( r >= 0 );

	r = engine->RegisterObjectMethod("dictionary", "void set(const string &in, const double&in)", asMETHODPR(CScriptDictionary,Set,(const string&,const double&),void), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectMethod("dictionary", "bool get(const string &in, double&out) const", asMETHODPR(CScriptDictionary,Get,(const string&,double&) const,bool), asCALL_THISCALL); assert( r >= 0 );

	r = engine->RegisterObjectMethod("dictionary", "bool exists(const string &in) const", asMETHOD(CScriptDictionary,Exists), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectMethod("dictionary", "bool isEmpty() const", asMETHOD(CScriptDictionary, IsEmpty), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectMethod("dictionary", "uint getSize() const", asMETHOD(CScriptDictionary, GetSize), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectMethod("dictionary", "void delete(const string &in)", asMETHOD(CScriptDictionary,Delete), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectMethod("dictionary", "void deleteAll()", asMETHOD(CScriptDictionary,DeleteAll), asCALL_THISCALL); assert( r >= 0 );

	r = engine->RegisterObjectMethod("dictionary", "array<string> @getKeys() const", asMETHOD(CScriptDictionary,GetKeys), asCALL_THISCALL); assert( r >= 0 );

	r = engine->RegisterObjectMethod("dictionary", "dictionaryValue &opIndex(const string &in)", asMETHODPR(CScriptDictionary, operator[], (const string &), CScriptDictValue*), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectMethod("dictionary", "const dictionaryValue &opIndex(const string &in) const", asMETHODPR(CScriptDictionary, operator[], (const string &) const, const CScriptDictValue*), asCALL_THISCALL); assert( r >= 0 );

	// Register GC behaviours
	r = engine->RegisterObjectBehaviour("dictionary", asBEHAVE_GETREFCOUNT, "int f()", asMETHOD(CScriptDictionary,GetRefCount), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectBehaviour("dictionary", asBEHAVE_SETGCFLAG, "void f()", asMETHOD(CScriptDictionary,SetGCFlag), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectBehaviour("dictionary", asBEHAVE_GETGCFLAG, "bool f()", asMETHOD(CScriptDictionary,GetGCFlag), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectBehaviour("dictionary", asBEHAVE_ENUMREFS, "void f(int&in)", asMETHOD(CScriptDictionary,EnumReferences), asCALL_THISCALL); assert( r >= 0 );
	r = engine->RegisterObjectBehaviour("dictionary", asBEHAVE_RELEASEREFS, "void f(int&in)", asMETHOD(CScriptDictionary,ReleaseAllReferences), asCALL_THISCALL); assert( r >= 0 );

#if AS_USE_STLNAMES == 1
	// Same as isEmpty
	r = engine->RegisterObjectMethod("dictionary", "bool empty


le chargement intégral du document se termine 562 ms plus tôt, toujours parce que le chargement de toutes les ressources externes a pu démarrer plus rapidement.

Les quatre dernières requêtes (surlignées en jaune) sont renvoyées sous forme de réponses 304 Not Modified avec un en-tête If-None-Match. Par défaut, Cloudflare Pages demande au navigateur de confirmer que toutes les ressources sont récentes et par conséquent, dans l'éventualité où elles ont été mises à jour entre la réponse d'Early Hints et le moment de leur utilisation, le navigateur vérifie si elles ont été modifiées. Puisque ce n'est pas le cas, il n'y a pas de contenu à télécharger, et la réponse est rapidement finalisée. Ceci peut être évité en définissant un en-tête Cache-Control personnalisé pour ces ressources avec un fichier _headers. Par exemple, vous pouvez mettre en cache ces images pendant une minute avec une règle telle que :

# _headers

/*.png
  Cache-Control: max-age=60

Nous pourrions pousser plus loin cet audit des performances en explorant d'autres fonctionnalités que propose Cloudflare, telles que la minimisation CSS automatique, Cloudflare Images et Redimensionnement d'image.

Nous servons déjà Cloudflare Pages depuis l'un des réseaux les plus rapides du monde ; Early Hints permet simplement aux développeurs de profiter encore davantage de notre réseau mondial.

Utilisation d'Early Hints et de Cloudflare Pages

La fonctionnalité Early Hints de Cloudflare est actuellement limitée à la mise en cache des en-têtes Link dans la réponse d'une page web. Habituellement, cela signifierait que les utilisateurs de Cloudflare Pages devraient utiliser le fichier _headers ou Pages Functions pour appliquer ces en-têtes. Cependant, pour votre confort, nous avons également ajouté la possibilité de transformer tout élément HTML <link> inclus dans le corps de la page dans les en-têtes Link. Ceci vous permet de contrôler directement les données Early Hints que vous envoyez, directement depuis le même document dans lequel vous référencez ces ressources ; plus besoin de sortir du code HTML pour profiter d'Early Hin


items:center}.ybar-ytheme-crunch ._yb_l2-news ._yb_1fgvb2y ._yb_170b9mh ._yb_1il88ct ._yb_1m9r3ve:first-of-type{margin-top:4px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_e4ycax ._yb_1m9r3ve ._yb_c8iby5 ._yb_1o0j2a5{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:148px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-2{width:332px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-3{width:494px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-4{width:664px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-5{width:834px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-6{width:1004px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-7{width:1174px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-8{width:1344px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-9{width:1514px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-10{width:1684px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-11{width:1854px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_ow-12{width:2072px}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_1il88ct._yb_1bd4i20 ._yb_1m9r3ve{max-width:196px;min-width:162px;width:auto}.ybar-ytheme-crunch ._yb_1fgvb2y:not(._yb_18g4mml) ._yb_e4ycax ._yb_1il88ct._yb_1bd4i20 ._yb_1m9r3ve ._yb_c8iby5 div{max-width:185px}.ybar-dark ._yb_e4ycax ._yb_1m9r3ve a._yb_c8iby5:focus:before{background:#fff;background:var(--yb-white)}.ybar-dark ._yb_e4ycax ._yb_1m9r3ve a._yb_c8iby5:focus{color:#fff;color:var(--yb-white);text-shadow:.8px 0 0 #fff;text-shadow:.8px 0 0 var(--yb-white)}._yb_e4ycax ._yb_1m9r3ve:hover ._yb_c8iby5{background-color:rgb(24 143 255/12%);color:#000;color:var(--yb-black);text-shadow:.8px 0 0 #000;text-shadow:.8px 0 0 var(--


      {
        "Id": "Deployment-2",
        "ReleaseId": "Release-2",
        "EnvironmentId": "Environment-1",
        "DeployedAt": "2000-01-01T11:00:00"
      },
      ],
      environments: [{
        "Id": "Environment-1",
        "Name": "Staging"
      },],
      projects: [{
        "Id": "Project-1",
        "Name": "Random Quotes"
      },],
      releases: [{
        "Id": "Release-1",
        "ProjectId": "Project-1",
        "Version": "1.0.0",
        "Created": "2000-01-01T08:00:00"
      },
      {
        "Id": "Release-2",
        "ProjectId": "Project-1",
        "Version": "1.0.0",
        "Created": "2000-01-01T09:00:00"
      },

      ]
    }, 2);

    expect(result).toBeDefined();
    expect(result.releasesKept).toHaveLength(2);

    //I like writing my array assertions this way, because it's simple.
    // However, it is a little bit more brittle, assuming that the array order doesn't matter, if you were to change the implementation and the order changed, then these tests would break.

    expect(result.releasesKept[1].release.Id).toBe("Release-1");
    expect(result.releasesKept[1].keepReason).toBe("Release-1 kept because it was the 1 most recently deployed to Environment-1");

    expect(result.releasesKept[0].release.Id).toBe("Release-2");
    expect(result.releasesKept[0].keepReason).toBe("Release-2 kept because it was the 0 most recently deployed to Environment-1");

    // Alternatively, you can write your array assertions this way
    // But this is a lot more difficult to write, and read, IMO.
    // Let me know if you have any suggestions on a better way to do this!
    expect(result.releasesKept).toEqual(expect.arrayContaining([
      expect.objectContaining(
        {
          release: {
            "Created": "2000-01-01T08:00:00",
            "Id": "Release-1",
            "ProjectId": "Project-1",
            "Version": "1.0.0"
          },
          keepReason: "Release-1 kept because it was the 1 most recently deployed to Environment-1"
        },
      ),
      expect.objectContaining({
        release: {
          "Id": "Release-2",
          "ProjectId": "Project-1",
          "Version": "1.0.0",
          "Created": "2000-01-01T09:00:00"
        },
        keepReason: "Release-2 kept because it was the 0 most recently deployed to Environment-1"
      })]));

  });

});import stringify from 'json-stringify-safe';

export function log(target: Record<string, any>, key: string, descriptor: TypedPropertyDescriptor<any>): TypedPropertyDescriptor<any> {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]): any {
    const a = args.map(a => stringify(a)).join();
    const result = originalMethod.apply(this, args);
    const r = stringify(result);
    console.log(`Call: ${key}(${a}) => ${r}`);
    return result;
  };

  return descriptor;
}

export function debug(target: Record<string, any>, key: string, descriptor: TypedPropertyDescriptor<any>): TypedPropertyDescriptor<any> {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]): any {
    console.debug('>>>>>>>>>>>>>>>>>> ' + originalMethod.name);
    const result = origina


	err = b.db.ScanRows(rows, file)
		if err != nil {
			return err
		}
		err = f(file)
		if err != nil {
			return err
		}
	}

	return nil
}
package metadata

import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/root-gg/plik/server/common"
)

func TestCreateSetting(t *testing.T) {
	b := newTestMetadataBackend()
	defer shutdownTestMetadataBackend(b)

	err := b.CreateSetting(&common.Setting{Key: "foo", Value: "bar"})
	require.NoError(t, err, "create setting error")

	err = b.CreateSetting(&common.Setting{Key: "foo", Value: "bar"})
	require.Error(t, err, "create setting error expected")
}

func TestGetSetting(t *testing.T) {
	b := newTestMetadataBackend()
	defer shutdownTestMetadataBackend(b)

	setting, err := b.GetSetting("foo")
	require.NoError(t, err, "get setting error")
	require.Nil(t, setting, "non nil setting")

	err = b.CreateSetting(&common.Setting{Key: "foo", Value: "bar"})
	require.NoError(t, err, "create setting error")

	setting, err = b.GetSetting("foo")
	require.NoError(t, err, "get setting error")
	require.NotNil(t, setting, "nil setting")
	require.Equal(t, "foo", setting.Key, "invalid setting key")
	require.Equal(t, "bar", setting.Value, "invalid setting value")
}

func TestUpdateSetting(t *testing.T) {
	b := newTestMetadataBackend()
	defer shutdownTestMetadataBackend(b)

	err := b.UpdateSetting("foo", "bar", "baz")
	require.Error(t, err, "update setting error expected")

	err = b.CreateSetting(&common.Setting{Key: "foo", Value: "bar"})
	require.NoError(t, err, "create setting error")

	err = b.UpdateSetting("foo", "bar", "baz")
	require.NoError(t, err, "update setting error")

	err = b.UpdateSetting("foo", "bar", "baz")
	require.Error(t, err, "update setting error expected")

	setting, err := b.GetSetting("foo")
	require.NoError(t, err, "get setting error")
	require.NotNil(t, setting, "nil setting")
	require.Equal(t, "foo", setting.Key, "invalid setting key")
	require.Equal(t, "baz", setting.Value, "invalid setting value")
}

func TestDeleteSetting(t *testing.T) {
	b := newTestMetadataBackend()
	defer shutdownTestMetadataBackend(b)

	err := b.CreateSetting(&common.Setting{Key: "foo", Value: "bar"})
	require.NoError(t, err, "create setting error")

	setting, err := b.GetSetting("foo")
	require.NoError(t, err, "get setting error : %s", err)
	require.NotNil(t, setting, "nil setting")

	err = b.DeleteSetting("foo")
	require.NoError(t, err, "delete setting error : %s", err)

	setting, err = b.GetSetting("foo")
	require.NoError(t, err, "get setting error : %s", err)
	require.Nil(t, setting, "non nil setting")
}

func TestBackend_ForEachSetting(t *testing.T) {
	b := newTestMetadataBackend()
	defer shutdownTestMetadataBackend(b)

	err := b.CreateSetting(&common.Setting{Key: "foo", Value: "bar"})
	require.NoError(t, err, "create setti


func (s *ReportService) GetPageReport(rid int, crawlId int64, tab string, page int) *models.PageReportView {
	v := &models.PageReportView{
		PageReport: s.repository.FindPageReportById(rid),
		ErrorTypes: s.repository.FindErrorTypesByPage(rid, crawlId),
	}

	v.PageReport.Hreflangs = s.repository.FindPageReportHreflangs(&v.PageReport, crawlId)

	switch tab {
	case "internal":
		v.PageReport.InternalLinks = s.repository.FindLinks(&v.PageReport, crawlId, page)
	case "external":
		v.PageReport.ExternalLinks = s.repository.FindExternalLinks(&v.PageReport, crawlId, page)
	case "inlinks":
		v.InLinks = s.repository.FindInLinks(v.PageReport.URL, crawlId, page)
	case "redirections":
		v.Redirects = s.repository.FindPageReportsRedirectingToURL(v.PageReport.URL, crawlId, page)
	case "styles":
		v.PageReport.Styles = s.repository.FindPageReportStyles(&v.PageReport, crawlId)
	case "scripts":
		v.PageReport.Scripts = s.repository.FindPageReportScripts(&v.PageReport, crawlId)
	case "videos":
		v.PageReport.Videos = s.repository.FindPageReportVideos(&v.PageReport, crawlId)
	case "audios":
		v.PageReport.Audios = s.repository.FindPageReportAudios(&v.PageReport, crawlId)
	case "iframes":
		v.PageReport.Iframes = s.repository.FindPageReportIframes(&v.PageReport, crawlId)
	case "images":
		v.PageReport.Images = s.repository.FindPageReportImages(&v.PageReport, crawlId)
	}

	v.Paginator = s.getPaginator(&v.PageReport, crawlId, tab, page)

	return v
}

// Returns the paginator for the specific "tab".
func (s *ReportService) getPaginator(pageReport *models.PageReport, crawlId int64, tab string, page int) models.Paginator {
	paginator := models.Paginator{
		CurrentPage: page,
	}

	switch tab {
	case "internal":
		paginator.TotalPages = s.repository.GetNumberOfPagesForLinks(pageReport, crawlId)
	case "external":
		paginator.TotalPages = s.repository.GetNumberOfPagesForExternalLinks(pageReport, crawlId)
	case "inlinks":
		paginator.TotalPages = s.repository.GetNumberOfPagesForInlinks(pageReport, crawlId)
	case "redirections":
		paginator.TotalPages = s.repository.GetNumberOfPagesForRedirecting(pageReport, crawlId)
	default:
		paginator.TotalPages = 1
	}

	if paginator.CurrentPage < paginator.TotalPages {
		paginator.NextPage = paginator.CurrentPage + 1
	}

	if paginator.CurrentPage > 1 {
		paginator.PreviousPage = paginator.CurrentPage - 1
	}

	return paginator
}

// Return channel of PageReports by error type.
func (s *ReportService) GetPageReporsByIssueType(crawlId int64, eid string) <-chan *models.PageReport {
	if eid != "" {
		return s.repository.FindAllPageReportsByCrawlIdAndErrorType(crawlId, eid)
	}

	return s.repository.FindAllPageReportsByCrawlId(crawlId)
}

// Returns a PaginatorView with the corresponding page reports.
func (s *ReportService) GetPaginatedReports(crawlId int64, currentPage int, term string) (models.PaginatorView, error) {
	paginator := models.Paginator{
		TotalPages:  s.repository.GetNumberOfPagesForPageReport(crawlId, term),
		CurrentPage: currentPage,
	}

	if currentPage < 1 || (paginator.TotalPages > 0 && currentPage > paginator.TotalPages) {
		return models.PaginatorView{}, errors.New("page out of bounds")
	}

	if currentPage < p


, P, V> {
        let extractor = self.get_interval_value_extractor();
        let mut intervals = Vec::new();
        let mut values = Vec::new();
        match self.next() {
            None => {
                intervals.push(None);
                values.push(None);
            }
            Some(x) => {
                let (interval, value) = extractor(x);
                intervals.push(Some(interval));
                values.push(Some(value));
            }
        }
        match other.next() {
            None => {
                intervals.push(None);
                values.push(None);
            }
            Some(x) => {
                let (interval, value) = extractor(x);
                intervals.push(Some(interval));
                values.push(Some(value));
            }
        }
        CommonRefinementZipped {
            iters: vec![self, other],
            intervals,
            values,
            extractor,
            phantom: PhantomData,
        }
    }
}

/// # Example
/// ```
/// use analytic::{
///     interval::{traits::Interval, IntInterval},
///     iter::CommonRefinementZip,
/// };
/// use std::collections::BTreeMap;
///
/// let m1: BTreeMap<IntInterval<usize>, i32> =
///     vec![(IntInterval::new(0, 5), 5), (IntInterval::new(8, 10), 2)]
///         .into_iter()
///         .collect();
///
/// let m2: BTreeMap<IntInterval<usize>, i32> =
///     vec![(IntInterval::new(2, 4), 8), (IntInterval::new(12, 13), 9)]
///         .into_iter()
///         .collect();
///
/// let mut iter = m1.iter().common_refinement_zip(m2.iter());
/// assert_eq!(
///     Some((IntInterval::new(0, 1), vec![Some(5), None])),
///     iter.next()
/// );
/// assert_eq!(
///     Some((IntInterval::new(2, 4), vec![Some(5), Some(8)])),
///     iter.next()
/// );
/// assert_eq!(
///     Some((IntInterval::new(5, 5), vec![Some(5), None])),
///     iter.next()
/// );
/// assert_eq!(
///     Some((IntInterval::new(8, 10), vec![Some(2), None])),
///     iter.next()
/// );
/// assert_eq!(
///     Some((IntInterval::new(12, 13), vec![None, Some(9)])),
///     iter.next()
/// );
/// assert_eq!(None, iter.next());
/// ```
impl<'a, V, B: Integer + Copy + ToPrimitive>
    CommonRefinementZip<B, (&'a IntInterval<B>, &'a V), IntInterval<B>, V>
    for std::collections::btree_map::Iter<'a, IntInterval<B>, V>
where
    B: 'a,
    V: 'a + Clone,
{
    fn get_interval_value_extractor(
        &self,
    ) -> Box<dyn Fn(<Self as Iterator>::Item) -> (IntInterval<B>, V)> {
        Box::new(|item| ((*item.0).clone(), (*item.1).clone()))
    }
}

impl<'a, V, B: Integer + Copy + ToPrimitive>
    CommonRefinementZip<B, (IntInterval<B>, V), IntInterval<B>, V>
    for std::collections::btree_map::IntoIter<IntInterval<B>, V>
where
    B: 'a,
{
    fn get_interval_value_extractor(
        &self,
    ) -> Box<dyn Fn(<Self as Iterator>::Item) -> (IntInterval<B>, V)> {
        Box::new(|item| (item.0, item.1))
    }
}

/// # Iterator Algorithm Description
/// Given a list of iterators, a list of the current minimum interval for each iterator will be
/// maintained together with their associated values. Then, at each pass the smallest minimum common
/// refinement of the current intervals is subtracted from each interval. A list of v


g boolean arrays uses `&`, `|` or `~`
  * Equivalent to `locigal_and`, `logical_or` and `logical_not` functions
  * `and`, `or` and `not` are scalar only

# Array logical operators
* Elementwise _and_ : `c[i]` `True` if `a[i]` and `b[i]` are `True`
```python
c = a & b
c = np.logical_and(a, b)
```
* Elementwise _or_ : `c[i]` `True` if `a[i]` or `b[i]` are `True`
```python
c =a | b
c = np.logical_or(a, b)
```
* Elementwise _not_ : `c[i]` `True` if `a[i]` is False
```python
c = ~a
c = np.logical_not(a)
```

# `any` and `all`
## Logical aggregation

* Common to use `any` or `all` on arrays
  * `any` returns `True` is any value is `True`
  * `all` returns `True` is all values are `True`
* Reduce vectors to scalars
* Key difference between `DataFrame` methods and NumPy functions
  * `df.any` and `df.all` operator column-by-column
  * `np.any` and `np.all` default to entire array
    * Use `np.any(axis=0)` for column-by-column
* Using `axis=1` operates row-by-row

# Numerical Conversion

* Boolean values are 0/1
* Mathematical operations cast Booleans to integers
  * `sum` counts boolean arrays
  * `mean` computes frequency
  * Multiplication (`*`) produces interactions

```python
x = np.array([-3, 3, 2, -2, -1, 1, 0])
x * (x < 0)
```
```
array([-3, 0, 0, -2, -1, 0, 0])
```

# Boolean Arrays
## Summary

* Boolean arrays are created using `<`, `<=`, `==`, `!=`,  `>=`, `>`
* Arrays of `True` and `False`
  * `True` is 1 in math ops
* Must use `&`, `|` and `~`
  * Function equivalents: `logical_and`, `logical_or`, `logical_not`
  * `and`, `or` and `not` produce errors

# Lesson 16

# Boolean Selection
## Overview

* Boolean arrays can be used to select
  * `True` includes
  * `False` excludes
* Use `.loc` in pandas
* NumPy selection behaves like list of integers
  * Use `np.ix_` when selecting 2 or more axes

# Selection using `.loc`
## `DataFrame` and `Series`

* Logical selection must use `loc`
* Equivalent
```python
sel = (df > 0).any(axis=1)
df.loc[sel]
df.loc[df.index[sel]]
```
* Logical selector must match dimension or rows/columns

# Boolean Selection in array
## Matches list selection

* Boolean selection in NumPy array matches list selection
* Equivalent to using `np.where` to convert boolean to position
* Can only be directly used for 1 axis
  * Use `np.ix_` when using list/boolean in multiple dimensions

# Boolean Selection
## Summary

* Use `.loc` with boolean arrays
* Array dimension must match axis shape
* NumPy converts boolean array to list of integers
  * Care needed when selecting in 2 or more axes

# Lesson 17

# Conditional Statements
## Overview

* `if` statements allow conditional execution
* `else` extends an `if` to ensure code execution
* `elif` can be used to add additional paths
* Must use consistent indentation in `if`-`elif`-`else` blocks

# `if`

* Basic conditional statement
* Execute code in block if condition is `True`
  * Nothing executed if `False`

```python
if x >= 0:
    print(x)
```

* `if`:  Required keyword
* _condition_ is evaluated to `True`/`False`
* colon (`:`)


 represented in two's complement. We must
     never shift right a value that may be negative, since that would
     invalidate the sign bit. On the other hand, divexact by odd
     numbers work fine with two's complement.
  */

  mpn_add_n (w5, w5, w4, m);
  if (flags & toom7_w1_neg)
    {
#ifdef HAVE_NATIVE_mpn_rsh1add_n
      mpn_rsh1add_n (w1, w1, w4, m);
#else
      mpn_add_n (w1, w1, w4, m);  ASSERT (!(w1[0] & 1));
      mpn_rshift (w1, w1, m, 1);
#endif
    }
  else
    {
#ifdef HAVE_NATIVE_mpn_rsh1sub_n
      mpn_rsh1sub_n (w1, w4, w1, m);
#else
      mpn_sub_n (w1, w4, w1, m);  ASSERT (!(w1[0] & 1));
      mpn_rshift (w1, w1, m, 1);
#endif
    }
  mpn_sub (w4, w4, m, w0, 2*n);
  mpn_sub_n (w4, w4, w1, m);  ASSERT (!(w4[0] & 3));
  mpn_rshift (w4, w4, m, 2); /* w4>=0 */

  tp[w6n] = mpn_lshift (tp, w6, w6n, 4);
  mpn_sub (w4, w4, m, tp, w6n+1);

  if (flags & toom7_w3_neg)
    {
#ifdef HAVE_NATIVE_mpn_rsh1add_n
      mpn_rsh1add_n (w3, w3, w2, m);
#else
      mpn_add_n (w3, w3, w2, m);  ASSERT (!(w3[0] & 1));
      mpn_rshift (w3, w3, m, 1);
#endif
    }
  else
    {
#ifdef HAVE_NATIVE_mpn_rsh1sub_n
      mpn_rsh1sub_n (w3, w2, w3, m);
#else
      mpn_sub_n (w3, w2, w3, m);  ASSERT (!(w3[0] & 1));
      mpn_rshift (w3, w3, m, 1);
#endif
    }

  mpn_sub_n (w2, w2, w3, m);

  mpn_submul_1 (w5, w2, m, 65);
  mpn_sub (w2, w2, m, w6, w6n);
  mpn_sub (w2, w2, m, w0, 2*n);

  mpn_addmul_1 (w5, w2, m, 45);  ASSERT (!(w5[0] & 1));
  mpn_rshift (w5, w5, m, 1);
  mpn_sub_n (w4, w4, w2, m);

  mpn_divexact_by3 (w4, w4, m);
  mpn_sub_n (w2, w2, w4, m);

  mpn_sub_n (w1, w5, w1, m);
  mpn_lshift (tp, w3, m, 3);
  mpn_sub_n (w5, w5, tp, m);
  mpn_divexact_by9 (w5, w5, m);
  mpn_sub_n (w3, w3, w5, m);

  mpn_divexact_by15 (w1, w1, m);
  mpn_add_n (w1, w1, w5, m);  ASSERT (!(w1[0] & 1));
  mpn_rshift (w1, w1, m, 1); /* w1>=0 now */
  mpn_sub_n (w5, w5, w1, m);

  /* These bounds are valid for the 4x4 polynomial product of toom44,
   * and they are conservative for toom53 and toom62. */
  ASSERT (w1[2*n] < 2);
  ASSERT (w2[2*n] < 3);
  ASSERT (w3[2*n] < 4);
  ASSERT (w4[2*n] < 3);
  ASSERT (w5[2*n] < 2);

  /* Addition chain. Note carries and the 2n'th limbs that need to be
   * added in.
   *
   * Special care is needed for w2[2n] and the corresponding carry,
   * since the "simple" way of adding it all together would overwrite
   * the limb at wp[2*n] and rp[4*n] (same location) with the sum of
   * the high half of w3 and the low half of w4.
   *
   *         7    6    5    4    3    2    1    0
   *    |    |    |    |    |    |    |    |    |
   *                  ||w3 (2n+1)|
   *             ||w4 (2n+1)|
   *        ||w5 (2n+1)|        ||w1 (2n+1)|
   *  + | w6 (w6n)|        ||w2 (2n+1)| w0 (2n) |  (share storage with r)
   *  -----------------------------------------------
   *  r |    |    |    |    |    |    |    |    |
   *        c7   c6   c5   c4   c3                 Carries to propagate
   */

  cy = mpn_add_n (rp + n, rp + n, w1, m);
  MPN_INCR_U (w2 + n + 1, n , cy);
  cy = mpn_add_n (rp + 3*n, rp + 3*n, w3, n);
  MPN_INCR_U (w3 + n, n + 1, w2[2*n] + cy);
  cy = mpn_add_n (rp + 4*n, w3 + n, w4, n);
  MPN_INCR_U (w4 + n, n + 1, w3[2*n] + cy);
  cy = mpn_add_n (rp + 5*n, w4 + n, w5, n);
  MPN_INCR_U (w5 + n, n + 1, w4[2*n] + cy);
  if (w6n > n + 1)
    {
      cy = mpn_add_n (rp + 6*n, rp + 6*n, w5 + n, n + 1);
      MPN_INCR_U (rp + 7*n + 1, w6n - n - 1, cy);
    }
  else
    {
      ASSERT_NOCARRY (mpn_add_n (rp + 6*n, rp + 6*n, w5 + n, w6n));
#if WANT_ASSERT
      {
	mp_size_t i;
	for (i = w6n; i <= n; i++)
	  ASSERT (w5[n + i] == 0);
      }
#endif
    }
}


02Fmining\u002Fandrew-forrest-set-to-bury-sand-miner-quarry-parks-bid-to-poke-around-billionaires-minderoo-station-ng-b881667232z","source":"The West Australian","isLive":false,"requiredAccess":{"level":"subscriber"},"_self":"https://thewest.com.au\u002Fbusiness\u002Fmining\u002Fandrew-forrest-set-to-bury-sand-miner-quarry-parks-bid-to-poke-around-billionaires-minderoo-station-ng-b881667232z","promotionType":undefined,"allowCommenting":false,"profiles":[{"name":"Neale Prior","slug":"neale-prior","email":"neale.prior@wanews.com.au","position":"Personal Finance Editor","biography":"Neale Prior had a misspent youth as a cadet then a real plod with WA Police. After a uni student stint cleaning toilets and waiting tables, he went into journalism. He’s covered most rounds but most enjoys personal finance and investigating dodgy business behaviour, areas sadly overlapping given most scams are aimed at the most vulnerable. His addiction to coffee is very handy given he’s studying for a masters in financial planning, an area linked to his main gig as The West Australian’s personal finance editor.","mainPhoto":"https://images.thewest.com.au\u002Fassets\u002Fprofiles\u002FNealePrior.png","thumbnailPhoto":"https://images.thewest.com.au\u002Fassets\u002Fprofiles\u002FNealePrior_thumb.png"}],"layoutView":"default","classification":undefined},{"id":"B881667013Z","cardType":"publication","isSponsored":false,"lastUpdated":"2020-09-15T04:41:51.185Z","publicationDate":"2020-09-15T02:36:00.000Z","primaryTopic":{"id":"sport\u002Fsydney-swans","guid":"cke86q6oi01es07lm5l953rdp","title":"Sydney Swans","metadata":{},"seoTitle":"Sydney Swans","parent":{"id":"sport","guid":"cke86oc2b016107lm4hmj7pr9","title":"Sport","metadata":{},"seoTitle":"Sport","seoDescription":"The latest sport coverage from your team and others. Includes the most recent AFL, WAFL, cricket, tennis, soccer, basketball, golf and racing coverage."}},"secondaryTopics":[{"id":"sport\u002Fafl","guid":"cke86ofa8016i07lm01aaf9rl","title":"AFL","metadata":{},"seoTitle":"AFL","parent":{"id":"sport","guid":"cke86oc2b016107lm4hmj7pr9","title":"Sport","metadata":{},"seoTitle":"Sport","seoDescription":"The latest sport coverage from your team and others. Includes the most recent AFL, WAFL, cricket, tennis, soccer, basketball, golf and racing coverage."}},{"id":"news\u002Fcourt-justice","guid":"cke86q6bj01eq07lmaou0bowb","title":"Courts & Justice","metadata":{},"seoTitle":"Courts & Justice","parent":{"id":"news","guid":"cke86obuk016007lm7d5j70ke","title":"News","metadata":{},"seoTitle":"News","seoDescription":"The latest news at home and across the world featuring news on Western Australia, Australia, the world and other topics you are interested in."}},{"id":"news\u002Fcrime","guid":"cke86ohox016u07lme66q3flc","title":"Crime","metadata":{},"seoTitle":"Crime","parent":{"id":"news","guid":"cke86obuk016007lm7d5j70ke","title":"News","metadata":{},"seoTitle":"News","seoDescription":"The latest news at home and across the world featuring news on Western Australia, Australia, the world and other topics you are interested in."}},{"id":"news\u002Fperth","guid":"cke86oh9q016s07lm2m9j8qu6","title":"Perth","metadata":{},"seoTitle":"Perth","parent":{"id":"news","guid":"cke86obuk016007lm7d5j70ke","title":"News","metadata":{},"seoTitle":"


                }

            else -> error("MenuTitleSerializer does not support $element")
        }
    }

}

object CycleModeSerializer : KSerializer<CycleMode> {

    override val descriptor = PrimitiveSerialDescriptor("CycleMode", PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder): CycleMode = decoder.decodeString().tolerantEnum(CycleMode.LOOP)

    override fun serialize(encoder: Encoder, value: CycleMode) = encoder.encodeString(value.name)

}

internal object InventoryTypeSerializer : KSerializer<InventoryType> {

    override val descriptor = PrimitiveSerialDescriptor("InventoryType", PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder): InventoryType = decoder.decodeString().tolerantEnum(InventoryType.CHEST)

    override fun serialize(encoder: Encoder, value: InventoryType) = encoder.encodeString(value.name)

}

private inline fun <reified T : Enum<T>> String.tolerantEnum(default: T) = uppercase()
    .replace(' ', '_')
    .replace('-', '_')
    .let { input -> enumValues<T>().find { it.name == input } ?: default }@file:Suppress("DSL_SCOPE_VIOLATION")

import java.io.FileInputStream
import java.util.Properties
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType

plugins {
    alias(libs.plugins.agp.application)
    alias(libs.plugins.ktlint)
    alias(libs.plugins.kotlin.android)
    alias(libs.plugins.ksp)
    alias(libs.plugins.mannodermaus.android.junit5)
    alias(libs.plugins.mikepenz.aboutlibraries)
    alias(libs.plugins.compose.compiler)
    checkstyle
    jacoco
}

apply(plugin = "checkstyle")

tasks.register<Checkstyle>("checkstyle") {
    source = fileTree("src")
    configFile = project.rootProject.file("config/checkstyle/checkstyle.xml")
    includes += "**/*.java"
    isShowViolations = true
    excludes += setOf("**/gen/**", "**/R.java")
    classpath = files()
    reports {
        xml.required.set(true)
        html.required.set(true)
    }
}

tasks.check {
    dependsOn("checkstyle")
}

android {
    val versionPropsFile = file("version.properties")
    val versionProps = Properties()
    versionProps.load(FileInputStream(versionPropsFile))

    val versionMajor = (versionProps["MAJOR"] as String).toInt()
    val versionMinor = (versionProps["MINOR"] as String).toInt()
    val versionPatch = (versionProps["PATCH"] as String).toInt()
    val versionRc = (versionProps["RC"] as String).toInt()
    val prNumber = versionProps["PR"] as String?

    namespace = "inc.flide.vim8"
    compileSdk = 34

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }

    packaging {
        resources {
            excludes += setOf(
                "META-INF/licenses/*",
                "META-INF/AL2.0",
                "META-INF/LGPL*",
                "win32-x86-64/*",
                "win32-x86/*"
            )
        }
    }

    kotlinOptions {
        jvmTarget = "17"
        freeCompilerArgs = listOf(
            "-Xallow-result-return-type",
            "-opt-in=kotlin.contracts.ExperimentalContracts",
            "-Xjvm-default=all-compatibility"
        )
    }

    defaultConfig {
        applicationId = "inc.flide.vi8"
        minSdk = 24
        targetSdk = 34
        resValue("string", "app_name", "8Vim")
        if (prNumber != null) {
            versionCode = (System.currentT


dingElem.classList.add('building')
  let floorsElem = document.createElementNS('http://www.w3.org/2000/svg','g')
  //let peopleElem = document.createElementNS('http://www.w3.org/2000/svg','g')
  svg.appendChild(buildingElem)
  svg.appendChild(elevators)
  svg.appendChild(floorsElem)
  //svg.appendChild(peopleElem)
  let i = 0
  let interval = window.setInterval(() => {
    let elem = document.createElementNS('http://www.w3.org/2000/svg','circle')
    elem.r.baseVal.value = 4
    elem.classList.add('person')
    let p = new Person(building,elem,speed)
    if (i >= 228) window.clearInterval(interval)
    i++
  },250 / speed)
  /*for (let p = 0; p < 100; p++) {
    let person = new Person(building)
    people.push(person)
    let view = document.createElementNS('http://www.w3.org/2000/svg','circle')
    peopleElem.appendChild(view)
    view.classList.add('person')
    view.r.baseVal.value = 4
    let oldPosition: Elevator | Floor | null = null
    let t = svg.createSVGTransform()
    view.transform.baseVal.initialize(t)
    view.cy.baseVal.value = - (Math.random() * 0.8 + 0.1) * options.elevatorHeight
    updateHandlers.push((dt: number) => {
      if (person.position instanceof Elevator) {
        t.setTranslate(0,options.floorHeight * building.floorCount - (person.position.position * options.floorHeight))
      } else {
        t.setTranslate(0,options.floorHeight * building.floorCount - person.position.id * options.floorHeight)
      }
      if (person.position != oldPosition) {
        oldPosition = person.position
        if (person.position instanceof Elevator) {
          view.cx.baseVal.value =
            options.textWidth + options.elevatorGap + (Math.random() * 0.4 + 0.55) * options.elevatorWidth+
            person.position.shaft.id * (options.elevatorWidth + options.elevatorGap)
        } else if (person.position instanceof Floor) {
          view.cx.baseVal.value =
            Math.random() * (options.textWidth + options.elevatorGap)
        }
      }
    })
  } */
  building.shafts.forEach(shaft => {
    let view = new ElevatorView(shaft.elevator,svg,options)
    elevators.appendChild(view.elem)
    shaft.elevator.listen({
      broken(reason: string) {
        send({
          tag: "ElevatorBroken",
          "shaft": shaft.id,
          "reason": reason
        })
      },
      floorPassed() {
        send({
          tag: "FloorPassed",
          "shaft": shaft.id
        })
      },
      stopped(): void {
        send({
          tag: "ElevatorStopped",
            "shaft": shaft.id
        })
      },
      buttonPressed(floor: number): void {
        send({
          tag: "ElevatorButtonPressed",
            "shaft": shaft.id,
            "floor": floor
        })
      },
      personEntered(): void {},
      moved(): void {},
      lightStateChanged(): void {}
    })
    shaft.elevator.door.listen({
      opened(): void {
        send({
          tag: "ElevatorDoorOpened",
            "shaft": shaft.id
        })
      },
      closed(): void {
        send({
          tag: "ElevatorDoorClosed",
            "shaft": shaft.id
        })
      },
      broken(reason: string) {
        send({
          tag: "Elev


ties)
            {
                var weather = await service.GetWeatherAsync(city, country, eHandler);
                if (weather != null)
                {
                    Console.WriteLine(weather.Time);
                }
            }
        }

        private class ExceptionHandler : IProgress<Exception>
        {
            #region IProgress implementation
            public void Report (Exception value)
            {
                var e = value;

                while (e != null)
                {
                    Console.WriteLine (e.Message);
                    e = e.InnerException;
                }
            }
            #endregion
        }
    }
}


ry>
        public void OnResume()
        {

        }

        /// <summary>
        /// 回发邮件
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="body">邮件内容</param>
        public void ReportMail(string subject, string body)
        {
            if (_reportBufferTimer > 0)
                return;

            _reportBufferTimer = _exceptionManager.ReportBufferTime;

            if (_exceptionManager.IsHandler)
            {
                if (_sender != null)
                {
                    _sender.Send(subject, body);
                }
            }
        }
        /// <summary>
        /// 清理所有异常信息
        /// </summary>
        public void ClearExceptionInfos()
        {
            Main.m_ReferencePool.Despawns(ExceptionInfos);
        }

        private void Handler(string logString, string stackTrace, LogType type)
        {
            if (type == LogType.Error || type == LogType.Exception || type == LogType.Assert)
            {
                ExceptionInfos.Add(Main.m_ReferencePool.Spawn<ExceptionInfo>().Fill(logString, stackTrace, type));

                OnException(logString, stackTrace, type);

                _logInfoBuilder.Clear();
                _logInfoBuilder.Append($"[time]:{DateTime.Now}\r\n\r\n");
                _logInfoBuilder.Append($"[type]:{type}\r\n\r\n");
                _logInfoBuilder.Append($"[message]:{logString}\r\n\r\n");
                _logInfoBuilder.Append($"[stack trace]:{stackTrace}\r\n\r\n");

#if UNITY_STANDALONE_WIN
                string logPath = $"{_logPath}/{DateTime.Now.ToString("yyyy_MM_dd HH_mm_ss_fff")}.log";
                File.AppendAllText(logPath, _logInfoBuilder.ToString(), Encoding.UTF8);

                if (_exceptionManager.IsEnableFeedback)
                {
                    if (File.Exists(_exceptionManager.FeedbackProgramPath))
                    {
                        ProcessStartInfo process = new ProcessStartInfo();
                        process.FileName = _exceptionManager.FeedbackProgramPath;
                        process.Arguments = $"\"{logPath}\"";
                        Process pro = new Process();
                        pro.StartInfo = process;
                        pro.Start();
                    }
                    else
                    {
                        File.AppendAllText(logPath, $"[feedback]:Doesn't find feedback program!path: {_exceptionManager.FeedbackProgramPath}\r\n", Encoding.UTF8);
                    }
                    Application.Quit();
                }
#endif
                if (_exceptionManager.IsEnableMailReport)
                {
                    ReportMail($"{Application.productName}.Exception.{DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss")}", _logInfoBuilder.ToString());
                }
            }
        }
        private void OnException(string logString, string stackTrace, LogType type)
        {
            Main.m_Event.Throw(Main.m_ReferencePool.Spawn<EventException>().Fill(logString, stackTrace, type));
        }
    }
}


	testcases := []struct {
		input, currentpath string
	}{
		{"_testdata/project/assets/app.js", "assets/app.js"},
		{"not/another/path/assets/app.js", "not/another/path/assets/app.js"},
	}
	w := createTestWatcher(t)
	for _, testcase := range testcases {
		assert.Equal(t, w.parsePath(testcase.input), testcase.currentpath)
	}
}

func TestIsEventType(t *testing.T) {
	expectedOps := []watcher.Op{watcher.Write, watcher.Remove, watcher.Rename}
	refutedOps := []watcher.Op{watcher.Chmod, watcher.Create, watcher.Move}

	for _, op := range expectedOps {
		assert.True(t, isEventType(op, expectedOps...), fmt.Sprintf("%v", op))
	}

	for _, op := range refutedOps {
		assert.False(t, isEventType(op, expectedOps...), fmt.Sprintf("%v", op))
	}
}

func TestFileWatcher_StopWatching(t *testing.T) {
	w := createTestWatcher(t)
	w.Stop()
	w.Watch()
	w.Stop()
}

func createTestWatcher(t *testing.T) *Watcher {
	e := &env.Env{
		Directory:    filepath.Join("_testdata", "project"),
		IgnoredFiles: []string{"config/"},
	}
	w, err := NewWatcher(e, filepath.Join("_testdata", "project", "config.yml"), map[string]string{})
	assert.Nil(t, err)
	return w
}

func createTestFilterHook(t *testing.T) watcher.FilterFileHookFunc {
	e := &env.Env{
		Directory:    filepath.Join("_testdata", "project"),
		IgnoredFiles: []string{"config/"},
	}
	hook, err := filterHook(e, filepath.Join("_testdata", "project", "config.yml"))
	assert.Nil(t, err)
	return hook
}
package toxiproxy_test

import (
	"flag"
	"net"
	"os"
	"testing"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/rs/zerolog"

	"github.com/Shopify/toxiproxy/v2"
	"github.com/Shopify/toxiproxy/v2/collectors"
	"github.com/Shopify/toxiproxy/v2/testhelper"
)

func NewTestProxy(name, upstream string) *toxiproxy.Proxy {
	log := zerolog.Nop()
	if flag.Lookup("test.v").DefValue == "true" {
		log = zerolog.New(os.Stdout).With().Caller().Timestamp().Logger()
	}
	srv := toxiproxy.NewServer(
		toxiproxy.NewMetricsContainer(prometheus.NewRegistry()),
		log,
	)
	srv.Metrics.ProxyMetrics = collectors.NewProxyMetricCollectors()
	proxy := toxiproxy.NewProxy(srv, name, "localhost:0", upstream)

	return proxy
}

func WithTCPProxy(
	t *testing.T,
	f func(proxy net.Conn, response chan []byte, proxyServer *toxiproxy.Proxy),
) {
	testhelper.WithTCPServer(t, func(upstream string, response chan []byte) {
		proxy := NewTestProxy("test", upstream)
		proxy.Start()

		conn := AssertProxyUp(t, proxy.Listen, true)

		f(conn, response, proxy)

		proxy.Stop()
	})
}

func AssertProxyUp(t *testing.T, addr string, up bool) net.Conn {
	conn, err := net.Dial("tcp", addr)
	if err != nil && up {
		t.Error("Expected proxy to be up:", err)
	} else if err == nil && !up {
		t.Error("Expected proxy to be down")
	}
	return conn
}
package toxiproxy_test

import (
	"bytes"
	"net"
	"testing"

	"github.com/Shopify/t


as_ref().expect("mmap buf consumed").as_slice()
    }
}

impl ReadableMemoryMap for TestMmap {}

impl WritableMemoryMap for TestMmap {
    fn flush(&self) -> io::Result<()> {
        Ok(())
    }
}

impl AsyncRead for TestFile {
    fn poll_read(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let new_read_pos = {
            let mut inner = self.inner.lock();
            let src = inner.buf.as_mut().expect("file buf consumed");

            let cap = buf.remaining();
            let pos = self.read_pos;
            let available = src.len() - pos;
            let n = cmp::min(cap, available);

            let to = pos + n;
            buf.put_slice(&src[pos..to]);
            to
        };

        self.read_pos = new_read_pos;

        Poll::Ready(Ok(()))
    }
}

impl AsyncWrite for TestFile {
    fn poll_write(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        if !self.is_writable {
            return Err(io_err_permission_denied()).into();
        }

        let mut inner = self.inner.lock();
        let dst = inner.buf.as_mut().expect("file buf consumed");
        dst.extend_from_slice(buf);

        Poll::Ready(Ok(buf.len()))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        if !self.is_writable {
            return Err(io_err_permission_denied()).into();
        }

        Poll::Ready(Ok(()))
    }

    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        if !self.is_writable {
            return Err(io_err_permission_denied()).into();
        }

        Poll::Ready(Ok(()))
    }
}

#[async_trait]
impl AsyncFile for TestFile {
    async fn metadata(&self) -> io::Result<Metadata> {
        let len = {
            let inner = self.inner.lock();
            inner.buf.as_ref().expect("file buf consumed").len()
        };

        Ok(Metadata { len: len as u64 })
    }

    async fn sync_all(&self) -> io::Result<()> {
        Ok(())
    }
}

// Inner state of the test filesystem.
#[derive(Debug, Default)]
struct FilesystemInner {
    files: HashMap<PathBuf, TestFile>,
}

impl FilesystemInner {
    fn open_file_writable(&mut self, path: &Path) -> TestFile {
        let file = self
            .files
            .entry(path.to_owned())
            .or_insert_with(TestFile::new);
        let mut new_file = file.clone();
        new_file.set_writable();

        new_file
    }

    fn open_file_writable_atomic(&mut self, path: &Path) -> Option<TestFile> {
        if self.files.contains_key(path) {
            None
        } else {
            let mut new_file = TestFile::new();
            new_file.set_writable();

            self.files.insert(path.to_owned(), new_file.clone());

            Some(new_file)
        }
    }

    fn open_file_readable(&mut self, path: &Path) -> Option<TestFile> {
        self.files.get(path).cloned().map(|mut f| {
            f.set_readable();
            f
        })
    }

    fn open_mmap


ME_WEIGHT + FLOAT_TYPE + "," +
            OutcomeEventsTable.COLUMN_NAME_SESSION_TIME + INT_TYPE +
            ");"

    const val SQL_CREATE_UNIQUE_OUTCOME_ENTRIES_V1 =
        "CREATE TABLE " + CachedUniqueOutcomeTable.TABLE_NAME_V1 + " (" +
            CachedUniqueOutcomeTable.ID + INTEGER_PRIMARY_KEY_TYPE + "," +
            CachedUniqueOutcomeTable.COLUMN_NAME_NOTIFICATION_ID + TEXT_TYPE + "," +
            CachedUniqueOutcomeTable.COLUMN_NAME_NAME + TEXT_TYPE +
            ");"
    const val SQL_CREATE_UNIQUE_OUTCOME_ENTRIES_V2 =
        "CREATE TABLE " + CachedUniqueOutcomeTable.TABLE_NAME_V2 + " (" +
            CachedUniqueOutcomeTable.ID + INTEGER_PRIMARY_KEY_TYPE + "," +
            CachedUniqueOutcomeTable.COLUMN_CHANNEL_INFLUENCE_ID + TEXT_TYPE + "," +
            CachedUniqueOutcomeTable.COLUMN_CHANNEL_TYPE + TEXT_TYPE + "," +
            CachedUniqueOutcomeTable.COLUMN_NAME_NAME + TEXT_TYPE +
            ");"
}
package com.onesignal.core.internal.config

import com.onesignal.common.modeling.Model
import org.json.JSONArray
import org.json.JSONObject

class ConfigModel : Model() {
    /**
     * Whether this config has been initialized with remote data.
     */
    var isInitializedWithRemote: Boolean
        get() = getBooleanProperty(::isInitializedWithRemote.name) { false }
        set(value) {
            setBooleanProperty(::isInitializedWithRemote.name, value)
        }

    /**
     * The current OneSignal application ID provided to the SDK.
     */
    var appId: String
        get() = getStringProperty(::appId.name)
        set(value) {
            setStringProperty(::appId.name, value)
        }

    /**
     * This device's push subscription ID.
     */
    var pushSubscriptionId: String?
        get() = getOptStringProperty(::pushSubscriptionId.name)
        set(value) {
            setOptStringProperty(::pushSubscriptionId.name, value)
        }

    /**
     * The API URL String.
     */
    var apiUrl: String
        get() = getStringProperty(::apiUrl.name) { "https://api.onesignal.com/" }
        set(value) {
            setStringProperty(::apiUrl.name, value)
        }

    /**
     * Whether the SDK requires privacy consent to send data to backend.
     */
    var consentRequired: Boolean?
        get() = getOptBooleanProperty(::consentRequired.name)
        set(value) {
            setOptBooleanProperty(::consentRequired.name, value)
        }

    /**
     * Whether the SDK has been given consent to privacy.
     */
    var consentGiven: Boolean?
        get() = getOptBooleanProperty(::consentGiven.name)
        set(value) {
            setOptBooleanProperty(::consentGiven.name, value)
        }

    /**
     * Whether location is shared.
     */
    var locationShared: Boolean
        get() = getBooleanProperty(::locationShared.name) { false }
        set(value) = setBooleanProperty(::locationShared.name, value)

    /**
     * Whether to disable the "GMS is missing" prompt to the user.
     */
    var disableGMSMissingPrompt: Boolean
        get() = getBooleanProperty(::disableGMSMissingPrompt.name) { false }
        set(value) {
            setBooleanProperty(::disableGMSMissingPrompt.name, value)
        }

    /**
     * Whether to disable the "GMS is missing" prompt to the user.


aftforge.common.util.ForgeDirection;

public class TileEntityMachinePress extends TileEntityMachineBase implements IGUIProvider {

	public int speed = 0; // speed ticks up once (or four times if preheated) when operating
	public static final int maxSpeed = 400; // max speed ticks for acceleration
	public static final int progressAtMax = 25; // max progress speed when hot
	public int burnTime = 0; // burn ticks of the loaded fuel, 200 ticks equal one operation

	public int press; // extension of the press, operation is completed if maxPress is reached
	public double renderPress; // client-side version of the press var, a double for smoother rendering
	public double lastPress; // for interp
	private int syncPress; // for interp
	private int turnProgress; // for interp 3: revenge of the sith
	public final static int maxPress = 200; // max tick count per operation assuming speed is 1
	boolean isRetracting = false; // direction the press is currently going
	private int delay; // delay between direction changes to look a bit more appealing

	public ItemStack syncStack;

	public TileEntityMachinePress() {
		super(4);
	}

	@Override
	public String getName() {
		return "container.press";
	}

	@Override
	public void updateEntity() {

		if(!worldObj.isRemote) {

			// Triggers the legacy monoblock fix
			if (worldObj.getBlockMetadata(xCoord, yCoord, zCoord) < 12) {
				worldObj.scheduleBlockUpdate(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord), 1);
			}

			boolean preheated = false;

			for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
				if(worldObj.getBlock(xCoord + dir.offsetX, yCoord + dir.offsetY, zCoord + dir.offsetZ) == ModBlocks.press_preheater) {
					preheated = true;
					break;
				}
			}

			boolean canProcess = this.canProcess();

			if((canProcess || this.isRetracting) && this.burnTime >= 200) {
				this.speed += preheated ? 4 : 1;

				if(this.speed > this.maxSpeed) {
					this.speed = this.maxSpeed;
				}
			} else {
				this.speed -= 1;
				if(this.speed < 0) {
					this.speed = 0;
				}
			}

			if(delay <= 0) {

				int stampSpeed = speed * progressAtMax / maxSpeed;

				if(this.isRetracting) {
					this.press -= stampSpeed;

					if(this.press <= 0) {
						this.isRetracting = false;
						this.delay = 5;
					}
				} else if(canProcess) {
					this.press += stampSpeed;

					if(this.press >= this.maxPress) {
						this.worldObj.playSoundEffect(this.xCoord, this.yCoord, this.zCoord, "hbm:block.pressOperate", getVolume(1.5F), 1.0F);
						ItemStack output = PressRecipes.getOutput(slots[2], slots[1]);
						if(slots[3] == null) {
							slots[3] = output.copy();
						} else {
							slots[3].stackSize += output.stackSize;
						}
						this.decrStackSize(2, 1);

						if(slots[1].getMaxDamage() != 0) {
							slots[1].setItemDamage(slots[1].getItemDamage() + 1);
							if(slots[1].getItemDamage


drive.peek_code(1) as usize + 1);
                },
                |drive| {
                    drive.state.repeat_stack.pop();
                    let child_ctx = drive.state.popped_context.unwrap();
                    drive.ctx_mut().has_matched = child_ctx.has_matched;
                },
            ),
            SreOpcode::MAX_UNTIL => Box::new(OpMaxUntil::default()),
            SreOpcode::MIN_UNTIL => Box::new(OpMinUntil::default()),
            SreOpcode::REPEAT_ONE => Box::new(OpRepeatOne::default()),
            SreOpcode::MIN_REPEAT_ONE => Box::new(OpMinRepeatOne::default()),
            SreOpcode::GROUPREF => once(|drive| general_op_groupref(drive, |x| x)),
            SreOpcode::GROUPREF_IGNORE => once(|drive| general_op_groupref(drive, lower_ascii)),
            SreOpcode::GROUPREF_LOC_IGNORE => {
                once(|drive| general_op_groupref(drive, lower_locate))
            }
            SreOpcode::GROUPREF_UNI_IGNORE => {
                once(|drive| general_op_groupref(drive, lower_unicode))
            }
            SreOpcode::GROUPREF_EXISTS => once(|drive| {
                let (group_start, group_end) = drive.state.get_marks(drive.peek_code(1) as usize);
                match (group_start, group_end) {
                    (Some(start), Some(end)) if start <= end => {
                        drive.skip_code(3);
                    }
                    _ => drive.skip_code(drive.peek_code(2) as usize + 1),
                }
            }),
            _ => {
                // TODO python expcetion?
                unreachable!("unexpected opcode")
            }
        }
    }
}

fn char_loc_ignore(code: u32, c: u32) -> bool {
    code == c || code == lower_locate(c) || code == upper_locate(c)
}

fn charset_loc_ignore(set: &[u32], c: u32) -> bool {
    let lo = lower_locate(c);
    if charset(set, c) {
        return true;
    }
    let up = upper_locate(c);
    up != lo && charset(set, up)
}

fn general_op_groupref<F: FnMut(u32) -> u32>(drive: &mut StackDrive, mut f: F) {
    let (group_start, group_end) = drive.state.get_marks(drive.peek_code(1) as usize);
    let (group_start, group_end) = match (group_start, group_end) {
        (Some(start), Some(end)) if start <= end => (start, end),
        _ => {
            drive.ctx_mut().has_matched = Some(false);
            return;
        }
    };
    let mut wdrive = WrapDrive::drive(*drive.ctx(), &drive);
    let mut gdrive = WrapDrive::drive(
        MatchContext {
            string_position: group_start,
            // TODO: cache the offset
            string_offset: drive.state.string.offset(0, group_start),
            ..*drive.ctx()
        },
        &drive,
    );
    for _ in group_start..group_end {
        if wdrive.at_end() || f(wdrive.peek_char()) != f(gdrive.peek_char()) {
            drive.ctx_mut()


(proposal.GetFeeHash().ToString()));

    this->setWindowTitle("Proposal details");
}

ProposalDetailDialog::~ProposalDetailDialog()
{
    delete ui;
}

void ProposalDetailDialog::openExplorer()
{
    QDesktopServices::openUrl(QUrl(QString::fromStdString("https://insight.smartcash.cc/tx/" + proposal.GetFeeHash().ToString())));
}

void ProposalDetailDialog::close()
{
    done(QDialog::Accepted);
}

void ProposalDetailDialog::copyProposalHash()
{
    GUIUtil::setClipboard(ui->hashLabel->text());
}

void ProposalDetailDialog::copySignature()
{
    GUIUtil::setClipboard(ui->signatureLabel->text());
}

void ProposalDetailDialog::copyTransactionHash()
{
    GUIUtil::setClipboard(ui->txLabel->text());
}

void ProposalDetailDialog::copyRawProposal()
{
    CDataStream ssProposal(SER_NETWORK, PROTOCOL_VERSION);
    ssProposal << static_cast<CProposal>(proposal);
    std::string strRawProposal = HexStr(ssProposal.begin(), ssProposal.end());
    GUIUtil::setClipboard(QString::fromStdString(strRawProposal));
}
// Copyright (c) 2018-2020 - The SmartCash Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif

#include "smartvoting.h"
#include "ui_smartvoting.h"
#include "smartproposal.h"
#include "smartrewards/rewards.h"

#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "txmempool.h"
#include "walletmodel.h"
#include "coincontrol.h"
#include "wallet/wallet.h"
#include "clientmodel.h"
#include "castvotesdialog.h"
#include "validation.h"
#include "voteaddressesdialog.h"
#include "specialtransactiondialog.h"

#include <boost/assign/list_of.hpp> // for 'map_list_of()'

#include <QMenu>
#include <QMessageBox>
#include <QSortFilterProxyModel>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QScrollBar>
#include <QDateTime>

const int nRefreshLockSeconds = 120;
const int nForceRefreshSeconds = 300;
static int nLastRefreshTime = 0;

struct QSmartVortingField
{
    QString label;
    QString address;
    CAmount balance;

    QSmartVortingField() : label(QString()), address(QString()),
                          balance(0){}
};

SmartVotingPage::SmartVotingPage(const PlatformStyle *platformStyle, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SmartVotingPage),
    platformStyle(platformStyle),
    walletModel(0)
{
    ui->setupUi(this);

    votingManager = new SmartVotingManager();

    connect(votingManager, SIGNAL(proposalsUpdated(const std::string&)),this,SLOT(proposalsUpdated(const std::string&)));
    connect(votingManager, SIGNAL(addressesUpdated()), this, SLOT(updateUI()));
    connect(ui->selectAddressesButton, SIGNAL(clicked()),this,SLOT(selectAddresses()));
    connect(ui->castVotesButton, SIGNAL(clicked()),this,SLOT(castVotes()));
    connect(ui->refreshButton, SIGNAL(clicked()),this,SLOT(refreshProposals()));
    connect(ui->scrollArea->verticalScrollBar(), SIGNAL(valueChanged(int)),this,SLOT(scrollChanged(int)));
    connect(&lockTimer, SIGNAL(timeout()), t


 will not return response and decrease reliabilty, request buffer of 1 is good for most cases
    pub async fn get_setting_infos(&self) -> Result<Vec<SettingInfo>, &str> {
        if &self.core.buff_size() == &0 {
            return Err("can't read response when buff_size is 0")
        }

        println!("describe pg groups"); // TODO: write in debug flag
        let pg_settings = self.get_pg_settings().await?;

        println!("found {} groups", pg_settings.len());
        let setting_ids: Vec<u16> = pg_settings
            .iter()
            .flat_map(|pg_s| (pg_s.start_id..=pg_s.end_id).map(u16::from).collect::<Vec<u16>>())
            .collect();

        let setting_info_futures = setting_ids
            .iter()
            .map(|id| self.get_setting_info_by_id(&id));

        return try_join_all(setting_info_futures).await;
    }

    // TODO: return iteratable stream here
    pub async fn get_setting_infos_by_names(&self, names: Vec<&String>) -> Result<Vec<SettingInfo>, &str> {
        if &self.core.buff_size() == &0 {
            return Err("can't read response when buff_size is 0")
        }

        let setting_info_futures = names
            .iter()
            .map(|name| self.get_setting_info_by_name(&name));

        return try_join_all(setting_info_futures).await;
    }

    async fn _request_setting_info_by_id(&self, id: &u16) -> Result<(), &str> {
        let payload = MspSettingInfoRequest {
            null: 0,
            id: *id,
        };

        return self._request_setting_info(payload.pack().to_vec()).await;
    }

    async fn _request_setting_info_by_name(&self, name: &str) -> Result<(), &str> {
        let mut payload = name.as_bytes().to_vec();
        payload.push(b'\0');
        return self._request_setting_info(payload).await;
    }

    async fn _request_setting_info(&self, id: Vec<u8>) -> Result<(), &str> {
        let packet = MspPacket {
            cmd: MspCommandCode::MSP2_COMMON_SETTING_INFO as u16,
            direction: MspPacketDirection::ToFlightController,
            data: id,
        };

        return select! {
            _ = self.core.write(packet).fuse() => Ok(()),
            e_res = self.core.error().fuse() => {
                eprintln!("{:?}", e_res);
                Err("failed to requests setting_info")
            },
        };
    }

    async fn _receive_setting_info(&self) -> Result<SettingInfo, &str> {
        let ack_rec = self.subscribe(MspCommandCode::MSP2_COMMON_SETTING_INFO as u16, self.core.buff_size()).await;
        let payload = select! {
            p_res = ack_rec.recv().fuse() => {
                match p_res {
                    Ok(r) => r,
                    Err(_) => return Err("failed to get setting info, channel closed"),
                }
            },
            e_res = self.core.error().fuse() => {
                eprintln!("{:?}", e_res);
                return Err("failed to get setting info");
            },
        };

        let name = Msp::str_from_u8_nul_utf8(&payload).unwrap();
        let len = MspSettingInfo::packed_bytes();
        let mut index = name.len() + 1;
        let setting_info = MspSettingInfo::unpack_from_slice(&payload[index..index + len]).expect("Failed


        packages=packages,
                use_session_imports=imports is None,
                _ast=ast,
                _ast_id=ast_id,
            )

            if type(func) is tuple:  # update file registration
                module_name = self._import_file(func[0], udf_name=udf_name)
                self._registry[udf_name].func = (module_name, func[1])

            if imports is not None:
                for _import in imports:
                    if type(_import) is str:
                        self._import_file(_import, udf_name=udf_name)
                    else:
                        local_path, import_path = _import
                        self._import_file(local_path, import_path, udf_name=udf_name)

            return self._registry[udf_name]


			}
			log.Fatal(err)
		}
		rm, err := icmp.ParseMessage(1, rb[:n])
		if err != nil {
			log.Fatal(err)
		}
		rtt := time.Since(begin)

		// In the real world you need to determine whether the
		// received message is yours using ControlMessage.Src,
		// ControlMessage.Dst, icmp.Echo.ID and icmp.Echo.Seq.
		switch rm.Type {
		case ipv4.ICMPTypeTimeExceeded:
			names, _ := net.LookupAddr(peer.String())
			fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, cm)
		case ipv4.ICMPTypeEchoReply:
			names, _ := net.LookupAddr(peer.String())
			fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, cm)
			return
		default:
			log.Printf("unknown ICMP message: %+v\n", rm)
		}
	}
}

func ExampleRawConn_advertisingOSPFHello() {
	c, err := net.ListenPacket("ip4:89", "0.0.0.0") // OSPF for IPv4
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	r, err := ipv4.NewRawConn(c)
	if err != nil {
		log.Fatal(err)
	}

	en0, err := net.InterfaceByName("en0")
	if err != nil {
		log.Fatal(err)
	}
	allSPFRouters := net.IPAddr{IP: net.IPv4(224, 0, 0, 5)}
	if err := r.JoinGroup(en0, &allSPFRouters); err != nil {
		log.Fatal(err)
	}
	defer r.LeaveGroup(en0, &allSPFRouters)

	hello := make([]byte, 24) // fake hello data, you need to implement this
	ospf := make([]byte, 24)  // fake ospf header, you need to implement this
	ospf[0] = 2               // version 2
	ospf[1] = 1               // hello packet
	ospf = append(ospf, hello...)
	iph := &ipv4.Header{
		Version:  ipv4.Version,
		Len:      ipv4.HeaderLen,
		TOS:      0xc0, // DSCP CS6
		TotalLen: ipv4.HeaderLen + len(ospf),
		TTL:      1,
		Protocol: 89,
		Dst:      allSPFRouters.IP.To4(),
	}

	var cm *ipv4.ControlMessage
	switch runtime.GOOS {
	case "darwin", "linux":
		cm = &ipv4.ControlMessage{IfIndex: en0.Index}
	default:
		if err := r.SetMulticastInterface(en0); err != nil {
			log.Fatal(err)
		}
	}
	if err := r.WriteTo(iph, ospf, cm); err != nil {
		log.Fatal(err)
	}
}
// go generate gen.go
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT

package ipv4

// Internet Control Message Protocol (ICMP) Parameters, Updated: 2013-04-19
const (
	ICMPTypeEchoReply              ICMPType = 0  // Echo Reply
	ICMPTypeDestinationUnreachable ICMPType = 3  // Destination Unreachable
	ICMPTypeRedirect               ICMPType = 5  // Redirect
	ICMPTypeEcho                   ICMPType = 8  // Echo
	ICMPTypeRouterAdvertisement    ICMPType = 9  // Router Advertisement
	ICMPTypeRouterSolicitation     ICMPType = 10 // Router Solicitation
	ICMPTypeTimeE


存储重建。物化视图永远不会被应用程序直接更新，所以它是一个专门的缓存。

当视图的源数据更改时，必须更新视图以包含新信息。可以设置为自动更新，或者在系统检测到对原始数据的更改更新。在某些情况下，可能需要手动重新生成视图。下图是如何使用物化视图模式的例子。
![](https://docs.microsoft.com/en-us/azure/architecture/patterns/_images/materialized-view-pattern-diagram.png)

## 问题和注意事项

在决定如何实现这种模式时，请考虑以下几点：

* 如何以及何时更新视图。理想情况下，它将会响应于指示源数据更改的事件而重新生成，但是如果源数据快速更改，这可能会导致过多的开销。或者，考虑使用计划任务，外部触发器或手动操作来重新生成视图。

* 在某些系统中，例如当使用事件源模式来维护只修改数据的事件时，物化视图是必需的。通过检查所有事件来确定当前状态来预先填充视图可能是从事件存储库获取信息的唯一方法。如果不使用事件溯源，则需要考虑物化视图是否有用。物化视图往往是专门为一个或少量的查询定制的。如果使用了许多查询，物化视图会导致不可接受的存储容量要求和存储成本。

* 考虑生成视图时的数据一致性以及更新视图（如果按计划进行）时对数据一致性的影响。如果源数据在生成视图时发生变化，则视图中的数据副本将不会与原始数据完全一致。

* 考虑将在哪里存储视图。该视图不必与原始数据位于同一存储或分区中。它可以是几个不同分区组合的子集。

* 视图如果丢失可以重建。因此，如果视图是暂时的，并且仅用于通过反映数据的当前状态来提高查询性能，或者为了提高可伸缩性，则可以将其存储在缓存中或不太可靠的位置。

* 在定义物化视图时，根据现有数据项的计算或转换，查询中传递的值或适当时组合这些值，通过向其添加数据项或列来最大化其值。

* 在存储机制支持的情况下，考虑索引物化视图以进一步提高性能。大多数关系数据库都支持索引视图，而基于Apache Hadoop的大数据解决方案也是如此。

## 何时使用该模式

这种模式在以下情况下很有用

* 对难以直接查询的数据创建物化视图，或者非常复杂的查询才能提取的，以规范化，半结构化或非结构化方式存储的数据。
* 创建可显


_split);
        splitidx = (int)(w->wsplits.size()-1);
    }

    return splitidx;
}

void DTreesImpl::calcValue( int nidx, const vector<int>& _sidx )
{
    WNode* node = &w->wnodes[nidx];
    int i, j, k, n = (int)_sidx.size(), cv_n = params.getCVFolds();
    int m = (int)classLabels.size();

    cv::AutoBuffer<double> buf(std::max(m, 3)*(cv_n+1));

    if( cv_n > 0 )
    {
        size_t sz = w->cv_Tn.size();
        w->cv_Tn.resize(sz + cv_n);
        w->cv_node_risk.resize(sz + cv_n);
        w->cv_node_error.resize(sz + cv_n);
    }

    if( _isClassifier )
    {
        // in case of classification tree:
        //  * node value is the label of the class that has the largest weight in the node.
        //  * node risk is the weighted number of misclassified samples,
        //  * j-th cross-validation fold value and risk are calculated as above,
        //    but using the samples with cv_labels(*)!=j.
        //  * j-th cross-validation fold error is calculated as the weighted number of
        //    misclassified samples with cv_labels(*)==j.

        // compute the number of instances of each class
        double* cls_count = buf.data();
        double* cv_cls_count = cls_count + m;

        double max_val = -1, total_weight = 0;
        int max_k = -1;

        for( k = 0; k < m; k++ )
            cls_count[k] = 0;

        if( cv_n == 0 )
        {
            for( i = 0; i < n; i++ )
            {
                int si = _sidx[i];
                cls_count[w->cat_responses[si]] += w->sample_weights[si];
            }
        }
        else
        {
            for( j = 0; j < cv_n; j++ )
                for( k = 0; k < m; k++ )
                    cv_cls_count[j*m + k] = 0;

            for( i = 0; i < n; i++ )
            {
                int si = _sidx[i];
                j = w->cv_labels[si]; k = w->cat_responses[si];
                cv_cls_count[j*m + k] += w->sample_weights[si];
            }

            for( j = 0; j < cv_n; j++ )
                for( k = 0; k < m; k++ )
                    cls_count[k] += cv_cls_count[j*m + k];
        }

        for( k = 0; k < m; k++ )
        {
            double val = cls_count[k];
            total_weight += val;
            if( max_val < val )
            {
                max_val = val;
                max_k = k;
            }
        }

        node->class_idx = max_k;
        node->value = classLabels[max_k];
        node->node_risk = total_weight - max_val;

        for( j = 0; j < cv_n; j++ )
        {
            double sum_k = 0, sum = 0, max_val_k = 0;
            max_val = -1; max_k = -1;

            for( k = 0; k < m; k++ )
            {
                double val_k = cv_cls_count[j*m + k];
                double val = cls_count[k] - val_k;
                sum_k += val_k;
                sum += val;
                if( max_val < val )
                {
                    max_val = val;
                    max_val_k = val_k;


es=T_2m1['data'].values-T_2m2['data'].values
# set map extent
    if(area != None):
        south_China_sea=False

    if(area != None):
        cntr_pnt,zoom_ratio=utl.get_map_area(area_name=area)

    map_extent=[0,0,0,0]
    map_extent[0]=cntr_pnt[0]-zoom_ratio*1*map_ratio
    map_extent[1]=cntr_pnt[0]+zoom_ratio*1*map_ratio
    map_extent[2]=cntr_pnt[1]-zoom_ratio*1
    map_extent[3]=cntr_pnt[1]+zoom_ratio*1

    delt_x=(map_extent[1]-map_extent[0])*0.2
    delt_y=(map_extent[3]-map_extent[2])*0.1

#+ to solve the problem of labels on all the contours
    mask1 = (dTmx_2m['lon'] > map_extent[0]-delt_x) & (dTmx_2m['lon'] < map_extent[1]+delt_x) & (dTmx_2m['lat'] > map_extent[2]-delt_y) & (dTmx_2m['lat'] < map_extent[3]+delt_y)
    dTmx_2m=dTmx_2m.where(mask1,drop=True)

#- to solve the problem of labels on all the contours
    dTmx2=xr.DataArray(np.squeeze(dTmx_2m['data'].values,axis=0),name='data',
                    coords={'time':('time',[dTmx_2m['forecast_reference_time'].values]),
                            'fhour':('time',[fhour]),
                            'lat':('lat',dTmx_2m['lat'].values),
                            'lon':('lon',dTmx_2m['lon'].values)
                            },
                    dims=('time','lat','lon'),
                    attrs={'model_name':'中央气象台中短期指导',
                           'var_name':'2米最低温度24小时变温',
                           'vhours':24})

    draw_SCMOC.draw_dT2m(dTmx2,map_extent=map_extent,south_China_sea=south_China_sea,**kargws)


_per_cycle == 0)) {

            // ----------------------- Tests for each cycle of the cycle -----------------------
            println!("run cycle tests: {}, level: {:?}", cycle, level);

            test_rpc_compare_json(&format!("{}/{}/{}?cycle={}", "chains/main/blocks", level, "helpers/endorsing_rights", cycle)).await;
            test_rpc_compare_json(&format!("{}/{}/{}?cycle={}", "chains/main/blocks", level, "helpers/endorsing_rights", cycle+preserved_cycles)).await;
            test_rpc_compare_json(&format!("{}/{}/{}?cycle={}", "chains/main/blocks", level, "helpers/endorsing_rights", std::cmp::max(0, cycle-2) )).await;

            test_rpc_compare_json(&format!("{}/{}/{}?all&cycle={}", "chains/main/blocks", level, "helpers/baking_rights", cycle)).await;
            test_rpc_compare_json(&format!("{}/{}/{}?all&cycle={}", "chains/main/blocks", level, "helpers/baking_rights", cycle+preserved_cycles)).await;
            test_rpc_compare_json(&format!("{}/{}/{}?all&cycle={}", "chains/main/blocks", level, "helpers/baking_rights", std::cmp::max(0, cycle-2) )).await;
            //test_rpc_compare_json(&format!("{}/{}/{}?cycle={}&delegate={}", "chains/main/blocks", &prev_block, "helpers/endorsing_rights", cycle, "tz1YH2LE6p7Sj16vF6irfHX92QV45XAZYHnX")).await;

            // known ocaml node bugs
            // - endorsing rights: for cycle 0, when requested cycle 4 there should be cycle check error:
            //  [{"kind":"permanent","id":"proto.005-PsBabyM1.seed.unknown_seed","oldest":0,"requested":4,"latest":3}]
            //  instead there is panic on
            //  [{"kind":"permanent","id":"proto.005-PsBabyM1.context.storage_error","missing_key":["cycle","4","last_roll","1"],"function":"get"}]
            // if cycle==0 {
            //     let block_level_1000 = "BM9xFVaVv6mi7ckPbTgxEe7TStcfFmteJCpafUZcn75qi2wAHrC";
            //     test_rpc_compare_json(&format!("{}/{}/{}?cycle={}", "chains/main/blocks", block_level_1000, "helpers/endorsing_rights", 4)).await;
            // }
            // - endorsing rights: if there is last level of cycle is not possible to request cycle - PERSERVED_CYCLES
            // test_rpc_compare_json(&format!("{}/{}/{}?cycle={}", "chains/main/blocks", &prev_block, "helpers/endorsing_rights", std::cmp::max(0, cycle-PERSERVED_CYCLES) )).await;

            // ------------------- End of tests for each cycle of the cycle --------------------

            if cycle_loop_counter == MAX_CYCLE_LOOPS*2 {
                break
            }
            cycle_loop_counter += 1;
        }
    }
}

async fn test_rpc_compare_json(rpc_path: &str) {
    // print the asserted path, to know which one errored in case of an error, use --nocapture
    println!("Checking: {}", rpc_path);
    let ocaml_json = get_rpc_as_json(NodeType::Ocaml, rpc_path).await.unwrap();
    let tezedge_json = get_rpc_as_json(NodeType::Tezedge, rpc


ND_MORE.ordinal
							== HASH_AND_MORE.ordinal)
				assert(TupleDescriptor.IntegerSlots.HASH_OR_ZERO.isSamePlaceAs(
					HASH_OR_ZERO))
			}
		}
	}

	/**
	 * The layout of object slots for my instances.
	 */
	enum class ObjectSlots : ObjectSlotsEnum
	{
		/**
		 * The basis tuple of which this is a subrange.  The basis tuple must be
		 * flat -- it may not be another subrange tuple, nor may it be a tree
		 * tuple.
		 */
		ORIGIN_TUPLE
	}

	override fun o_AppendCanDestroy(
		self: AvailObject,
		newElement: A_BasicObject,
		canDestroy: Boolean): A_Tuple
	{
		// Fall back to concatenating a singleton.
		if (!canDestroy)
		{
			self.makeImmutable()
		}
		val singleton = tuple(newElement)
		return self.concatenateWith(singleton, canDestroy)
	}

	// Answer maximum integer value so that any other representation
	// for comparison is used in favor of a Reverse Tuple representation.
	override fun o_BitsPerEntry(self: AvailObject): Int = Int.MAX_VALUE

	override fun o_ChildAt(self: AvailObject, childIndex: Int): A_Tuple
	{
		if (!self.descriptor().isShared)
		{
			val treeTuple = internalTreeReverse(self[ORIGIN_TUPLE])
			treeTuple.setHashOrZero(self[HASH_OR_ZERO])
			self.becomeIndirectionTo(treeTuple)
			return treeTuple.childAt(childIndex)
		}
		// Object is shared so it cannot change to an indirection.  Instead, we
		// need to return the reverse of the child one level down at the
		// opposite end of the tree from the childIndex.
		val adjustedSubscript = self.childCount + 1 - childIndex
		return self[ORIGIN_TUPLE]
			.childAt(adjustedSubscript)
			.tupleReverse()
	}

	override fun o_ChildCount(self: AvailObject): Int =
		self[ORIGIN_TUPLE].childCount

	override fun o_CompareFromToWithStartingAt(
		self: AvailObject,
		startIndex1: Int,
		endIndex1: Int,
		anotherObject: A_Tuple,
		startIndex2: Int): Boolean
	{
		var index = startIndex1
		var index2 = startIndex2
		while (index <= endIndex1)
		{
			if (!self.tupleAt(index).equals(anotherObject.tupleAt(index2)))
			{
				return false
			}
			index++
			index2++
		}
		return true
	}

	override fun o_ConcatenateWith(
		self: AvailObject,
		otherTuple: A_Tuple,
		canDestroy: Boolean): A_Tuple
	{
		// If the receiver tuple is empty return the otherTuple.
		val size1 = self.tupleSize
		if (size1 == 0)
		{
			if (!canDestroy)
			{
				otherTuple.makeImmutable()
			}
			return otherTuple
		}
		// If otherTuple is empty return the receiver tuple, object.
		val size2 = otherTuple.tupleSize
		if (size2 == 0)
		{
			if (!canDestroy)
			{
				self.makeImmutable()
			}
			return self
		}
		val newSize = size1 + size2
		if (newSize <= maximumCopySize)
		{
			// Copy the objects.
			val unreversedFirstTuple: A_Tuple =
				self[ORIGIN_TUPLE]
			return generateObjectTupleFrom(newSize)
			{
				if (it <= size1)
				{
					unreversedFirstTuple.tupleAt(size1 + 1 - it)
				}
				else
				{
					otherTuple.tupleAt(it - size1)
				}
			}
		}
		if (!canDestroy)
		{
			self.makeImmutable()
			otherTuple.makeImmutable()
		}
		if (self[ORIGIN_TUPLE].treeTupleLevel == 0)
		{
			return if (otherTuple.treeTupleLevel == 0)
			{
				TreeTupleDescriptor.createTwoPartTreeTuple(
					self, otherTuple, 1, 0)
			}
			else TreeTupleDescriptor.