tware; you can redistribute
 * it and/or modify it under the terms of the 'WiEngine' license with
 * the additional provision that 'WiEngine' must be credited in a manner
 * that can be be observed by end users, for example, in the credits or during
 * start up. (please find WiEngine logo in sdk's logo folder)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.wiyun.engine.tests.other;

import com.wiyun.engine.R;
import com.wiyun.engine.WiEngineTestActivity;
import com.wiyun.engine.nodes.Director;
import com.wiyun.engine.nodes.Label;
import com.wiyun.engine.nodes.Layer;
import com.wiyun.engine.nodes.Node;
import com.wiyun.engine.nodes.Sprite;
import com.wiyun.engine.nodes.Node.IPositionListener;
import com.wiyun.engine.types.WYSize;

public class NodePhysicsTest extends WiEngineTestActivity {
	@Override
	protected Layer createLayer() {
		return new MyLayer();
	}

    class MyLayer extends Layer implements IPositionListener {
    	private Label mLabel;

        public MyLayer() {
        	Sprite sprite = Sprite.make(R.drawable.grossini);
        	sprite.setVelocity(100, 100);
        	sprite.setAcceleration(100, 100);
        	sprite.setPositionListener(this);
        	addChild(sprite);

            // hint label
        	WYSize s = Director.getInstance().getWindowSize();
            mLabel = Label.make("callback display label", 20);
            mLabel.setPosition(s.width / 2, 100);
            addChild(mLabel);
        }

		public void onPositionChanged(int nodePointer) {
			Node node = Node.from(nodePointer);
			WYSize s = Director.getInstance().getWindowSize();
			float px = node.getPositionX();
			float py = node.getPositionY();
			if(px > s.width || py > s.height) {
				node.setVelocity(-100, -100);
				node.setAcceleration(-100, -100);
			} else if(px < 0 || py < 0) {
				node.setVelocity(100, 100);
				node.setAcceleration(100, 100);
			}

			mLabel.setText(String.format("pos: %.1f, %.1f", px, py));
		}
    }
}
/*
 * Copyright (c) 2010 WiYun Inc.
 * Author: luma(stubma@gmail.com)
 *
 * For all entities this program is free software; you can redistribute
 * it and/or modify it under the terms of the 'WiEngine' license with
 * the additional provision that 'WiEngine' must be credited in a manner
 * that can be be observed by end users, for example, in the credits or during
 * start up. (please


ce],
            charcommand[snippet],
            n > 2 and leftcommand[advance] or nil,
            n > 2 and charcommand[snippet] or nil,
        },
    }
end

virtualcharacters[0x2A75] = function(data) return equals(data,0x2A75,0x003D, 1/5,2) end -- ==
virtualcharacters[0x2A76] = function(data) return equals(data,0x2A76,0x003D, 1/5,3) end -- ===
virtualcharacters[0x2980] = function(data) return equals(data,0x2980,0x007C,-1/8,3) end -- |||

-- addextra(0xFE941) -- EXTREMELY IDENTICAL TO
--
-- virtualcharacters[0xFE941] = function(data) -- this character is only needed for mathpairs
--     local characters = data.target.characters
--     local parameters = data.target.parameters
--     local basechar   = characters[0x003D]
--     local width      = basechar.width or 0
--     local height     = basechar.height or 0
--     local depth      = basechar.depth or 0
--     return {
--         unicode   = 0xFE941,
--         width     = width,
--         height    = height,         -- we cheat (no time now)
--         depth     = depth,          -- we cheat (no time now)
--         commands  = {
--             upcommand[height/2], -- sort of works
--             charcommand[0x003D],
--             leftcommand[width],
--             downcommand[height],     -- sort of works
--             charcommand[0x003D],
--         },
--     }
-- end

-- lucida needs this

virtualcharacters[0x305] = function(data)
    local target = data.target
    local height = target.parameters.xheight/8
    local width  = target.parameters.emwidth/2
    local depth  = height
    local used   = 0.8 * width
    return {
        width    = width,
        height   = height,
        depth    = depth,
        commands = { { "rule", height, width } },
        horiz_variants = {
            {
              advance   = width,
              ["end"]   = used,
              glyph     = 0x305,
              start     = 0,
            },
            {
              advance   = width,
              ["end"]   = 0,
              extender  = 1,
              glyph     = 0x305,
              start     = used,
            },
        }
    }
end

local function threedots(data,shift)
    local characters = data.target.characters
    local parameters = data.target.parameters
    local periodchar = characters[0x002E]
    local pluschar   = characters[0x002B]
    local period     = charcommand[0x002E]
    local periodwd   = periodchar.width  or 0
    local periodht   = periodchar.height or 0
    local perioddp   = periodchar.depth or 0
    local offset     = 0
    if shift then
        local plusht = pluschar.height or 0
        local plusdp = pluschar.depth or 0
        local axis   = floor((plusdp + plusht)/2) - plusdp
        offset   = axis - floor(periodht/2)
        periodht = axis + floor(periodht/2)
    end
    return {
        width    = 3*periodwd,
        height   = periodht,
        depth    = 0,
        commands = { upcommand[offset], period, period, period }
    }
end

virtualcharacters[0x2026] = function(data) return threedots(data,false) end virtualforced[0x2026] = true
virtualcharacters[0x22EF] = function(data) return threedots(data, true) end virtualforced[0x22EF] = true


Selection());
		editLogin.setEnabled(checkUseProxy.getSelection() && checkRequireAuth.getSelection());
		editPassword.setEnabled(checkUseProxy.getSelection() && checkRequireAuth.getSelection());
	}

   /**
    * @see org.netxms.nxmc.base.propertypages.PropertyPage#applyChanges(boolean)
    */
   @Override
   protected boolean applyChanges(boolean isApply)
	{
		final IPreferenceStore ps = getPreferenceStore();

		ps.setValue("HTTP_PROXY_ENABLED", checkUseProxy.getSelection());
		ps.setValue("HTTP_PROXY_SERVER", editProxyServer.getText());
		ps.setValue("HTTP_PROXY_PORT", editProxyPort.getText());
		ps.setValue("HTTP_PROXY_EXCLUSIONS", editExclusions.getText().replaceAll("\\,", "|"));
		ps.setValue("HTTP_PROXY_AUTH", checkRequireAuth.getSelection());
		ps.setValue("HTTP_PROXY_LOGIN", editLogin.getText());
		ps.setValue("HTTP_PROXY_PASSWORD", editPassword.getText());

		if (checkUseProxy.getSelection())
		{
			System.setProperty("http.proxyHost", ps.getString("HTTP_PROXY_SERVER"));
			System.setProperty("http.proxyPort", ps.getString("HTTP_PROXY_PORT"));
			System.setProperty("http.noProxyHosts", ps.getString("HTTP_PROXY_EXCLUSIONS"));
         System.setProperty("https.proxyHost", ps.getString("HTTP_PROXY_SERVER"));
         System.setProperty("https.proxyPort", ps.getString("HTTP_PROXY_PORT"));
         System.setProperty("https.noProxyHosts", ps.getString("HTTP_PROXY_EXCLUSIONS"));

			if (checkRequireAuth.getSelection())
			{
				Authenticator.setDefault(new Authenticator() {
					@Override
					protected PasswordAuthentication getPasswordAuthentication()
					{
						return new PasswordAuthentication(ps.getString("HTTP_PROXY_LOGIN"), ps.getString("HTTP_PROXY_PASSWORD").toCharArray());
					}
				});
			}
			else
			{
				Authenticator.setDefault(null);
			}
		}
		else
		{
			System.clearProperty("http.proxyHost");
			System.clearProperty("http.proxyPort");
			System.clearProperty("http.noProxyHosts");
         System.clearProperty("https.proxyHost");
         System.clearProperty("https.proxyPort");
         System.clearProperty("https.noProxyHosts");
			Authenticator.setDefault(null);
		}

      return true;
	}
}
/*******************************************************************************
 * Copyright (c) 2004, 2015 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.netxms.nxmc.base.widgets;

import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.ACC;
import org.eclipse.swt.accessibility.Accessible;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleControlAdapter;
import org.eclipse.swt.accessibility.AccessibleControlEvent;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.netxms.nxmc.tools.ColorConverter;
import org.netxms.nxmc.tools.WidgetHelper;

/**
 * Hyperlink is a concrete implementation of the abstract base class that draws text in th


validate() {
        var l_s_username = document.getElementById('l_s_username').value;
        var l_s_card = document.getElementById('l_s_card').value;
        var l_s_phone = document.getElementById('l_s_phone').value;
        var l_s_grade = document.getElementById('l_s_grade').value;
        var l_s_class = document.getElementById('l_s_class').value;
        var l_begintime = document.getElementById('l_begintime').value;
        var l_endtime = document.getElementById('l_endtime').value;
        var l_address = document.getElementById('l_address').value;
        var l_cause = document.getElementById('l_cause').value;
        if (l_s_card == ''){
            document.getElementById('state').innerHTML = '学号未填写';
        }else if (l_s_username == ''){
            document.getElementById('state').innerHTML = '姓名未填写';
        }else if (l_s_phone == ''){
            document.getElementById('state').innerHTML = '手机号未填写';
        }else if (l_s_grade == ''){
            document.getElementById('state').innerHTML = '级别未选择';
        }else if (l_s_class == ''){
            document.getElementById('state').innerHTML = '班级未选择';
        }else if (l_begintime == ''){
            document.getElementById('state').innerHTML = '开始时间未选择';
        }else if (l_endtime == ''){
            document.getElementById('state').innerHTML = '结束时间未选择';
        }else if (l_address == ''){
            document.getElementById('state').innerHTML = '前往地点未填写';
        }else if (l_cause == ''){
            document.getElementById('state').innerHTML = '请假原因未填写';
        }else {
            document.getElementById('my_form').submit();
        }
    }

</script>

    <button class="am-topbar-btn am-topbar-toggle am-btn am-btn-sm am-btn-success am-show-sm-only" data-am-collapse="{target: '#topbar-collapse'}">导航切换 </button>

                    {$header_name}

 退出


=e.plugins[r].schema["jupyter.lab.menus"])===null||h===void 0?void 0:h.main)!==null&&p!==void 0?p:[];if(!u.JSONExt.deepEqual(o,f)){if(c[r]){await t(a)}else{c[r]=u.JSONExt.deepCopy(f);const e=l.SettingRegistry.reconcileMenus(f,m,false,false).filter((e=>!e.disabled)).map((e=>{var t;return{...e,items:l.SettingRegistry.filterDisabledItems((t=e.items)!==null&&t!==void 0?t:[])}}));s.MenuFactory.updateMenus(g,e,i).forEach((e=>{n(e)}))}}}}))}e.loadSettingsMenu=n})(D||(D={}))},83344:(e,t,n)=>{"use strict";var i=n(32902);var s=n(34849);var o=n(79536);var r=n(90516);var a=n(82401);var l=n(59240);var d=n(74518)},97630:(e,t,n)=>{"use strict";n.r(t);n.d(t,{EditMenu:()=>a,FileMenu:()=>l,HelpMenu:()=>d,IMainMenu:()=>_,KernelMenu:()=>c,MainMenu:()=>g,RunMenu:()=>h,SettingsMenu:()=>u,TabsMenu:()=>p,ViewMenu:()=>m});var i=n(60243);var s=n(58740);var o=n(76906);var r=n(3887);class a extends i.RankedMenu{constructor(e){super(e);this.undoers={redo:new r.SemanticCommand,undo:new r.SemanticCommand};this.clearers={clearAll:new r.SemanticCommand,clearCurrent:new r.SemanticCommand};this.goToLiners=new r.SemanticCommand}}class l extends i.RankedMenu{constructor(e){super(e);this.quitEntry=false;this.closeAndCleaners=new r.SemanticCommand;this.consoleCreators=new r.SemanticCommand}get newMenu(){var e,t;if(!this._newMenu){this._newMenu=(t=(e=(0,s.find)(this.items,(e=>{var t;return((t=e.submenu)===null||t===void 0?void 0:t.id)==="jp-mainmenu-file-new"})))===null||e===void 0?void 0:e.submenu)!==null&&t!==void 0?t:new i.RankedMenu({commands:this.commands})}return this._newMenu}dispose(){var e;(e=this._newMenu)===null||e===void 0?void 0:e.dispose();super.dispose()}}class d extends i.RankedMenu{constructor(e){super(e);this.getKernel=new r.SemanticCommand}}class c extends i.RankedMenu{constructor(e){super(e);this.kernelUsers={changeKernel:new r.SemanticCommand,clearWidget:new r.SemanticCommand,interruptKernel:new r.SemanticCommand,reconnectToKernel:new r.SemanticCommand,restartKernel:new r.SemanticCommand,shutdownKernel:new r.SemanticCommand}}}class h extends i.RankedMenu{constructor(e){super(e);this.codeRunners={restart:new r.SemanticCommand,run:new r.SemanticCommand,runAll:new r.SemanticCommand}}}class u extends i.RankedMenu{constructor(e){super(e)}}class p extends i.RankedMenu{constructor(e){super(e)}}class m extends i.RankedMenu{constructor(e){super(e);this.editorViewers={toggleLineNumbers:new r.SemanticCommand,toggleMatchBrackets:new r.Semantic


gamma(1 + n)) ** (1 / n)
        / R**2
    )  # ~ 2.01
    m = M / N  # single particle mass
    pos = np.random.randn(N, 3)  # randomly selected positions and velocities
    vel = np.zeros(pos.shape)

    # calculate initial gravitational accelerations
    acc = getAcc(pos, vel, m, h, k, n, lmbda, nu)

    # number of timesteps
    Nt = int(np.ceil(tEnd / dt))

    # prep figure
    fig = plt.figure(figsize=(4, 5), dpi=80)
    grid = plt.GridSpec(3, 1, wspace=0.0, hspace=0.3)
    ax1 = plt.subplot(grid[0:2, 0])
    ax2 = plt.subplot(grid[2, 0])
    rr = np.zeros((100, 3))
    rlin = np.linspace(0, 1, 100)
    rr[:, 0] = rlin
    rho_analytic = lmbda / (4 * k) * (R**2 - rlin**2)

    # Simulation Main Loop
    for i in range(Nt):
        # (1/2) kick
        vel += acc * dt / 2

        # drift
        pos += vel * dt

        # update accelerations
        acc = getAcc(pos, vel, m, h, k, n, lmbda, nu)

        # (1/2) kick
        vel += acc * dt / 2

        # update time
        t += dt

        # get density for plotting
        rho = getDensity(pos, pos, m, h)

        # plot in real time
        if plotRealTime or (i == Nt - 1):
            plt.sca(ax1)
            plt.cla()
            cval = np.minimum((rho - 3) / 3, 1).flatten()
            plt.scatter(
                pos[:, 0], pos[:, 1], c=cval, cmap=plt.cm.autumn, s=10, alpha=0.5
            )
            ax1.set(xlim=(-1.4, 1.4), ylim=(-1.2, 1.2))
            ax1.set_aspect("equal", "box")
            ax1.set_xticks([-1, 0, 1])
            ax1.set_yticks([-1, 0, 1])
            ax1.set_facecolor("black")
            ax1.set_facecolor((0.1, 0.1, 0.1))

            plt.sca(ax2)
            plt.cla()
            ax2.set(xlim=(0, 1), ylim=(0, 3))
            ax2.set_aspect(0.1)
            plt.plot(rlin, rho_analytic, color="gray", linewidth=2)
            rho_radial = getDensity(rr, pos, m, h)
            plt.plot(rlin, rho_radial, color="blue")
            plt.pause(0.001)

    # add labels/legend
    plt.sca(ax2)
    plt.xlabel("radius")
    plt.ylabel("density")

    # Save figure
    plt.savefig("sph.png", dpi=240)
    plt.show()

    return 0

if __name__ == "__main__":
    main()


ilename)
        # min
        # score = sum(np.abs((tmppit - tmppit.min()) -
        #                    (pit - pit.min())))
        # mean
        score = sum(np.abs((tmppit - tmppit.mean()) -
                           (pit - pit.mean())))
        choices[filename] = score.numpy()

    sorted_choices = sorted(choices.items(), key=lambda x: x[1])
    logger.info(f"{sorted_choices}")

    for ele in sorted_choices:
        final_save_name = os.path.splitext(
            ele[0])[0] + f"_{int(ele[1])}" + ".wav"
        os.rename(ele[0], final_save_name)
        logger.info(f"{ele[0]} -> {final_save_name}")

    return out_audio, final_save_name

def svc_infer_pipeline_panxin_choice_stage2(
    wave: str,
    spk_id: str,
    model_path: str,
    save_name: str = "svc_out.wav",
    f0scale: float = 1.0,
):
    """Test for auto f0 shift and choice the best

    Args:
        wav (str): Path of raw audio.
        spk (str): Path of speaker.
        pgg (str): Path of content vector.
        vec (str): Path of hubert vector.
        pit (str): Path of pitch csv file.
        shift (int, optional): Pitch shift key.. Defaults to 0.
        enable_retrieval (bool, optional): Enable index feature retrieval. Defaults to True.
        etrieval_index_prefix (str, optional): _description_. Defaults to "".
        retrieval_ratio (float, optional): ratio of feature retrieval effect. Must be in range 0..1. Defaults to 0.5.
        n_retrieval_vectors (int, optional): get n nearest vectors from retrieval index. Works stably in range 1..3. Defaults to 3.
        hubert_index_path (str, optional): path to hubert index file. Defaults to "data_svc/indexes/speaker.../%prefix%hubert.index".

    """
    model = load_svc_model(model_path, synthesizer_infer_model)

    model.eval()
    model.to(service_hparams["device"])
    # TODO 优化音频的读取逻辑，现在的音频被反复读取
    # logger.info(f"whisper infer start ...")
    ppg = whisper_infer(wave)
    # logger.info(f"whisper infer done...")
    # logger.info(f"hubert infer start ...")

    vec = hubert_infer(wave)
    # logger.info(f"hubert infer done ...")
    # logger.info(f"pitch infer start ...")

    pit = pitch_infer(wave)
    # logger.info(f"pitch infer start ...")

    spk = np.load(f"data_svc/singer/{spk_id}.spk.npy")
    spk = torch.FloatTensor(spk)

    # Spk pitch
    spkPit = np.load(f"data_svc/pitch/{spk_id}/{spk_id}.npy")

    ppg = np.repeat(ppg, 2, 0)  # 320 PPG -> 160 * 2
    ppg = torch.FloatTensor(ppg)

    vec = np.repeat(vec, 2, 0)  # 320 PPG -> 160 * 2
    vec = torch.FloatTensor(vec)

    shift = 0
    if spkPit[2] < np.mean(pit.numpy()) * f0scale:
        pit = np.array(pit)
        source = pit[pit > 0]
        source_ave = source.mean()
        source_min = source.min()
        source_max = source.max()
        logger.info(
            f"source pitch statics: mean={source_ave:0.1f}, \
                min={source_min:0.1f}, max={source_max:0.1f}"
        )
        shift = -12
        pit = pit * (2 ** (shift / 12))

    pit = torch.FloatTensor(pit)
    retrieval = DummyRetrieval()
    out_audio = svc_infer(model, retrieval, spk, pit, ppg, vec, hp, device)

    new_wav, _ = post_process(ref_wave_path=wave, svc_wave=out_audio)

    final_save_name = save_name + f"{shift}.wav"
    logger.info(f"save {final_save_name} with shift {shift}")
    write(final_save_name, hp.data.sampling_rate, new_wav)

    return out_audio, final_save_name

def svc_infer_pipeline_panxin_choice_f0shift(
    wave: str,
    spk_id: str,
    model_path: str,
    save_name: str = "svc_out.wav",
    shifts: int = 0,
):
    """Test for auto f0 shift and auto f0 shift choice by mean comparation.

    Args:
        wav (str): Path of raw audio.
        spk (str): Path of speaker.
        pgg (str): Path of content vector.
        vec (str): Path of hubert vector.
        pit (str): Path of pitch csv file.
        shift (int, optional): Pitch shift key.. Defaults to 0.
        enable_retrieval (bool, optional): Enable index feature retrieval. Defaults to True.
        etrieval_index_prefix (str, optional): _description_. Defaults to "".
        retrieval_ratio (float, optional): ratio of feature retrieval effect. Must be in range 0..1. Defaults to 0.5.
        n_retrieval_vectors (int, optional): get n nearest vectors from retrieval index. Works stably in range 1..3. Defaults to 3.
        hubert_index_path (str, optional): path to hubert index file. Defaults to "data_svc/indexes/speaker.../%prefix%hubert.index".


_NAME}
  namespace: ${KUADRANT_GATEWAY_NS}
  labels:
    kuadrant.io/gateway: "true"
spec:
    gatewayClassName: istio
    listeners:
    - allowedRoutes:
        namespaces:
          from: All
      hostname: "api.${KUADRANT_ZONE_ROOT_DOMAIN}"
      name: api
      port: 443
      protocol: HTTPS
      tls:
        certificateRefs:
        - group: ""
          kind: Secret
          name: api-${KUADRANT_GATEWAY_NAME}-tls
        mode: Terminate
EOF
```

Check the status of the `Gateway` ensuring the gateway is Accepted and Programmed:

```bash
kubectl get gateway ${KUADRANT_GATEWAY_NAME} -n ${KUADRANT_GATEWAY_NS} -o=jsonpath='{.status.conditions[?(@.type=="Accepted")].message}{"\n"}{.status.conditions[?(@.type=="Programmed")].message}'
```

Check the status of the listener, you will see that it is not yet programmed or ready to accept traffic due to bad TLS configuration. This will be fixed in the next step with the `TLSPolicy`:

```bash
kubectl get gateway ${KUADRANT_GATEWAY_NAME} -n ${KUADRANT_GATEWAY_NS} -o=jsonpath='{.status.listeners[0].conditions[?(@.type=="Programmed")].message}'
```

## Secure and protect the Gateway with Auth, Rate Limit, and DNS policies.

### Deploy the gateway TLS policy

```bash
kubectl apply -f - <<EOF
apiVersion: kuadrant.io/v1
kind: TLSPolicy
metadata:
  name: ${KUADRANT_GATEWAY_NAME}-tls
  namespace: ${KUADRANT_GATEWAY_NS}
spec:
  targetRef:
    name: ${KUADRANT_GATEWAY_NAME}
    group: gateway.networking.k8s.io
    kind: Gateway
  issuerRef:
    group: cert-manager.io
    kind: ClusterIssuer
    name: ${KUADRANT_CLUSTER_ISSUER_NAME}
EOF
```

Check that the `TLSpolicy` has an Accepted and Enforced status (This may take a few minutes for certain provider e.g Lets Encrypt):

```bash
kubectl get tlspolicy ${KUADRANT_GATEWAY_NAME}-tls -n ${KUADRANT_GATEWAY_NS} -o=jsonpath='{.status.conditions[?(@.type=="Accepted")].message}{"\n"}{.status.conditions[?(@.type=="Enforced")].message}'
```

### Setup Toystore application HTTPRoute

```bash

kubectl apply -f - <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: toystore
  namespace: ${KUADRANT_DEVELOPER_NS}
  labels:
    deployment: toystore
    service: toystore
spec:
  parentRefs:
  - name: ${KUADRANT_GATEWAY_NAME}
    namespace: ${KUADRANT_GATEWAY_NS}
  hostnames:
  - "api.${KUADRANT_ZONE_ROOT_DOMAIN}"
  rules:
  - matches:
    - method: GET
      path:
        type: PathPrefix
        value: "/cars"
    - method: GET
      path:
        type: PathPrefix
        value: "/health"
    backendRefs:
    - name: toystore
      port: 80
EOF
```

While the `Gateway` is now deployed, it currently has exposed endpoints. The next steps will be defining an `AuthPolicy` to set up a default `403` response for any unprotected endpoints, as well as a `RateLimitPolicy` to set up a default unrealistic low global limit to further


    buffer = 1,
          path = 1,
        },
        confirm_opts = {
          behavior = cmp.ConfirmBehavior.Replace,
          select = false,
        },
        window = {
          completion = cmp.config.window.bordered(border_opts),
          documentation = cmp.config.window.bordered(border_opts),
        },
        mapping = {
          ["<Up>"] = cmp.mapping.select_prev_item { behavior = cmp.SelectBehavior.Select },
          ["<Down>"] = cmp.mapping.select_next_item { behavior = cmp.SelectBehavior.Select },
          ["<C-p>"] = cmp.mapping.select_prev_item { behavior = cmp.SelectBehavior.Insert },
          ["<C-n>"] = cmp.mapping.select_next_item { behavior = cmp.SelectBehavior.Insert },
          ["<C-k>"] = cmp.mapping.select_prev_item { behavior = cmp.SelectBehavior.Insert },
          ["<C-j>"] = cmp.mapping.select_next_item { behavior = cmp.SelectBehavior.Insert },
          ["<C-u>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
          ["<C-d>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
          ["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
          ["<C-y>"] = cmp.config.disable,
          ["<C-e>"] = cmp.mapping { i = cmp.mapping.abort(), c = cmp.mapping.close() },
          ["<CR>"] = cmp.mapping.confirm { select = false },
          ["<Tab>"] = cmp.mapping(function(fallback)
            if cmp.visible() then
              cmp.select_next_item()
            elseif luasnip.expand_or_jumpable() then
              luasnip.expand_or_jump()
            elseif has_words_before() then
              cmp.complete()
            else
              fallback()
            end
          end, { "i", "s" }),
          ["<S-Tab>"] = cmp.mapping(function(fallback)
            if cmp.visible() then
              cmp.select_prev_item()
            elseif luasnip.jumpable(-1) then
              luasnip.jump(-1)
            else
              fallback()
            end
          end, { "i", "s" }),
        },
        sources = cmp.config.sources {
          { name = "nvim_lsp", priority = 1000 },
          { name = "luasnip", priority = 750 },
          { name = "buffer", priority = 500 },
          { name = "path", priority = 250 },
        },
      }
    end,
  },
}


      CheckStatus::Success => Ok(NameStatus::next(prev_stat, curr_stat)),
        }
    } else {
        new_name_error! {name, prev_cls, curr_cls, prev_loc, curr_loc}
    }
}

#[derive(Debug)]
struct NetworkNameInfo {
    stat: NameStatus,
    class: NetworkName,
    index: usize,
    loc: Loc,
}

impl<'a> NetworkNameInfo {
    fn validate(&self, name: &'a str) -> Result<(), UndefinedNameError<'a>> {
        self.stat.validate(name, self.loc)
    }
}

#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
enum NetworkName {
    Automata,
    Link,
    Event,
    ObsLabel,
    RelLabel,
    UnknowAutomata,
}

#[derive(Debug)]
struct AutomataNameTable<'a> {
    names: AHashMap<&'a str, AutomataInfo>,
    loc: Loc,
    index: usize,
    counter: ClassIndex<AutomataName>,
    name: &'a str,
}

impl<'a> AutomataNameTable<'a> {
    fn new(name: &'a str, loc: Loc, index: usize) -> Self {
        AutomataNameTable {
            names: AHashMap::new(),
            loc,
            index,
            counter: ClassIndex::new(),
            name,
        }
    }

    fn into_index_table(self, name: &'a str) -> (AutomataNamesFactory<'a>, usize) {
        let mut factory = AutomataNamesFactory::new(name);
        for (name, info) in self.names.into_iter() {
            match info.class {
                AutomataName::State | AutomataName::Begin => factory.add_state(name, info.index),
                AutomataName::Transition => factory.add_transition(name, info.index),
            }
        }

        (factory, self.index)
    }

    fn set_index(&mut self, name: &str) {
        let item = self.names.get_mut(name).unwrap();
        let cls = item.class;
        let index = self.counter.get_count(cls);
        item.index = index;
    }

    fn get_name_class(&self, name: &str) -> Option<NameClass> {
        if let Some(def) = self.names.get(name) {
            Some((&def.class).into())
        } else {
            None
        }
    }

    fn insert_name(&mut self, name: &'a str, loc: Loc, class: AutomataName, stat: NameStatus) {
        if let Some(info) = self.names.get_mut(name) {
            info.loc = loc;
            info.stat = stat;
        } else {
            let info = AutomataInfo {
                loc,
                class,
                stat,
                index: 0,
            };
            self.names.insert(name, info);
        }
    }

    fn validate(&self) -> Result<(), NameError<'a>> {
        self.validate_definitions()?;
        self.validate_begin_state()?;
        Ok(())
    }

    fn validate_definitions(&self) -> Result<(), UndefinedNameError<'a>> {
        for (name, item) in self.names.iter() {
            item.stat.validate(name, item.loc)?
        }
        Ok(())
    }

    fn validate_begin_state(&self) -> Result<(), BeginStateError<'a>> {
        let begin_states: Vec<&'a str> = self
            .names
            .iter()
            .filter_map(|(name, info)| match info.class {
                AutomataName::Begin => Some(*name),
                _ => None,
            })
            .collect();
        let class = match begin_states.len() {
            0 => Some(BeginStateErrorClass


,
  });

  @override
  List<Object> get props {
    return [
      quoteId,
      userId,
      createdAt,
      quoteText,
      author,
      textAlign,
      backgroundColor,
      fontSize,
      fontWeight,
      wordSpacing,
      letterSpacing,
      likes,
    ];
  }

  @override
  bool get stringify => true;

  Map<String, dynamic> toJson() {
    return <String, dynamic>{
      QuoteKey.quoteId: quoteId,
      QuoteKey.userId: userId,
      QuoteKey.createdAt: createdAt.millisecondsSinceEpoch,
      QuoteKey.quoteText: quoteText,
      QuoteKey.author: author,
      QuoteKey.textAlign: textAlign,
      QuoteKey.backgroundColor: backgroundColor,
      QuoteKey.fontSize: fontSize,
      QuoteKey.fontWeight: fontWeight,
      QuoteKey.wordSpacing: wordSpacing,
      QuoteKey.letterSpacing: letterSpacing,
      QuoteKey.likes: likes,
    };
  }

  factory RemoteQuoteModel.fromSnapshot(DocumentSnapshot snap) {
    final map = snap.data() as Map<String, dynamic>;

    return RemoteQuoteModel(
      quoteId: map[QuoteKey.quoteId] as String,
      userId: map[QuoteKey.userId] as String,
      createdAt: DateTime.fromMillisecondsSinceEpoch(
        map[QuoteKey.createdAt] as int,
      ),
      quoteText: map[QuoteKey.quoteText] as String,
      author: map[QuoteKey.author] as String,
      textAlign: map[QuoteKey.textAlign] as String,
      backgroundColor: map[QuoteKey.backgroundColor] as int,
      fontSize: map[QuoteKey.fontSize] as double,
      fontWeight: map[QuoteKey.fontWeight] as String,
      wordSpacing: map[QuoteKey.wordSpacing] as double,
      letterSpacing: map[QuoteKey.letterSpacing] as double,
      likes: List.from(snap[QuoteKey.likes]),
    );
  }
}
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:pub_app/provider.dart';
import 'package:pub_app/ui/publisher.dart';
import 'package:pub_app/ui/search.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({super.key});

  @override
  ConsumerState<HomePage> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage> {
  static bool refreshed = false;

  @override
  void initState() {
    super.initState();

    if (!refreshed) {
      ref
          .read(packageManagerPod.future)
          .then((pm) => pm.bulkLoad('is:flutter-favorite'));
      refreshed = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        physics: const ClampingScrollPhysics(),
        child: SafeArea(
          top: false,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              SizedBox(
                height: 230,
                child: Search(
                  onSearch: (query) {
                    context.go('/search/$query');
                  },
                ),
              ),
              const Favorites(),
            ],
          ),
        ),
      ),
    );
  }
}

final randomFavoriteNamesPod = StreamProvider((ref) async* {
  final manager = await ref.watch(packageManagerPod.future);
  Set<String>? previousNames;
  await for (final packageNames in manager.watchFavoriteNames()) {
    if (packageNames.isNotEmpty &&
        (previousNames == null ||
            !setEquals(packageNames.toSet(), previousNames))) {
      previousNames = packageNames.toSet();
      packageNames.shuffle();
      yield packageName


E2A8 AFBF0014 */  sw    $ra, 0x14($sp)
/* AD544C 8005E2AC AFA5001C */  sw    $a1, 0x1c($sp)
/* AD5450 8005E2B0 0C018A8A */  jal   func_80062A28
/* AD5454 8005E2B4 00C02825 */   move  $a1, $a2
/* AD5458 8005E2B8 8FBF0014 */  lw    $ra, 0x14($sp)
/* AD545C 8005E2BC 27BD0018 */  addiu $sp, $sp, 0x18
/* AD5460 8005E2C0 03E00008 */  jr    $ra
/* AD5464 8005E2C4 00000000 */   nop

/* AD5468 8005E2C8 27BDFFE8 */


.
     */
    static handleError(error: object): ECErrorStack | boolean;
    /**
     * A helper method to initialize the communication with the database.
     * @param {ECSQLInitObject} initObject The initialization object.
     */
    static init(initObject: ECSQLInitObject): void;
}
import Adresse from './adresse'

export default class Transport {
    public Nom: string = "";
    public Journee: Date = new Date();
    public Depart: Adresse;
    public Arrivee: Adresse;
    public Id: number = 0;
    public NomClient: string = "";
    public PrenomClient: string = "";

    private static maxId : number = 0;

    public constructor(nom: string, nomClient: string, prenomClient: string,
        journee: Date, depart: Adresse,
        arrivee: Adresse) {
            this.Nom = nom;
            this.NomClient = nomClient;
            this.PrenomClient = prenomClient;
            this.Journee = journee;
            this.Depart = depart;
            this.Arrivee = arrivee;
            this.Id = Transport.maxId++;
    }
}import { ComboBuff } from '../../interface'
import { AddHPLast } from '../computed'
/**
 * 加血buff模型
 * @param value
 * @desc 每回合回{value}血
 */
export const HealthModel = (value: number): ComboBuff => {
  return {
    buffs: [AddHPLast(value)]
  }
}
import * as fs from "fs";
import MessageHandler from "./interfaces/message-handler";
import * as Discord from "discord.js";
import ConfigManager from "../../config/config-manager";
import MiscHelper from "../../helpers/misc-helper";

export default class MessageHandlerManager {
    private static readonly HANDLERS_FOLDER_NAME = "handlers";
    private static readonly HELP_COMMAND = "help";

    private messageHandlers: MessageHandler[];

    public constructor(
        private client: Discord.Client
    ) {
        this.registerMessageHandlers();
    }

    private registerMessageHandlers() {
        this.messageHandlers = fs
            .readdirSync(`${__dirname}/${MessageHandlerManager.HANDLERS_FOLDER_NAME}`)
            .filter(filename => filename.endsWith(".ts"))
            .map(filename => `${__dirname}/${MessageHandlerManager.HANDLERS_FOLDER_NAME}/${filename}`)
            .map(filename => new (require(filename)).default());

        if (this.messageHandlers.some(i => i.aliases.length === 0)) {
            throw new Error(`There is a message handler with no aliases in it`);
        }

        this.messageHandlers.forEach(messageHandler =>
            console.info("Loaded '" + messageHandler.aliases.join(", ") + "' argument(s) listener"));

        this.client.on("message", async (message: Discord.Message) => this.messageArrived(message));
    }

    private async messageArrived(message: Discord.Message) {
        if (message.author.bot) {
            return;
        }

        if (message.type !== "DEFAULT") {
            return;
        }

        const args = message.content.split(" ");

        if (args.length === 0) {
            console.log("args.length was 0, not processing the message");

            return;
        }

        let command = args[0];

        if (!command.startsWith(ConfigManager.config.commandPrefix)) {
            return;
        }

        command = command.substring(ConfigManager.config.commandPrefix.length);

        args.shift();

        console.log(`> ${message.author.username}: ${message.content}`);

        await this.executeCommand(message, command, args);
    }

    private async executeCommand(message: Discord.Message, command: string, args: string[]) {
        if (command === MessageHandlerManager.HELP_COMMAND) {
            await this.helpMessageArrived(message);

            return;


https://wg21.link/n3408

[niebler.iter.0] Eric Niebler. 2015. To Be or Not to Be (an Iterator).

http://ericniebler.com/2015/01/28/to-be-or-not-to-be-an-iterator/

[niebler.iter.1] Eric Niebler. 2015. Iterators++, Part 1.

http://ericniebler.com/2015/02/03/iterators-plus-plus-part-1/

[niebler.iter.2] Eric Niebler. 2015. Iterators++, Part 2.

http://ericniebler.com/2015/02/13/iterators-plus-plus-part-2/

[niebler.iter.3] Eric Niebler. 2015. Iterators++, Part 3.

http://ericniebler.com/2015/03/03/iterators-plus-plus-part-3/

[P0024R2] Jared Hoberock. 2016. The Parallelism TS Should be Standardized.

https://wg21.link/p0024r2

[P0592R4] Ville Voutilainen. 2019. To boldly suggest an overall plan for C++23.

https://wg21.link/p0592r4

[P0836R1] Gordon Brown, Christopher Di Bella, Michael Haidl, Toomas Remmelg, Ruyman Reyes, Michel Steuwer, Michael Wong. 2018. Introduce Parallelism to the Ranges TS.

https://wg21.link/p0836r1

[P0896R4] Eric Niebler, Casey Carter, Christopher Di Bella. 2018. The One Ranges Proposal.

https://wg21.link/p0896r4

[P1206R1] Corentin Jabot, Eric Niebler, Casey Carter. 2019. ranges::to: A function to convert any range to a container.

https://wg21.link/p1206r1

[P1255R6] Steve Downey. 2020. A view of 0 or 1 elements: views::maybe.

https://wg21.link/p1255r6


n_bi_xor2() {
    for _ in 0..1 {
        pla_can_learn_bi(BinOp::XOR, 2, 500);
    }
}

#[test]
fn pla_can_learn_bi_nor2() {
    for _ in 0..1 {
        pla_can_learn_bi(BinOp::NOR, 2, 500);
    }
}

#[test]
fn pla_can_learn_bi_xnor2() {
    for _ in 0..1 {
        pla_can_learn_bi(BinOp::XNOR, 2, 500);
    }
}

// #[test]
// fn pla_can_learn_bi_or3() {
//     for _ in 0..100 {
//         pla_can_learn_bi(BinOp::OR, 3, 2000);
//     }
// }

// #[test]
// fn pla_can_learn_bi_nand3() {
//     for _ in 0..100 {
//         pla_can_learn_bi(BinOp::NAND, 3, 1500);
//     }
// }

#[test]
fn pla_can_learn_bi_and3() {
    for _ in 0..1 {
        pla_can_learn_bi(BinOp::AND, 3, 1500);
    }
}

#[test]
fn pla_can_learn_bi_xor3() {
    for _ in 0..1 {
        pla_can_learn_bi(BinOp::XOR, 3, 1500);
    }
}

#[test]
fn pla_can_learn_bi_nor3() {
    for _ in 0..1 {
        pla_can_learn_bi(BinOp::NOR, 3, 2000);
    }
}

#[test]
fn pla_can_learn_bi_xnor3() {
    for _ in 0..1 {
        pla_can_learn_bi(BinOp::XNOR, 3, 1500);
    }
}
// This file is part of lfchring-rs.
//
// Copyright 2021 <NAME>
//
// 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.

use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher as StdHasher;

use thiserror::Error;

pub(crate) enum Update {
    Insert,
    Remove,
}

pub(crate) enum Adjacency {
    Predecessor,
    Successor,
}

/// A type for the internal ID of each virtual node of every distinct consistent hashing ring node.
///
/// This is merely a type alias for `u16` for now.
/// Therefore, each distinct [`Node`] in the [`HashRing<N, H>`] can be mapped at least once and at
/// most [`u16::MAX`] times on the consistent hashing ring.
///
///
///  [`HashRing<N, H>`]: ../struct.HashRing.html
pub type Vnid = u16;

/// A custom `Result` type for this crate, combining a return value with a [`HashRingError`].
///
/// It is used all over the crate and also returned by many functions and method in its external
/// API.
pub type Result<T> = std::result::Result<T, HashRingError>;

/// A trait to be implemented by any type that needs to act as a distinct node in the consistent
/// hashing ring.
pub trait Node {
    /// Returns a byte slice that uniquely identifies the particular [`Node`] from the rest of its


        use util::{TAG_PUBKEY_FULL, TAG_PUBKEY_HYBRID_EVEN, TAG_PUBKEY_HYBRID_ODD};

        if !(p[0] == TAG_PUBKEY_FULL
            || p[0] == TAG_PUBKEY_HYBRID_EVEN
            || p[0] == TAG_PUBKEY_HYBRID_ODD)
        {
            return Err(Error::InvalidPublicKey);
        }
        let mut x = Field::default();
        let mut y = Field::default();
        if !x.set_b32(array_ref!(p, 1, 32)) {
            return Err(Error::InvalidPublicKey);
        }
        if !y.set_b32(array_ref!(p, 33, 32)) {
            return Err(Error::InvalidPublicKey);
        }
        let mut elem = Affine::default();
        elem.set_xy(&x, &y);
        if (p[0] == TAG_PUBKEY_HYBRID_EVEN || p[0] == TAG_PUBKEY_HYBRID_ODD)
            && (y.is_odd() != (p[0] == TAG_PUBKEY_HYBRID_ODD))
        {
            return Err(Error::InvalidPublicKey);
        }
        if elem.is_infinity() {
            return Err(Error::InvalidPublicKey);
        }
        if elem.is_valid_var() {
            Ok(PublicKey(elem))
        } else {
            Err(Error::InvalidPublicKey)
        }
    }

    pub fn parse_compressed(
        p: &[u8; util::COMPRESSED_PUBLIC_KEY_SIZE],
    ) -> Result<PublicKey, Error> {
        use util::{TAG_PUBKEY_EVEN, TAG_PUBKEY_ODD};

        if !(p[0] == TAG_PUBKEY_EVEN || p[0] == TAG_PUBKEY_ODD) {
            return Err(Error::InvalidPublicKey);
        }
        let mut x = Field::default();
        if !x.set_b32(array_ref!(p, 1, 32)) {
            return Err(Error::InvalidPublicKey);
        }
        let mut elem = Affine::default();
        elem.set_xo_var(&x, p[0] == TAG_PUBKEY_ODD);
        if elem.is_infinity() {
            return Err(Error::InvalidPublicKey);
        }
        if elem.is_valid_var() {
            Ok(PublicKey(elem))
        } else {
            Err(Error::InvalidPublicKey)
        }
    }

    pub fn serialize(&self) -> [u8; util::FULL_PUBLIC_KEY_SIZE] {
        use util::TAG_PUBKEY_FULL;

        debug_assert!(!self.0.is_infinity());

        let mut ret = [0u8; 65];
        let mut elem = self.0;

        elem.x.normalize_var();
        elem.y.normalize_var();
        elem.x.fill_b32(array_mut_ref!(ret, 1, 32));
        elem.y.fill_b32(array_mut_ref!(ret, 33, 32));
        ret[0] = TAG_PUBKEY_FULL;

        ret
    }

    pub fn serialize_compressed(&self) -> [u8; util::COMPRESSED_PUBLIC_KEY_SIZE] {
        use util::{TAG_PUBKEY_EVEN, TAG_PUBKEY_ODD};

        debug_assert!(!self.0.is_infinity());

        let mut ret = [0u8; 33];
        let mut elem = self.0;

        elem.x.normalize_var();
        elem.y.normalize_var();
        elem.x.fill_b32(array_mut_ref!(ret, 1, 32));
        ret[0] = if elem.y.is_odd() {
            TAG_PUBKEY_ODD
        } else {
            TAG_PUBKEY_EVEN
        };

        ret
    }

    pub fn tweak_add_assign_with_context(
        &mut self,
        tweak: &SecretKey,
        context: &ECMultContext,
    ) -> Result<(), Error> {
        let


60068058 - twitch: SohrabXch
  [181914067] = {3}, --steam: http://steamcommunity.com/profiles/76561198142179795 - twitch: Soundkidz
  [80374433] = {3}, --steam: http://steamcommunity.com/profiles/76561198040640161 - twitch: SquareG66
  [123018754] = {3}, --steam: http://steamcommunity.com/profiles/76561198083284482 - twitch: the_funkalizer
  [162267134] = {3}, --steam: http://steamcommunity.com/profiles/76561198122532862 - twitch: the_lightnin
  [196954061] = {3}, --steam: http://steamcommunity.com/profiles/76561198157219789 - twitch: TheOnly1Matt
  [148245960] = {3}, --steam: http://steamcommunity.com/profiles/76561198108511688 - twitch: -no name given}, steam name toxic panda
  [186729309] = {3}, --steam: http://steamcommunity.com/profiles/76561198146995037 - twitch: -no name given}, steam name renton
  [332989639] = {3}, --steam: http://steamcommunity.com/profiles/76561198293255367 - twitch: ReAlUnKnOwNgUy
  [268013660] = {3}, --steam: http://steamcommunity.com/profiles/76561198228279388 - twitch: Johnathan963
  [293127420] = {3}, --steam: http://steamcommunity.com/profiles/76561198253393148 - twitch: -no name given}, current steam name crazyrock
  [156899250] = {3}, --steam: http://steamcommunity.com/profiles/76561198117164978 - twitch: -no name given}, current steam name bonde
  [226594311] = {3}, --steam: http://steamcommunity.com/profiles/76561198186860039 - twitch: Oaksworth
  [92726647] = {3}, --steam: http://steamcommunity.com/profiles/76561198052992375 - twitch: -no name given}, current steam name Pomfritten
  [201059237] = {3}, --steam: https://steamcommunity.com/profiles/76561198161324965/ - twitch: GiveYaTheWorld

  -- twitch donators 20

  --KarmaticNeutral
  [259101879] = {3,4}, --steam: http://steamcommunity.com/profiles/76561198219367607 - twitch: Chives donated 2x10 with same profile link and different message
  [144379677] = {3,4}, --steam: http://steamcommunity.com/profiles/76561198104645405 - twitch: 99LuftBalloons
  [106881079] = {3,4}, --steam: http://steamcommunity.com/profiles/76561198067146807 - twitch: Alsher7
  [113199503] = {3,4}, --steam: http://steamcommunity.com/profiles/76561198073465231 - twitch: BananaCharge
  [82995898] = {3,4}, --steam: http://steamcommunity.com/profiles/76561198043261626 - twitch: bobAKAbill
  [102208419] = {3,4}, --steam: http://steamcommunity.com/profiles/76561198062474147 - twitch: CreepySniper
  [98653735] = {3,4}, --steam: http://steamcommunity.com/profiles/76561198058919463 - twitch: CynicalDemon
  [99112333] = {3


price = 59
a = f"The price is {price} dollars"
print(a)


 nome do meu clã, Senhores do Trovão, um nome logo esquecido por este mundo. Poucos compartilham meu coração melancólico; por isso eu o sigo, aquele velho orc rabugento.$B$BLamentar o passado não adianta. A Horda é o que somos agora. Só desejo transmitir o espírito da caça, o coração e a mente daqueles que vieram antes, para que eles, e eu, vivamos para sempre.$B$BE você, é a vela que acendi com meu fogo. Um dia, de sua chama, nascerá outro.$B$BEncontre seu caminho para a ilha principal, através do porto em ruínas de Breezhaven. Passando a mina e o pomar, vire à direita para encontrar o lago Sorrowmere. Pinte-se com sangue de crocolisco e retorne com cinco de suas caudas. Já faz muito tempo desde que provei sua carne.$B$BSeja audacioso, seja cauteloso e, acima de tudo, empolgue-se com a caça.",
    ["O"] = "Mate 10 crocoliscos de Pesaroscuro e entregue 5 de suas caudas para Gre\'shka Mordida de Lobo em Ponta Tempestade, Balor.",
    ["T"] = "O Primeiro de Muitos",
  },
  [41817] = {
    ["D"] = "Uma sensação quente, não é? Uma tentativa bem-sucedida, cujo saque você compartilhou com outro, unido a você pelo respeito mútuo pela caça.$B$BEste momento que compartilhamos agora, já compartilhei inúmeras vezes com meu povo em casa. Não passava um dia sem que voltássemos com uma presa, comemorando com nosso saque e contando histórias de nossas caçadas.$B$BE uma boa vida que tivemos, que temos. Embora mesmo assim, muitos se perderam; uma simples negligência pode custar sua vida.$B$BO medo é seu rival, meu amigo. Você deve controlá-lo, ou ele governará você. Não se preocupe em competir com os outros, compita com seu medo. Um segundo é suficiente para que você pereça.$B$BCom isso em mente, deve voltar ao lago Sorrowmere e seguir as longas pontes até o Mato Corrente. Sua próxima caça espera. Mate as aranhas Casca da Névoa e observe como você se sai contra um inimigo de muitas patas e uma mordida venenosa.$B$BEnquanto caminha até lá, lembre-se do que eu disse: não são realmente eles que você está enfrentando, mas seu medo.",
    ["O"] = "Mate 5 aranhas Casca da Névoa e 6 tecelãs Casca da Névoa, depois retorne para Gre\'shka Mordida de Lobo em Ponta Tempestade.",
    ["T"] = "O Medo é seu Rival",
  },
  [41818] = {
    ["D"] = "Uma caça muito mais desafiadora, mas muitas outras esperam. Uma lição que você deve aprender é que nenhuma criatura nasce igual. Aqueles que dizem o contrário carecem de visão ou senso comum.$B$BNas suas viagens, enfrentará muitas provas. Azeroth é vasto e cruel; deve estar preparado para tudo.$B$BA desigualdade também marca nossa singularidade. Não veja a palavra \"desigual\" e mergulhe em pensamentos sombrios. Olhe além, entenda que embora o mundo não se incline para você, ser você mesmo é suficiente. Você encontrará um caminho, seu caminho, e será único.$B$BVocê enfrentou seu medo, e esse foi o primeiro passo


== 10) {
            numberOfLines++;
            if (firstLine == -1) firstLine = i;
        }
    }
}

unsigned int UpdateScore(short numOfLines) {
    unsigned int newIncrement = 0;
    switch (numOfLines) {
        case 1:
            newIncrement = 40;
            break;
        case 2:
            newIncrement = 100;
            break;
        case 3:
            newIncrement = 300;
            break;
        case 4:
            newIncrement = 1200;
            break;
        default:
            newIncrement = 0;
            break;
    }
    return newIncrement * (level + 1);
}

void UpdateBoard() {
    short firstLine, numberOfLines;
    do {
        CheckLines(firstLine, numberOfLines);
        for (int i = firstLine; i >= numberOfLines; i--) {
            for (int j = 0; j < 10; j++) {
                board[i][j] = board[i - numberOfLines][j];
                board[i - numberOfLines][j] = 0;
            }
        }
        fillrect(0, 0, BOARD_RIGHT, SCREEN_HEIGHT, Black);
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 10; j++) {
                if (board[i][j] != 0) {
                    fillrect(j * DIMENSION, i * DIMENSION, (j + 1) * DIMENSION, (i + 1) * DIMENSION, colors[board[i][j]]);
                    rect(j * DIMENSION, i * DIMENSION, (j + 1) * DIMENSION, (i + 1) * DIMENSION, Black);
                }
            }
        }
        score += UpdateScore(numberOfLines);
        DrawFigure();
    } while (numberOfLines != 0);
}

bool IsOver() {
    for (int i = 0; i < 10; i++) {
        if (board[0][i] != 0) {
            return true;
        }
    }
    return false;
}

void ShowGameOverScreen() {
    background(Black);
    foreground(White);
    locate(UI_POS_X_CENTER(10), 120);
    printf("GAME OVER");
    locate(UI_POS_X_CENTER(21), 150);
    printf("YOUR SCORE IS %d", score);
    wait(5);
}

void InitGame() {
    if (firstTime) {
        Tetromino(rand() % 7 + 1);
        DrawFigure();
        nextFigure = rand() % 7 + 1;
        ShowNextFigure();
        firstTime = false;
    }
}

void PlayGame() {
    InitGame();
    if (!MoveDown(1)) {
        OnAttached();
        UpdateBoard();
        ShowScore();
        Tetromino(nextFigure);
        DrawFigure();
        nextFigure = rand() % 7 + 1;
        ShowNextFigure();
        if (IsOver()) {
            game.detach();
            ShowGameOverScreen();
            EndPlay();
        }
    }
}

void OnTasterPressed() {
    static uint32_t debounce_counter = 0;
    const uint32_t debounce_threshold = 12;

    if (debounce_counter == 0) {
        if (!gameStarted) {
            joystick.detach();
            gameStarted = true;
            StartGame();
            joystick.attach(&ReadJoystickForFigure, 0.3);
            game.attach(&PlayGame, delays[level]);
        }
        debounce_counter = debounce_threshold;
    } else if (debounce_counter > 0) {
        debounce_counter--;
    }
}

void pause_game() {
    game


mode == invalid {
			return
		}
		if !isNumeric(x.typ) {
			check.invalidOp(s.X.Pos(), "%s%s (non-numeric type %s)", s.X, s.Tok, x.typ)
			return
		}

		Y := &ast.BasicLit{ValuePos: s.X.Pos(), Kind: token.INT, Value: "1"} // use x's position
		check.binary(&x, nil, s.X, Y, op)
		if x.mode == invalid {
			return
		}
		check.assignVar(s.X, &x)

	case *ast.AssignStmt:
		for i, x := range s.Rhs {
			if expr := check.tryFixOperatorCall(x); expr != nil {
				s.Rhs[i] = expr
			}
		}

		switch s.Tok {
		case token.ASSIGN, token.DEFINE:
			if len(s.Lhs) == 0 {
				check.invalidAST(s.Pos(), "missing lhs in assignment")
				return
			}
			if s.Tok == token.DEFINE {
				check.shortVarDecl(s.TokPos, s.Lhs, s.Rhs)
			} else {
				// regular assignment
				check.assignVars(s.Lhs, s.Rhs)
			}

		default:
			// assignment operations
			if len(s.Lhs) != 1 || len(s.Rhs) != 1 {
				check.errorf(s.TokPos, "assignment operation %s requires single-valued expressions", s.Tok)
				return
			}
			op := assignOp(s.Tok)
			if op == token.ILLEGAL {
				check.invalidAST(s.TokPos, "unknown assignment operation %s", s.Tok)
				return
			}
			var x operand
			check.binary(&x, nil, s.Lhs[0], s.Rhs[0], op)
			if x.mode == invalid {
				return
			}
			check.assignVar(s.Lhs[0], &x)
		}

	case *ast.DeferStmt:
		check.suspendedCall("defer", s.Call)

	case *ast.ReturnStmt:
		for i, x := range s.Results {
			if expr := check.tryFixOperatorCall(x); expr != nil {
				s.Results[i] = expr
			}
		}
		res := check.sig.results
		if res.Len() > 0 {
			// function returns results
			// (if one, say the first, result parameter is named, all of them are named)
			if len(s.Results) == 0 && res.vars[0].name != "" {
				// spec: "Implementation restriction: A compiler may disallow an empty expression
				// list in a "return" statement if a different entity (constant, type, or variable)
				// with the same name as a result parameter is in scope at the place of the return."
				for _, obj := range res.vars {
					if alt := check.lookup(obj.name); alt != nil && alt != obj {
						check.errorf(s.Pos(), "result parameter %s not in scope at return", obj.name)
						check.errorf(alt.Pos(), "\tinner declaration of %s", obj)
						// ok to continue
					}
				}
			} else {
				// return has results or result parameters are unnamed
				check.initVars(res.vars, s.Results, s.TokPos)
			}
		} else if len(s.Results) > 0 {
			check.error(s.Results[0].Pos(), "no result values expected")
			check.use(s.Results...)
		}

	case *ast.BranchStmt:
		if s.Label != nil {
			check.hasLabel = true
			return // checked in 2nd pass (check.labels)
		}
		switch s.Tok {
		case token.BREAK:
			if ctxt&breakOk == 0 {
				check.error(s.Pos(), "break not in for, switch, or select statement")
			}
		case token.CONTINUE:
			if ctxt&continueOk == 0 {
				check.error(s.Pos(), "continue not in


function self.getUtcTime() end

    --- Return the time offset between local timezone and UTC
    ---@return number value Time in seconds
    function self.getUtcOffset() end

    --- Return the locale in which the game is currently running
    ---@return string value The locale, currently one of "en-US", "fr-FR", or "de-DE"
    function self.getLocale() end

    --- Return delta time of action updates (to use in ActionLoop)
    ---@return number value The delta time in seconds
    function self.getActionUpdateDeltaTime() end

    --- Return the name of the given player, if in range of visibility or broadcasted by a transponder
    ---@param id integer The ID of the player
    ---@return string value The name of the player
    function self.getPlayerName(id) end

    --- Return the world position of the given player, if in range of visibility
    ---@param id integer The ID of the player
    ---@return table value The coordinates of the player in world coordinates
    function self.getPlayerWorldPos(id) end

    --- Return the item table corresponding to the given item ID.
    ---@param id integer The ID of the item
    ---@return table value An item table with fields: {[int] id, [string] name, [string] displayName, [string] locDisplayName, [string] displayNameWithSize, [string] locDisplayNameWithSize, [string] description, [string] locDescription, [string] type, [number] unitMass, [number] unitVolume, [integer] tier, [string] scale, [string] iconPath, [table] schematics, [table] products}
    function self.getItem(id) end

    --- Returns a list of recipes producing the given item from its id.
    ---@param itemId integer The ID of the item
    ---@return table value A list of recipe table with field: {[int] id, [int] tier,[double] time, [bool] nanocraftable, [table] products:{{[int] id, [double] quantity},...}, [table] ingredients:{{[int] id, [double] quantity},...}}
    function self.getRecipes(itemId) end
    ---@deprecated System.getSchematic(id) is deprecated, use System.getRecipes(itemId).tag.
    function self.getSchematic(id) error("System.getSchematic(id) is deprecated, use System.getRecipes(itemId) instead.") end

    --- Returns the corresping organization to the given organization id, if known, e.g. broadcasted by a transponder
    ---@param id integer The ID of the organization
    ---@return table value A table contain


/*
 * Copyright 2007-2009, Ingo Weinhold, bonefish@cs.tu-berlin.de.
 * Distributed under the terms of the MIT License.
 */
#ifndef _FSSH_DEFS_H
#define _FSSH_DEFS_H

#include "fssh_types.h"

// 32/64 bitness
#ifdef HAIKU_HOST_PLATFORM_64_BIT
#	define FSSH_B_HAIKU_64_BIT			1
#else
#	define FSSH_B_HAIKU_32_BIT			1
#endif

// Limits
#define FSSH_B_DEV_NAME_LENGTH		128
#define FSSH_B_FILE_NAME_LENGTH		256
#define FSSH_B_PATH_NAME_LENGTH 	1024
#define FSSH_B_ATTR_NAME_LENGTH		(FSSH_B_FILE_NAME_LENGTH-1)
#define FSSH_B_MIME_TYPE_LENGTH		(FSSH_B_ATTR_NAME_LENGTH - 15)
#define FSSH_B_MAX_SYMLINKS			16

// Open Modes
#define FSSH_B_READ_ONLY 		FSSH_O_RDONLY	// read only
#define FSSH_B_WRITE_ONLY 		FSSH_O_WRONLY 	// write only
#define FSSH_B_READ_WRITE		FSSH_O_RDWR   	// read and write

#define	FSSH_B_FAIL_IF_EXISTS	FSSH_O_EXCL		// exclusive create
#define FSSH_B_CREATE_FILE		FSSH_O_CREAT	// create the file
#define FSSH_B_ERASE_FILE		FSSH_O_TRUNC	// erase the file's data
#define FSSH_B_OPEN_AT_END	   	FSSH_O_APPEND	// point to the end of the data

// Node Flavors
enum fssh_node_flavor {
  FSSH_B_FILE_NODE		= 0x01,
  FSSH_B_SYMLINK_NODE	= 0x02,
  FSSH_B_DIRECTORY_NODE	= 0x04,
  FSSH_B_ANY_NODE		= 0x07
};

#if defined(__GNUC__) && __GNUC__ > 3
#define fssh_offsetof(type,member)   __builtin_offsetof(type, member)
#else
#define fssh_offsetof(type,member) ((size_t)&((type*)0)->member)
#endif

#define fssh_alignof(type)   __alignof__(type)

#define fssh_min_c(a,b) ((a)>(b)?(b):(a))
#define fssh_max_c(a,b) ((a)>(b)?(a):(b))

#define _FSSH_PACKED	__attribute__((packed))

#endif	// _FSSH_DEFS_H


Factory
import java.security.PrivateKey
import java.security.PublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher

/**
 * ClassName:Test
 * Description:
 */
val privateStr = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDERgoVmM/RDqtCOEdLF/6mvQQ6\n" +
        "XVVdV7JOngjIOhhsSrycF7HXvgiU8mH2DSMT8CRMpu5zHpt9Dk93G1Uni5HBNbsaB/2jhWVct8di\n" +
        "cZnw38SCeqbeDrGYkxzbsMXelgxeu13iRTk07Q/0AxV3tSkIQncooYDCr240kHpsExFTJks89OyR\n" +
        "dXQ1FPwbc05IYJzcTQ2tip3lSvdVZWpr7Ng+Fk4MdfllmwRO0RiiTDKugoMYAM0wFPWLgk0JGhZ2\n" +
        "TcuHBpO0qAQB1HpgHuVERqsgQql255pwh79iw8pGTGgg2GTfJ1beNV54in5DfFjMEmJ9VJDiJG98\n" +
        "XXT77GW7mH1RAgMBAAECggEAVy4dEJa9yEhRvaot0Kcpz3opxJrsbfekFdOQZw+XBZL00AieUAvy\n" +
        "1+YJqTcQm6yRExMa2zt/KT8QAQG9A0G1TjLFlrxx5w47hcGD6LA5Bor+SE6ejAfOzsyZhuOwIDxZ\n" +
        "5kInY3gH/wBFk8dC49cuEKMlNoD2JoOx2dtK5XJawal7meUoMs4FBLILSETYCN5P8zTTRw7iMiLg\n" +
        "iuECnRw4IismsD6FiSjR8JgqL2MQyzNRpag52g5Ih+VZfk3b4Zpyqb/mhHFC1pGhXJf0H1jGCv8K\n" +
        "6h6yZ2VoiGdWlSNGcVwOQgiIAoVnWHIcAl8DCVKDKkv08w3e7GuppOoXoCEPGQKBgQDkooygYYg6\n" +
        "VetgJf2yNuJWnj8pPzI5GHGlYrVr8i+i0XkZOaXbeNZ5ORyqnv3onq+uDR9a3EktuiihR5TbQcaQ\n" +
        "4uD+N9ZiRfu6zQsSh0iiwL3WutqO9yzps+j4yXwFRl7HL0Xz93VxqMB8Y0j3ysl5Lw0jksrt4us2\n" +
        "FDNWA7ZDFwKBgQDbw+1V+/xsji0KBk7cDsOVUwfNbSXZ4KlitkHpj9Kn2fNCVjSnii5qiKB6Qift\n" +
        "YsmOPYlZrvSvpk/3q7do1Zm2Uk2B5Bmpr2zTgBIBWpO3QdZqtMpTwwRV1YztjfbJEmtoaSr53xYX\n" +
        "kg7zOGpZGthFRMn5o63X1UJsETdlALYj1wKBgQCLCw/auXXPhFEQuAoBR79+Td67huNUNblnixAq\n" +
        "Ba9SpXGwFY74WhSUxFbarLZdsaPFhdV7vFwEoyHyc0Xj0aygkFmkQPDv8v+UKv6A1iUmVXEeFaS1\n" +
        "LTzzI6abJm12B8W7/NPd+rBB3w6wlvDZQUolmKe06qDe6xGAYeiWdstxIQKBgQCZoM+rCiqd4I4P\n" +
        "sfUy1IdZPd/4dVK+itUeknZlRgtnF298cjMA5BIqmzREAzdSNXrdGpuHvEyE9eh1JO9kM93unH5e\n" +
        "TQy7mEylVaRAmgclVrsDgTrnby76qfyInHNmgJ/hL5PBdXhGJe6ZjFibza5eTgY7o3aFqSlzzl1B\n" +
        "GEw7pQKBgE2ab9pknuhiDRLvvhYxPM06D+Bi7MT6Xjqj69+ullmYFWsuoiBZ0zXUIypZbfl9Z2cP\n" +
        "OB3/717bLtgviBS6zTFkzBf9a/i9e/ZP3X5oMExmwhHHvxuN+9803dB/x/WPJnNJC0MTD38AMoK5\n" +
        "/nxgN8WSMQtOOgWGGT8vvvRmVDl5"

val publicStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxEYKFZjP0Q6rQjhHSxf+pr0EOl1VXVey\n" +
        "Tp4IyDoYbEq8nBex174IlPJh9


$1E	w
;6
p1_subsong	=	$26	w
p1_nmastervol	=	$28	b	new
p1_tmastervol	=	$29	b	target
p1_cmastervol	=	$2A	b	count
p1_rmastervol	=	$2B	b	reset-count
p1_onflag	=	$2C
p1_nonflag	=	$2D
p1_songrept	=	$2E
p1_plstbase	=	$30
p1_patsbase	=	$34
p1_instbase	=	$38
;4

* Referenced from voice records (one for each channel, 84 bytes per record)
pv_running	=	$0
pv_setup	=	$1
;1
pv_csampmod	=	$3
pv_lastnote	=	$4
pv_thisnote	=	$5
pv_loopctr	=	$6
pv_nybvolume	=	$8
pv_notetune	=	$A
pv_instptr	=	$C
pv_instidx	=	$10
pv_cntdown	=	$12
pv_setdma	=	$14
pv_clrdma	=	$16
pv_nvolume	=	$18	b
pv_ovolume	=	$19	b
pv_reptctr	=	$1A
pv_rsampmod	=	$1B
pv_rvslide	=	$1C
pv_cvslide	=	$1D
pv_tvslide	=	$1E
pv_svslide	=	$1F
pv_kvibrato	=	$20
pv_vibrflag	=	$21
pv_rporta	=	$22
pv_cporta	=	$23
pv_nvibrato	=	$24	w
pv_rvibrato	=	$26
pv_cvibrato	=	$27
pv_per		=	$28
;2
pv_sampstart	=	$2C
pv_kporta	=	$30
pv_tporta	=	$32
pv_samplgth	=	$34
pv_envcycle	=	$36
pv_instisv	=	$38
pv_instpsv	=	$3A
;2
pv_setint	=	$40
pv_clrint	=	$42
;4
pv_audioptr	=	$48
pv_ksampmod	=	$4C
;2
pv_finalper	=	$50	w
pv_freqset	=	$52	b

* Referenced from tfmx_parms2 (200 bytes)
p2_songrst	=	$0
p2_songend	=	$2
p2_songptr	=	$4
p2_speed	=	$6
p2_lpattidx	=	$8	w
p2_lpattctr	=	$A	w
p2_pattptr	=	$28	l
p2_pattidx	=	$48	w
p2_pattrep	=	$4A	b
p2_pattctr	=	$68	w
p2_pattcdn	=	$6A	b
p2_pattpsv	=	$88
p2_pattcsv	=	$A8

; The vbl - calls sequencer and vbl filler.

; NOTE: VERY BADLY OPTIMIZED!  Could be trillions of times better!

do_music	move.w #$2500,sr
		;BSR Set_DMA
		MOVEM.L D0-D7/A0-A6,-(SP)
		;move.w #$303,$FFFF8240.w
		;BSR Vbl_play
		;move.w #$030,$FFFF8240.w
		;BSR calcnextdmaptrs
		;BSR tfmx_irqhdl
		;move.w #$000,$FFFF8240.w
		MOVEM.L (SP)+,D0-D7/A0-A6
		RTE

; Vbl pla


format='PNG')
            temp_files.append(temp.name)
            temp.close()
        print("🖨 รวมเป็น PDF ด้วย img2pdf...")
        with open(output_file, "wb") as f:
            f.write(img2pdf.convert(temp_files))
        print(f"✅ บันทึก PDF เป็น: {output_file}")
    finally:
        for fname in temp_files:
            try:
                os.remove(fname)
            except Exception:
                pass
def save_as_png(images, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    print("💾 บันทึกเป็น PNG...")
    for page, img in images:
        filename = os.path.join(output_dir, f"{page:03d}.png")
        img.save(filename)
    print(f"✅ บันทึก PNG ทั้งหมดที่โฟลเดอร์: {output_dir}")

def main():
    parser = argparse.ArgumentParser(description="📚 ดาวน์โหลดหนังสือจาก AnyFlip และบันทึกเป็น PDF หรือ PNG")
    parser.add_argument("url", help="URL หนังสือ เช่น https://anyflip.com/author/book")
    parser.add_argument("-s", "--start", type=int, help="หน้าที่เริ่มต้น (default=1)")
    parser.add_argument("-e", "--end", type=int, help="หน้าสุดท้าย (default=ตรวจอัตโนมัติ)")
    parser.add_argument("-f", "--format", choices=["pdf", "png"], default="pdf", help="รูปแบบ output: pdf หรือ png")
    parser.add_argument("-o", "--output", default="output.pdf", help="ชื่อไฟล์ PDF หรือโฟลเดอร์ PNG")
    parser.add_argument("-t", "--threads", type=int, default=8, help="จำนวน threads สำหรับดาวน์โหลด (default=8)")
    parser.add_argument("--detect-threads", type=int, default=4, help="จำนวน threads สำหรับตรวจสอบจำนวนหน้า (default=4)")
    parser.add_argument("-pf", "--pdf-format", choices=["JPEG", "PNG"], default="JPEG", help="ฟอร์แมตไฟล์ภาพสำหรับ PDF (JPEG หรือ PNG, default=JPEG)")
    parser.add_argument("-pq", "--pdf-quality", type=int, default=95, help="คุณภาพ JPEG สำหรับ PDF (1-100, default=95)")

    args = parser.parse_args()

    # Setup requests session with retries
    session = requests.Session()
    retries = Retry(total=3, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504])
    adapter = HTTPAdapter(max_retries=retries)
    session.mount('http://', adapter)
    session.mount('https://', adapter)

    try:
        book_path = extract_book_path(args.url)
    except ValueError as e:
        print(f"❌ Error: {e}")
        return

    config_js = None
    filenames = []
    use_large = False
    page_count = None

    # พยายามดึง config.js ถ้าได้จะใช้ large, ถ้าไม่ได้จะใช้ mobile
    try:
        config_js = fetch_config_js(book_path, session)
        filenames = parse_page_filenames(config_js)
        use_large = bool(filenames)
        page_count = len(filenames)
    except Exception as e:
        print(f"⚠ ไม่สามารถโหลด config.js: {e} (จะใช้โหมด mobile)")
        use_large = False
        filenames = []
        page_count = None

    # กำหนดจำนวนหน้าทั้งหมด
    total_pages = args.end
    if total_pages is None:
        if page_count:
            total_pages = page_count
        elif not use_large:
            print("🔍 กำลังตรวจสอบจำนวนหน้า (mobile)...")
            total_pages = estimate_page_count(book_path, session=session)
        elif use_large:
            total_pages = len(filenames)
        if total_pages is None or total_pages == 0:
            print("❌ ไม่สามารถตรวจสอบจำนวนหน้าได้ กรุณาระบุ --end ด้วยตนเอง")
            return

    start_page = args.start if args.start is not None else 1
    end_page = total_pages
    args.format = "pdf" if args.output.lower().endswith('.pdf') else args.format

    if start_page > end_page:
        print("❌ start page ต้องไม่มากกว่า end page")
        return
    images = download_images(book_path, start_page, end_page, session, use_large, filenames)

    if args.format == "pdf":
        save_as_pdf(images, args.output, pdf_format=args.pdf_format, pdf_quality=args.pdf_quality)
    else:
        save_as_png(images, args.output)

if __name__ == "__main__":
    main()


![NeuronValue(0); 2].into(),
            effects: vec![Effect(0); 4].into(),
            input_neurons: vec![].into(),
            output_neurons: vec![2usize].into(),
        };
        match Network::with_params(params) {
            Err(Error::InvalidNeuronIndex) => (),
            _ => panic!(),
        }
    }

    #[test]
    fn tick_io() {
        let tresholds = vec![
            NeuronValue(0),
            NeuronValue(16),
            NeuronValue(-16),
        ].into();

        let effects = vec![
            Effect(-8), Effect(1), Effect(2),
            Effect(-17), Effect(127), Effect(0),
            Effect(127), Effect(0), Effect(0),
        ].into();

        let input_neurons = vec![
            2,
            0,
        ].into();

        let output_neurons = vec![
            2,
            0,
            1,
        ].into();

        let mut net = Network::with_params(NetworkParams {
            tresholds,
            effects,
            input_neurons,
            output_neurons,
        }).unwrap();

        // first evaluate 2 ticks for expected output
        net.tick();

        assert_eq!(
            net.last_accumulator_buf(),
            &[
                NeuronValue(1),
                NeuronValue(129),
                NeuronValue(-8),
            ],
        );

        net.tick();

        assert_eq!(
            net.last_accumulator_buf(),
            &[
                NeuronValue(-16),
                NeuronValue(256),
                NeuronValue(-8),
            ],
        );

        // then check if inputs and outputs are handled correctly
        net.apply_inputs(
            &[
                NeuronValue(-9),
                NeuronValue(0),
            ]
        );

        net.tick();

        assert_eq!(
            net.last_accumulator_buf(),
            &[
                NeuronValue(-17),
                NeuronValue(127),
                NeuronValue(0),
            ],
        );

        let mut outputs = [NeuronValue(0); 3];

        net.read_outputs(&mut outputs);

        assert_eq!(
            &outputs,
            &[
                NeuronValue(0),
                NeuronValue(-17),
                NeuronValue(127),
            ],
        );
    }
}
#[macro_use]
extern crate tracing;
#[macro_use]
extern crate lazy_static;

pub mod configuration;
pub mod models;
pub mod routes;
pub mod startup;
pub mod telemetry;
use ndarray::{Array2, Axis};
use std::collections::BTreeSet;

fn checked_neighbors(x: usize, y: usize, n: usize, m: usize) -> Vec<(usize, usize)> {
    let (i_x, i_y, i_n, i_m) = (x as isize, y as isize, n as isize, m as isize);
    let mut out = Vec::new();
    for n_x in i_x - 1..=i_x + 1 {
        if n_x < 0 || n_x >= i_n {
            continue;
        }
        for n_y in i_y - 1..=i_y + 1 {
            if n_y >= 0 && n_y < i_m && (i_x, i_y) != (n_x, n_y) {
                out.push((n_x as usize, n_y as usize));
            }
        }
    }
    out
}

fn iterate_grid(grid: &mut Array2<u32>) -> usize {
    let mut to_check = Vec::new();
    let mut flashed = BTreeSet::new();

    for ((x, y), val) in grid.indexed_iter_mut() {
        *val += 1;
        if *val > 9 {
            to_check.push((x, y));
        }
    }

    while let Some(el @ (x


.endp

;==========================================================================
; Swap between the main screen and the split screen.
;
; Conventionally, the main screen is left as the selected context when
; the display handler is not active.
;
; Inputs:
;	C = 0	for main screen
;	C = 1	for split screen
;
; Modified:
;	X
;
; Preserved:
;	A
;
;==========================================================================
; Swap in the text screen (main if gr.0, split otherwise).
;
.proc	EditorSwapToText
	;set C=0 (main) if gr.0, C=1 (split) otherwise
	ldy		#23
	cpy		botscr

.def :ScreenSwap = *
	;check if the correct set is in place
	pha
	lda		#0
	adc		swpflg
	beq		already_there

	;Nope, we need to swap. Conveniently, the data to be swapped
	;is in a 12 byte block:
	;
	;	ROWCRS ($0054)		TXTROW ($0290)
	;	COLCRS ($0055)		TXTCOL ($0291)
	;	DINDEX ($0057)		TINDEX ($0293)
	;	SAVMSC ($0058)		TXTMSC ($0294)
	;	OLDROW ($005A)		TXTOLD ($0296)
	;	OLDCOL ($005B)		TXTOLD ($0297)
	;	OLDCHR ($005D)		TXTOLD ($0299)
	;	OLDADR ($005E)		TXTOLD ($029A)

	ldx		#11
swap_loop:
	lda		rowcrs,x
	ldy		txtrow,x
	sty		rowcrs,x
	sta		txtrow,x
	dex
	bpl		swap_loop

	;invert swap flag
	txa
	eor		swpflg
	sta		swpflg

already_there:
	pla
	rts
.endp

;==========================================================================
; Compute character address.
;
; Entry:
;	X = byte index
;	Y = line index
;
; Exit:
;	A:X = address
;
; Used:
;	ADRESS
;
.proc	ScreenComputeAddr
	jsr		ScreenComputeRangeSize
	sta		adress
	txa
	clc
	adc		adress			;row*10,20,40+col
	scc:inc	adress+1
	clc
	adc		savmsc
	tax
	lda		adress+1
	adc		savmsc+1
	rts
.endp

;==========================================================================
ScreenComputeToAddr = ScreenComputeToAddrX0.with_x
.proc	ScreenComputeToAddrX0
	ldx		#0
with_x:
	jsr		ScreenComputeAddr
	stx		toadr
	sta		toadr+1
	rts
.endp

;==========================================================================
; Compute size, in bytes, of a series of lines.
;
; Entry:
;	Y = line count
;
; Exit:
;	ADRESS+1	High byte of size
;	A			Low byte of size
;
; Preserved:
;	X
;
; Modified:
;	Y
;
.proc	ScreenComputeRangeSize
	mva		#0 adress+1
	sty		adress
	ldy		dindex
	lda		ScreenPixelWidthIds,y
	sec
	sbc		ScreenEncodingTab,y
	tay
	iny
	lda		adress
	asl
	rol		adress+1		;row*2
	asl
	rol		adress+1		;row*4
	adc		adress			;r


(it.nth(i - (j + 1)).unwrap())
            .apply(std::mem::swap);
    }
}

pub fn split(df: &DataFrame, train_ratio: f64) -> (Array2<f64>, Array2<f64>) {
    let mut matrix: Array2<f64> = df.to_ndarray::<Float64Type>().unwrap();
    random_shuffle(&mut matrix);

    let split_point = (train_ratio * matrix.nrows() as f64) as usize;

    let (train_set, test_set) = (
        matrix.slice(s![..split_point, ..]),
        matrix.slice(s![split_point.., ..]),
    );

    (train_set.to_owned(), test_set.to_owned())
}

fn sigmoid(z: Array2<f64>) -> Array2<f64> {
    z.mapv(|x| 1. / (1. + (-x).exp()))
}

fn forward_backward(
    weights: &Array2<f64>,
    bias: &f64,
    x_train: &Array2<f64>,
    y_train: &Array2<f64>,
) -> (f64, Array2<f64>, f64) {
    // forward
    let y_head: Array2<f64> = sigmoid(weights.t().dot(x_train).mapv(|x| x + bias));
    let loss = (y_train * &(y_head.mapv(|z| z.ln()))
        + &((y_train.mapv(|z| 1. - z)) * &y_head.mapv(|z| (1. - z).ln())))
        .mapv(|z| -1. * z);
    let cost = loss.sum() / x_train.ncols() as f64;

    // backward
    let d_weights = (x_train.dot(&(&y_head - y_train).t())).mapv(|z| z / x_train.ncols() as f64);
    let d_bias = (&y_head - y_train).sum() / x_train.ncols() as f64;

    (cost, d_weights, d_bias)
}

fn update(
    weights: Array2<f64>,
    bias: f64,
    x_train: Array2<f64>,
    y_train: Array2<f64>,
    learning_rate: f64,
    iterations: usize,
) -> (Vec<f64>, Array2<f64>, f64) {
    let mut costs: Vec<f64> = Vec::new();
    let mut weights = weights;
    let mut bias = bias;

    for _ in 0..iterations {
        let (cost, d_weight, d_bias) = forward_backward(&weights, &bias, &x_train, &y_train);
        weights -= &d_weight.mapv(|x| learning_rate * x);
        bias -= learning_rate * d_bias;

        costs.push(cost);
    }

    (costs, weights, bias)
}

pub fn train(
    train_set: &Array2<f64>,
    learning_rate: f64,
    iterations: usize,
) -> (Vec<f64>, Array2<f64>, f64) {
    let x_train: Array2<f64> = train_set.slice(s![.., ..-1]).t().to_owned();
    let y_train: Array2<f64> = train_set.slice(s![.., -1..]).t().to_owned();

    let weights = Array2::from_elem([x_train.nrows(), 1], 0.01);
    let bias = 0.0;

    update(weights, bias, x_train, y_train, learning_rate, iterations)
}

fn predict(weights: &Array2<f64>, bias: &f64, x_test: &Array2<f64>) -> Array2<f64> {
    sigmoid((&weights.t().dot(x_test)).mapv(|z| z + bias)).mapv(|z| if z <= 0.5 { 0. } else { 1. })
}

fn metrics(y_test: &Array2<f64>, y_pred: &Array2<f64>) -> (f64, f64, f64, f64) {
    // 100. - (y_pred - y_test).mapv(|z| z.abs() * 100.).mean().


"Application/Type" {
    export type Native = string | number | boolean;
    export type HashMap<T> = {
        [key: string]: T;
    };
}
/// <amd-module name="Application/_Interface/ISerializableState" />
declare module "Application/_Interface/ISerializableState" {
    import { HashMap, Native } from "Application/Type";
    /**
     * Интерфейс, который нужно поддержать компонентам, что бы их можно было сериализовать
     * и восстановливать их состояние в любой момент
     * @name Core/Request/ISerializableState
     * @interface
     * @example
     * <pre>
     * const DEFAULT_STATE = {
     *     // ...
     * }
     * class Control implements ISerializableState {
     *    private __uid: string;
     *    protected _state: HashMap<Native>;
     *    constructor(...args) {
     *        stateReceiver.register(this.__uid, this);
     *        // ...
     *    }
     *    getState(): HashMap<Native> {
     *        return this._state || {}
     *    }
     *    setState(data: HashMap<Native>): void {
     *        this._state = {
     *            ...DEFAULT_STATE,
     *            ...data
     *        }
     *        this._redraw();
     *    }
     *    destroy() {
     *        stateReceiver.unregister(this.__uid);
     *        // ...
     *    }
     * }
     * </pre>
     */
    export interface ISerializableState {
        /**
         * Получаем состояние для сериализации
         * @return {HashMap<string>}
         * @name Core/Request/ISerializableState#getState
         * @method
         */
        getState(): HashMap<Native>;
        /**
         * Устанавливаем состоиня после десериализации
         * @param {HashMap<string>} data
         * @name Core/Request/ISerializableState#setState
         * @method
         */
        setState(data: HashMap<Native>): void;
    }
}
/// <amd-module name="Application/_Config/Config" />
declare module "Application/_Config/Config" {
    import { ISerializableState } from "Application/_Interface/ISerializableState";
    import { HashMap, Native } from "Application/Type";
    export default class Config implements ISerializableState {
        private data;
        private __uid;
        constructor(data?: HashMap<Native>, __uid?: string);
        get(key: string): Native;
        getState(): HashMap<Native>;
        setState(data: HashMap<Native>): void;
        getUID(): string;
    }
}
/// <amd-module name="Application/_Interface/IStore" />
declare module "Application/_Interface/IStore" {
    /**
     * Описание интерфейса компонента, для работы неким Storage.
     * Необходим для того что бы создавать хранилище на клиенте и на сервисе представления.
     * @interface
     * @name Application/_Interface/IStorage
     */
    export interface IStore<T = string> {
        get(key: string): T | null;
        set(key: string, value: T): boolean;
        remove(key: string): void;
        getKeys(): string[];
        toObject(): {
            [key: string]: string;
        };
    }
    export interface IStoreMap {
        [propName: string]: IStore;
    }
}
/// <amd-module name="Application/_Env/Browser/Store" />
declare module "Application/_Env/Browser/Store" {
    import { IStore } from "Application/_Interface/IStore";
    /**
     * Эмуляция любого Storage браузера
     */
    export class FakeWebStorage implements Storage {
        private __data;
        readonly length: number;
        getItem(key: string): any;
        setItem


        for_each_row(
            &mut buffer_layout,
            &mut buffer,
            RGBA,
            None,
            None,
            &segments,
            BLACKF,
            &None,
            &|layer| styles[&layer].clone(),
        );

        let tiles = buffer_layout.slices(&mut buffer);

        assert_eq!(
            tiles.iter().map(|slice| slice.to_vec()).collect::<Vec<_>>(),
            // First two tiles need to be completely red.
            iter::repeat(vec![RED_RGBA; TILE_SIZE].concat())
                .take(TILE_SIZE)
                .chain(iter::repeat(vec![RED_RGBA; TILE_SIZE].concat()).take(TILE_SIZE))
                .chain(
                    // The last tile contains one blue and one green line.
                    iter::once(vec![BLUE_RGBA; TILE_SIZE].concat())
                        .chain(iter::once(vec![GREEN_RGBA; TILE_SIZE].concat()))
                        // Followed by black lines (clear color).
                        .chain(
                            iter::repeat(vec![BLACK_RGBA; TILE_SIZE].concat()).take(TILE_SIZE - 2)
                        )
                )
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn crop() {
        let mut buffer = vec![0u8; TILE_SIZE * TILE_SIZE * 9 * 4];

        let mut buffer_layout = LinearLayout::new(TILE_SIZE * 3, TILE_SIZE * 3 * 4, TILE_SIZE * 3);

        let mut segments = vec![];
        for j in 0..3 {
            for y in 0..TILE_SIZE {
                segments.push(PixelSegment::new(
                    false,
                    j,
                    0,
                    0,
                    y as u8,
                    TILE_SIZE as u8 - 1,
                    0,
                    PIXEL_WIDTH as i8,
                ));
            }
        }

        segments.sort();

        let mut styles = HashMap::new();

        styles.insert(0, Style { fill: Fill::Solid(BLUEF), ..Default::default() });

        for_each_row(
            &mut buffer_layout,
            &mut buffer,
            RGBA,
            None,
            None,
            &segments,
            REDF,
            &Some(Rect::new(TILE_SIZE..TILE_SIZE * 2 + TILE_SIZE / 2, TILE_SIZE..TILE_SIZE * 2)),
            &|layer| styles[&layer].clone(),
        );

        let tiles = buffer_layout.slices(&mut buffer);

        assert_eq!(
            tiles.iter().map(|slice| slice.to_vec()).collect::<Vec<_>>(),
            // First row of tiles needs to be completely black.
            iter::repeat(vec![0u8; TILE_SIZE * 4])
                .take(TILE_SIZE * 3)
                // Second row begins with a black tile.
                .chain(iter::repeat(vec![0u8; TILE_SIZE * 4]).take(TILE_SIZE))
                .chain(iter::repeat(vec![BLUE_RGBA; TILE_SIZE].concat()).take(TILE_SIZE * 2))
                // Third row of tiles needs to be completely black as well.
                .chain(iter::repeat(vec![0u8; TILE_SIZE * 4]).take(TILE_SIZE * 3))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn tiles_len() {
        let width = TILE_SIZE * 4;
        let width_stride = TILE_SIZE * 5 * 4;
        let height = TILE_SIZE * 8;

        let buffer_layout = LinearLayout::new(width, width_s


k;

		default:
			{
				btAssert(0);
			}
		}
}

void btBulletXmlWorldImporter::auto_serialize_root_level_children(TiXmlNode* pParent)
{
	int numChildren = 0;
	btAssert(pParent);
	if (pParent)
	{
		TiXmlNode*pChild;
		for ( pChild = pParent->FirstChild(); pChild != 0; pChild = pChild->NextSibling(), numChildren++)
		{
//			printf("child Name=%s\n", pChild->Value());
			if (!strcmp(pChild->Value(),"btVector3FloatData"))
			{
				int ptr;
				get_int_attribute_by_name(pChild->ToElement(),"pointer",&ptr);

				btAlignedObjectArray<btVector3FloatData> v;
				deSerializeVector3FloatData(pChild,v);
				int numVectors = v.size();
				btVector3FloatData* vectors= (btVector3FloatData*) btAlignedAlloc(sizeof(btVector3FloatData)*numVectors,16);
				for (int i=0;i<numVectors;i++)
					vectors[i] = v[i];
				m_floatVertexArrays.push_back(vectors);
				m_pointerLookup.insert((void*)ptr,vectors);
				continue;
			}

			if (!strcmp(pChild->Value(),"btGeneric6DofConstraintData"))
			{
				deSerializeGeneric6DofConstraintData(pChild);
				continue;
			}

			if (!strcmp(pChild->Value(),"btStaticPlaneShapeData"))
			{
				deSerializeStaticPlaneShapeData(pChild);
				continue;
			}

			if (!strcmp(pChild->Value(),"btCompoundShapeData"))
			{
				deSerializeCompoundShapeData(pChild);
				continue;
			}

			if (!strcmp(pChild->Value(),"btCompoundShapeChildData"))
			{
				deSerializeCompoundShapeChildData(pChild);
				continue;
			}

			if (!strcmp(pChild->Value(),"btConvexHullShapeData"))
			{
				deSerializeConvexHullShapeData(pChild);
				continue;
			}

			if (!strcmp(pChild->Value(),"btDynamicsWorldFloatData"))
			{
				deSerializeDynamicsWorldData(pChild);
				continue;
			}

			if (!strcmp(pChild->Value(),"btConvexInternalShapeData"))
			{
				deSerializeConvexInternalShapeData(pChild);
				continue;
			}
			if (!strcmp(pChild->Value(),"btRigidBodyFloatData"))
			{
				deSerializeRigidBodyFloatData(pChild);
				continue;
			}

			//printf("Error: btBulletXmlWorldImporter doesn't support %s yet\n", pChild->Value());
		//	btAssert(0);
		}
	}

	///=================================================================
	///fixup pointers in various places, in the right order

	//fixup compoundshape child data
	for (int i=0;i<m_compoundShapeChildDataArrays.size();i++)
	{
		btAlignedObjectArray<btCompoundShapeChildData>* childDataArray = m_compoundShapeChildDataArrays[i];
		for (int c=0;c<childDataArray->size();c++)
		{
			btCompoundShapeChildData* childData = &childDataArray->at(c);
			btCollisionShapeData** ptrptr = (btCollisionShapeData**)


iew)
    RecyclerView recyclerview;
    @BindView(R.id.id_swiperefreshlayout)
    SwipeRefreshLayout idSwiperefreshlayout;
    private DoubanFilmPresenter doubanFilmPresenter;
    private FilmUsBoxAdapter filmUsBoxAdapter;

    public static FilmGodFragment newInstance() {

        Bundle args = new Bundle();

        FilmGodFragment fragment = new FilmGodFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fim_live, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        filmUsBoxAdapter = new FilmUsBoxAdapter(getActivity());
        doubanFilmPresenter = new DoubanFilmPresenter(getActivity());
        doubanFilmPresenter.getUsBox(this);
        idSwiperefreshlayout.setColorSchemeColors(ThemeUtils.getThemeColor());
        idSwiperefreshlayout.setOnRefreshListener(this);

        recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 3));

        SpacesItemDecoration spacesItemDecoration=new SpacesItemDecoration(ScreenUtils.dipToPx(getActivity(),10),ScreenUtils.dipToPx(getActivity(),10),ScreenUtils.dipToPx(getActivity(),10),0);
        recyclerview.addItemDecoration(spacesItemDecoration);
        recyclerview.setAdapter(filmUsBoxAdapter);
    }

    @Override
    public boolean hasMultiFragment() {
        return false;
    }

    @Override
    protected String setFragmentName() {
        return null;
    }

    @Override
    public void getFilmUsBoxSuccess(FilmUsBox filmUsBox) {

        filmUsBoxAdapter.setDatas(filmUsBox.getSubjects());
        filmUsBoxAdapter.notifyDataSetChanged();
        filmUsBoxAdapter.setOnItemClickListener(new EasyRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position, Object data) {
                Intent intent=new Intent(getActivity(),FilmDetailActivity.class);
                intent.putExtra(FilmDetailActivity.EXTRA_ID,filmUsBox.getSubjects().get(position).getSubject().getId());
                startThActivityByIntent(intent);
            }
        });

    }

    @Override
    public void getDataFail() {

    }

    @Override
    public void onRefresh() {
        doubanFilmPresenter.getUsBox(this);

        idSwiperefreshlayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (idSwiperefreshlayout != null) {
                    idSwiperefreshlayout.setRefreshing(false);
                }
            }
        },2000);
    }
}
package forezp.com.douyalibrary.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Bitmap 操作类 ,
 * Created by b508a on 2015/12/28.
 */
public class BitmapU


 CharSequence?, p1: Int, p2: Int, p3: Int) {
            tvDesNum.text = "${p1 + p3}/200"
        }

        override fun afterTextChanged(p0: Editable?) {}
    }

    /**
     * 标题的监听器
     */
    @SuppressLint("SetTextI18n")
    inner class TitleTextWatcher : TextWatcher {
        init {
          tvTitleNum.text = "12"
        }
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            tvTitleNum.text = (12 - p1 - p3).toString()
        }

        override fun afterTextChanged(p0: Editable?) {}
    }
}package com.cyxbs.pages.volunteer.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.cyxbs.pages.volunteer.R

class PopupWindowRvAdapter(private var dataList: List<String>, private val onItemClick: (String) -> Unit) : RecyclerView.Adapter<PopupWindowRvAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var tv_year: TextView
        init {
            tv_year = view.findViewById<TextView>(R.id.tv_year)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PopupWindowRvAdapter.ViewHolder {
        return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.volunteer_item_pop_window, parent, false))
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        holder.tv_year.text = holder.itemView.context.getString(R.string.volunteer_string_year, dataList[position])
        holder.itemView.setOnClickListener { onItemClick(dataList[position]) }
    }

}package com.cyxbs.pages.volunteer.widget

import android.content.Context
import android.os.Bundle
import android.widget.TextView
import com.cyxbs.pages.volunteer.R
import com.cyxbs.pages.volunteer.bean.VolunteerAffair
import com.cyxbs.pages.volunteer.utils.DateUtils.stamp2Date
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.cyxbs.components.view.text.MarqueeTextView

/**
 * Created by yyfbe, Date on 2020/9/5.
 */
class VolunteerAffairBottomSheetDialog(
    context: Context
) : BottomSheetDialog(context, com.cyxbs.components.config.R.style.ConfigBottomSheetDialogTheme) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.volunteer_layout_volunteer_affair_detail)
    }

    fun refresh(volunteerAffair: VolunteerAffair) {
        findViewById<MarqueeTextView>(R.id.tv_volunteer_affair_detail_title)?.text =
            volunteerAffair.name
        findViewById<TextView>(R.id.tv_volunteer_affair_detail_description)?.text =
            volunteerAffair.description
        findViewById<TextView>(R.id.tv_volunteer_affair_detail_sign_up_end_time)?.text =
            stamp2Date(volunteerAffair.lastDate)
        findViewById<TextView>(R.id.tv_volunteer_affair_detail_service_time)?.text =
            stamp2Date(volunteerAffair.date)
        findViewById<TextView>(R.id.tv_volunteer_affair_detail_time_value)?.text =


tify.pojo.WeworkNotifyTextMessage
import com.tencent.devops.notify.service.EmailService
import com.tencent.devops.notify.service.RtxService
import com.tencent.devops.notify.service.SmsService
import com.tencent.devops.notify.service.VoiceService
import com.tencent.devops.notify.service.WechatService
import com.tencent.devops.notify.service.WeworkService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class NotifyMessageConsumer @Autowired constructor(
    private val rtxService: RtxService,
    private val emailService: EmailService,
    private val smsService: SmsService,
    private val wechatService: WechatService,
    private val weworkService: WeworkService,
    private val voiceService: VoiceService
) {
    companion object {
        private val logger = LoggerFactory.getLogger(NotifyMessageConsumer::class.java)
    }

    fun onReceiveRtxMessage(rtxNotifyMessageWithOperation: RtxNotifyMessageWithOperation) {
        try {
            rtxService.sendMessage(rtxNotifyMessageWithOperation)
        } catch (ignored: Exception) {
            logger.warn("Failed process received RTX message", ignored)
        }
    }

    fun onReceiveEmailMessage(emailNotifyMessageWithOperation: EmailNotifyMessageWithOperation) {
        try {
            emailService.sendMessage(emailNotifyMessageWithOperation)
        } catch (ignored: Exception) {
            logger.warn("Failed process received Email message", ignored)
        }
    }

    fun onReceiveSmsMessage(smsNotifyMessageWithOperation: SmsNotifyMessageWithOperation) {
        try {
            smsService.sendMessage(smsNotifyMessageWithOperation)
        } catch (ignored: Exception) {
            logger.warn("Failed process received SMS message", ignored)
        }
    }

    fun onReceiveVoiceMessage(voiceNotifyMessageWithOperation: VoiceNotifyMessageWithOperation) {
        try {
            voiceService.sendMessage(voiceNotifyMessageWithOperation)
        } catch (e: Exception) {
            logger.warn("Failed process received voice message", e)
        }
    }

    fun onReceiveWechatMessage(wechatNotifyMessageWithOperation: WechatNotifyMessageWithOperation) {
        try {
            wechatService.sendMessage(wechatNotifyMessageWithOperation)
        } catch (ignored: Exception) {
            logger.warn("Failed process received Wechat message", ignored)
        }
    }

    fun onReceiveWeworkMessage(weworkNotifyMessageWithOperation: WeworkNotifyMessageWithOperation) {
        try {
            val weworkNotifyTextMessage = WeworkNotifyTextMessage(
                receivers = weworkNotifyMessageWithOperation.getReceivers(),
                receiverType = WeworkReceiverType.single,
                textType = if (weworkNotifyMessageWithOperation.markdownContent) {
                    WeworkTextType.markdown
                } else {
                    WeworkTextType.text
                },
                message = weworkNotifyMessageWithOperation.body
            )
            weworkService.sendTextMessage(weworkNotifyTextMessage)
        } catch (ignored: Exception) {
            logger.warn("Failed process received Wework message", ignored)
        }
    }
}
/*
 * Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
 *
 * Copyright (C) 2019 Tencent.  All rights reserved.
 *
 * BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
 *
 * A copy of the MIT License is included in this file.
 *
 *
 * Terms of the MIT License


alty_program:
        loyalty_program = ref_doc.loyalty_program
    else:
        loyalty_program = frappe.db.get_value("Customer", ref_doc.customer, ["loyalty_program"])

    if (
    loyalty_program
    and frappe.db.get_value("Loyalty Program", loyalty_program, ["company"]) != ref_doc.company
    ):
        frappe.throw(_("The Loyalty Program isn't valid for the selected company"))

    if loyalty_program and points_to_redeem:
        loyalty_program_details = get_loyalty_program_details_with_points(
            ref_doc.customer, loyalty_program, posting_date, ref_doc.company
        )

    if points_to_redeem > loyalty_program_details.loyalty_points:
        frappe.throw(_("You don't have enough Loyalty Points to redeem"))

    loyalty_amount = flt(points_to_redeem * loyalty_program_details.conversion_factor)

    if loyalty_amount > ref_doc.grand_total and not ref_doc.is_return:
        frappe.throw(_("You can't redeem Loyalty Points having more value than the Rounded Total."))

    if not ref_doc.loyalty_amount and ref_doc.loyalty_amount != loyalty_amount:
        ref_doc.loyalty_amount = loyalty_amount

    if ref_doc.doctype == "Sales Invoice":
        ref_doc.loyalty_program = loyalty_program
        if not ref_doc.loyalty_redemption_account:
            ref_doc.loyalty_redemption_account = loyalty_program_details.expense_account

        if not ref_doc.loyalty_redemption_cost_center:
            ref_doc.loyalty_redemption_cost_center = loyalty_program_details.cost_center

    elif ref_doc.doctype == "Sales Order":
        return loyalty_amount


":{
                "id":"rule1",
                "sql":"SELECT * FROM stream1",
                "actions":[
                    {
                        "log":{
                        }
                    }]
            }
        }]
}
```

### 3.2 显示规则列表

```json
{
    "commands":[
        {
            "url":"/rules",
            "description":"list rule",
            "method":"get"
        }]
}
```

### 3.3 获取规则 rule1

```json
{
    "commands":[
        {
            "url":"/rules/rule1",
            "description":"get rule1",
            "method":"get"
        }]
}
```

### 3.4 删除规则 rule1

```json
{
    "commands":[
        {
            "url":"/rules/rule1",
            "description":"del rule1",
            "method":"delete"
        }]
}

```
### 3.5 停止规则 rule1

```json
{
    "commands":[
        {
            "url":"/rules/rule1/stop",
            "description":"stop rule1",
            "method":"post"
        }]
}
```

### 3.6 启动规则 rule1

```json
{
    "commands":[
        {
            "url":"/rules/rule1/start",
            "description":"start rule1",
            "method":"post"
        }]
}
```

### 3.7 重启规则 rule1

```json
{
    "commands":[
        {
            "url":"/rules/rule1/restart",
            "description":"restart rule1",
            "method":"post"
        }]
}
```

### 3.8 替换并重启规则 rule1

```json
{
    "commands":[
        {
            "url":"/rules/rule1",
            "description":"update rule1",
            "method":"put",
            "data":{
                "id":"rule1",
                "sql":"SELECT * FROM stream1",
                "actions":[
                    {
                        "log":{
                        }
                    }]
            }
        }]
}
```

### 3.9 显示规则 rule1 的状态

```json
{
    "commands":[
        {
            "url":"/rules/rule1/status",
            "description":"get rule1 status",
            "method":"get"
        }]
}
```

## 4 多命令集合示例：

```json
{
    "commands":[
        {
            "url":"/streams",
            "description":"create stream1",
            "method":"post",
            "data":{
                "sql":"create stream stream1 (id bigint, name string, score float) WITH ( datasource = \"topic/temperature\", FORMAT = \"json\", KEY = \"id\");"
            }
        },
        {
            "url":"/streams",
            "description":"create stream2",
            "method":"post",
            "data":{
                "sql":"create stream stream2