问:
Mixing Tag Manager GA4 events and Google Ads hotel conversions
We currently have a hotel website which uses Tag Manager to post data into GA4. The Tag Manager embed code is included in the  of all pages. On the booking confirmation page there is some inline code, below, which posts generic purchase details to the data layer, from which an Analytics Tag fires in Tag Manager and the purchase event is logged in GA4. This works fine.

```<code>window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
    event: 'purchase',
    ecommerce: {
        currency: 'EUR',
        value: 123.45,
        tax: 0.00,
        shipping: 0.00,
        affiliation: 'Some Affiliation',
        transaction_id: 'ID234',
        coupon: '',
        items: [{
            item_name: 'Item 1',
            item_id: 'SKU1',
            price: '123.00',
            item_brand: 'Our Brand',
            item_category: 'Some Category',
            quantity: '1'
        },
        {
            item_name: 'Item 2',
            item_id: 'SKU2',
            price: '0.45',
            item_brand: 'Our Brand',
            item_category: 'Some Category',
            quantity: '1'
        }],
        facebook_pixel_ecommerce_tracking: 'true',
        content_name: 'Content Name',
        content_ids: 222,333,444
    }
});
</code>```

Now we would like to use Conversion Tracking for Hotel Campaigns to log conversions in Google Ads and I'm finding it hard to understand how to do this in our implementation from that documentation.

The docs suggest calling the following code on the purchase confirmation page:

```<code>gtag('event', 'purchase', {
    'send_to': [
    'AW-GOOGLE_CONVERSION_ID/GOOGLE_CONVERSION_LABEL'
    'transaction_id': 'BOOKING_ID',
    'value': PRICE,
    'currency': 'CURRENCY',
    'items': [{
        'id': 'PARTNER_HOTEL_ID',
        'start_date': 'CHECK_IN_DATE',
        'end_date': 'CHECK_OUT_DATE'
    }]
});
</code>```

Questions:

Am I correct in saying that both snippets of code are effectively required - the first will continue to trigger the GA4 event and the second will trigger the Ads conversion? i.e. We can't merge them into a single event?

We're using the Tag Manager embed code globally across the site, which does not give us access to gtag, so actually using the second code snippet above will error in our case. Assuming we don't want to replace our global Tag Manager embed code with a GTAG script, how can we get the second snippet to work without affecting any existing tags etc?

Many thanks.

Body:
We currently have a hotel website which uses Tag Manager to post data into GA4. The Tag Manager embed code is included in the  of all pages. On the booking confirmation page there is some inline code, below, which posts generic purchase details to the data layer, from which an Analytics Tag fires in Tag Manager and the purchase event is logged in GA4. This works fine.

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
    event: 'purchase',
    ecommerce: {
        currency: 'EUR',
        value: 123.45,
        tax: 0.00,
        shipping: 0.00,
        affiliation: 'Some Affiliation',
        transaction_id: 'ID234',
        coupon: '',
        items: [{
            item_name: 'Item 1',
            item_id: 'SKU1',
            price: '123.00',
            item_brand: 'Our Brand',
            item_category: 'Some Category',
            quantity: '1'
        },
        {
            item_name: 'Item 2',
            item_id: 'SKU2',
            price: '0.45',
            item_brand: 'Our Brand',
            item_category: 'Some Category',
            quantity: '1'
        }],
        facebook_pixel_ecommerce_tracking: 'true',
        content_name: 'Content Name',
        content_ids: 222,333,444
    }
});

Now we would like to use Conversion Tracking for Hotel Campaigns to log conversions in Google Ads and I'm finding it hard to understand how to do this in our implementation from that documentation.

The docs suggest calling the following code on the purchase confirmation page:

gtag('event', 'purchase', {
    'send_to': [
    'AW-GOOGLE_CONVERSION_ID/GOOGLE_CONVERSION_LABEL'
    'transaction_id': 'BOOKING_ID',
    'value': PRICE,
    'currency': 'CURRENCY',
    'items': [{
        'id': 'PARTNER_HOTEL_ID',
        'start_date': 'CHECK_IN_DATE',
        'end_date': 'CHECK_OUT_DATE'
    }]
});

Questions:

Am I correct in saying that both snippets of code are effectively required - the first will continue to trigger the GA4 event and the second will trigger the Ads conversion? i.e. We can't merge them into a single event?

We're using the Tag Manager embed code globally across the site, which does not give us access to gtag, so actually using the second code snippet above will error in our case. Assuming we don't want to replace our global Tag Manager embed code with a GTAG script, how can we get the second snippet to work without affecting any existing tags etc?

Many thanks.


来源: stackexchange

问:
Google Cloud Memcache
Is there any C++ library/client to connect with the memcached instance created within Google Cloud Platform?
Is there any example how to configure and use Google Cloud Memcache instance in C++ application?

I found libmemcached, but I havn't found a confirmation, that it is for GCP too and how to configure it for GCP.

ContentLicense: CC BY-SA 4.0

Title: Google Cloud Memcache


问:
Looking to find a Best way to copy a collection from one server to another server with two different mongodb versions
I need to copy a collection (large data size, around 100 GB) from one database server to another server. Also both server follows two different mongodb versions.

```<code>source server - lower mongodb version

destination server - latest mongodb version
</code>```

Is there any best and faster way to make it done?

Thanks in advance.

Body:
I need to copy a collection (large data size, around 100 GB) from one database server to another server. Also both server follows two different mongodb versions.

source server - lower mongodb version

destination server - latest mongodb version

Is there any best and faster way to make it done?

Thanks in advance.


问:
cannot open shared object file: No such file or directory, even after modifying LD_LIBRARY_PATH variable
I have been trying to use PETSc for some MPI enhanced matrix operations, but I keep getting this error when I submit the job using slurm on a supercomputer:

```<code>ERROR: ERROR: LoadError: LoadError: could not load library
"/home/20ph92r03/petsc/arch-linux-c-debug/lib/libpetsc.so"
liblapack.so.3: cannot open shared object file: No such file or directorycould not
load library "/home/20ph92r03/petsc/arch-linux-c-debug/lib/libpetsc.so"
liblapack.so.3: cannot open shared object file: No such file or directory
</code>```

And this is my jobscript

```<code>#!/bin/bash
#SBATCH -J slepcTest
#SBATCH -p standard-low
#SBATCH --output=slepcTest-out
#SBATCH -n 2
#SBATCH -t 1:00:00

module load compiler/intel-mpi/mpi-2020-v4

export LD_LIBRARY_PATH=/home/21ph92r03/julia-1.8.0/lib/julia:$LD_LIBRARY_PATH

time mpiexec -n 2 /home/20ph92r03/julia-1.8.0/bin/julia mpiSlepc.jl
</code>```

I have followed the earlier threads related to the same error and modified the LD_LIBRARY_PATH environment variable in the .bashrc file, like this:

```<code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:'/home/20ph92r03/petsc/arch-linux-c-
debug/lib/:/usr/lib64/'
</code>```

But the error persists. I don't know what else to try!

Thanks!

Body:
I have been trying to use PETSc for some MPI enhanced matrix operations, but I keep getting this error when I submit the job using slurm on a supercomputer:

ERROR: ERROR: LoadError: LoadError: could not load library
"/home/20ph92r03/petsc/arch-linux-c-debug/lib/libpetsc.so"
liblapack.so.3: cannot open shared object file: No such file or directorycould not
load library "/home/20ph92r03/petsc/arch-linux-c-debug/lib/libpetsc.so"
liblapack.so.3: cannot open shared object file: No such file or directory

And this is my jobscript

#!/bin/bash
#SBATCH -J slepcTest
#SBATCH -p standard-low
#SBATCH --output=slepcTest-out
#SBATCH -n 2
#SBATCH -t 1:00:00

module load compiler/intel-mpi/mpi-2020-v4

export LD_LIBRARY_PATH=/home/21ph92r03/julia-1.8.0/lib/julia:$LD_LIBRARY_PATH

time mpiexec -n 2 /home/20ph92r03/julia-1.8.0/bin/julia mpiSlepc.jl

I have followed the earlier threads related to the same error and modified the LD_LIBRARY_PATH environment variable in the .bashrc file, like this:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:'/home/20ph92r03/petsc/arch-linux-c-
debug/lib/:/usr/lib64/'

But the error persists. I don't know what else to try!

Thanks!


问:
Index match. Calculating quota vs the actual booking values
I've an excel file wherein there are 141 sales reps and 14 managers. Those 141 sales people have been assigned to different managers randomly and their quota for a FY.

Sales reps with their managers and quota

With the help of sumifs and countif I got their yearly quota:

```<code>=SUMIFS(Quotas!$D$3:$D$143,Quotas!$B$3:$B$143,$I5)
</code>```

With the help of quota mentioned above I need to derive the actual business that sales reps have achieved.

I tried xlookup, index match, choose and nested ifs but nothing is working out.

In booking I have more than 4000 entries.

Body:
I've an excel file wherein there are 141 sales reps and 14 managers. Those 141 sales people have been assigned to different managers randomly and their quota for a FY.

Sales reps with their managers and quota

With the help of sumifs and countif I got their yearly quota:

=SUMIFS(Quotas!$D$3:$D$143,Quotas!$B$3:$B$143,$I5)

With the help of quota mentioned above I need to derive the actual business that sales reps have achieved.

I tried xlookup, index match, choose and nested ifs but nothing is working out.

In booking I have more than 4000 entries.


问:
How to plot linear regression lines on scatterplots in plotmatrix function in Matlab/Octave GNU?
Data, Plotmatrix, Scatterplot properties, and Histogram properties

```<code>clear all; close all; clc;
estudiantes=10;
materias=3;
E=410+fix(rand(1,estudiantes)*(510-410+1));
I=610+fix(rand(1,estudiantes)*(710-610+1));
M=510+fix(rand(1,estudiantes)*(610-510+1));
Y=[E; I; M]'
X=[1:10;1:10;1:10]'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%h=figure('Position',[1 21 1366 670], ...
h=figure('Position',[1 21 1920 986], ...
'Name',strcat('Correlación entre Materias - ',...
              'Pruebas Estandarizadas'));
[s, sax, bigax, h, hax]=plotmatrix(Y);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%s = scatterplot properties
Xlabel=['Español';'Español';'Inglés';'Inglés';'Matemáticas';'Matemáticas'];
Ylabel=['Inglés';'Matemáticás';'Español';'Matemáticas';'Español';'Inglés'];
for i=1:length(s)
set(s(i),'color',[1 0 0],'marker','*','markersize',20, ...
         'markerfacecolor','none','markeredgecolor','auto')
set(sax(i),'xlabel',Xlabel(i,:),...
          'fontsize',18,'fontweight','bold','fontsizemode','manual')
set(sax(i),'ylabel',Ylabel(i,:),...
          'fontsize',18,'fontweight','bold','fontsizemode','manual')
endfor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%h=histogram properties
Xlabel=['Español';'Inglés';'Matemáticas'];
Ylabel=['Cantidad';'Cantidad';'Cantidad'];
for i=1:length(h)
set(h(i),'edgecolor',[0 0 0],'facecolor',[0 0 1],...
         'linestyle','-','linewidth',1,'horizontal','off', ...
         'showbaseline','on')
set(hax(i),'xlabel',Xlabel(i,:),...
          'fontsize',18,'fontweight','bold','fontsizemode','manual')
set(hax(i),'ylabel',Ylabel(i,:),...
          'fontsize',18,'fontweight','bold','fontsizemode','manual')
endfor
</code>```

This is the output plotmatrix and properties.
randi: Return random integers in the range 1:imax.
fix: Truncate fractional portion of x and return the integer portion.
rand: Return a matrix with random elements uniformly distributed on the interval (0, 1).
figure: Create a new figure window for plotting.

i

Body:
Data, Plotmatrix, Scatterplot properties, and Histogram properties

clear all; close all; clc;
estudiantes=10;
materias=3;
E=410+fix(rand(1,estudiantes)*(510-410+1));
I=610+fix(rand(1,estudiantes)*(710-610+1));
M=510+fix(rand(1,estudiantes)*(610-510+1));
Y=[E; I; M]'
X=[1:10;1:10;1:10]'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%h=figure('Position',[1 21 1366 670], ...
h=figure('Position',[1 21 1920 986], ...
'Name',strcat('Correlación entre Materias - ',...
              'Pruebas Estandarizadas'));
[s, sax, bigax, h, hax]=plotmatrix(Y);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%s = scatterplot properties
Xlabel=['Español';'Español';'Inglés';'Inglés';'Matemáticas';'Matemáticas'];
Ylabel=['Inglés';'Matemáticás';'Español';'Matemáticas';'Español';'Inglés'];
for i=1:length(s)
set(s(i),'color',[1 0 0],'marker','*','markersize',20, ...
         'markerfacecolor','none','markeredgecolor','auto')
set(sax(i),'xlabel',Xlabel(i,:),...
          'fontsize',18,'fontweight','bold','fontsizemode','manual')
set(sax(i),'ylabel',Ylabel(i,:),...
          'fontsize',18,'fontweight','bold','fontsizemode','manual')
endfor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%h=histogram properties
Xlabel=['Español';'Inglés';'Matemáticas'];
Ylabel=['Cantidad';'Cantidad';'Cantidad'];
for i=1:length(h)
set(h(i),'edgecolor',[0 0 0],'facecolor',[0 0 1],...
         'linestyle','-','linewidth',1,'horizontal','off', ...
         'showbaseline','on')
set(hax(i),'xlabel',Xlabel(i,:),...
          'fontsize',18,'fontweight','bold','fontsizemode','manual')
set(hax(i),'ylabel',Ylabel(i,:),...
          'fontsize',18,'fontweight','bold','fontsizemode','manual')
endfor

This is the output plotmatrix and properties.
randi: Return random integers in the range 1:imax.
fix: Truncate fractional portion of x and return the integer portion.
rand: Return a matrix with random elements uniformly distributed on the interval (0, 1).
figure: Create a new figure window for plotting.

i


问:
Flutter on IntelliJ building for Android cannot find `java`
Hitting a bit of a wall here when trying to build a brand new flutter sandbox application within IntelliJ for Android.

The error that I get is the following:

```<code>java: Cannot run program "/Users/vintrin/Library/AndroidStudio/sdk/bin/java" (in directory "/Users/vintrin/Library/Caches/JetBrains/IntelliJIdea2022.3/compile-server"): error=2, No such file or directory
</code>```

This file /Users/vintrin/Library/AndroidStudio/sdk/bin/java in fact does NOT exist.

I am starting the IntelliJ from my terminal to get all the environment variables to be recognized by IntelliJ using

open -na "IntelliJ IDEA.app"
```
<p>Below you can see the print out of the values from within the IntelliJ terminal:</p>
```Viktors-MacBook-Pro:flutter_sandbox vintrino$ echo $JAVA_HOME
/usr/local/Cellar/openjdk@11/11.0.17
Viktors-MacBook-Pro:flutter_sandbox vintrino$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/usr/local/opt/coreutils/libexec/gnubin:/usr/local/opt/findutils/libexec/gnubin:/Users/vintrin/.nvm/versions/node/v15.14.0/bin:/Users/vintrin/Library/AndroidStudio/sdk/emulator:/Users/vintrin/Library/AndroidStudio/sdk/tools:/Users/vintrin/Library/AndroidStudio/sdk/tools/bin:/Users/vintrin/Library/AndroidStudio/sdk/platform-tools:/Users/vintrin/Library/AndroidStudio/sdk/cmdline-tools/latest/bin:/Users/vintrin/.toolbox/bin:/apollo/env/envImprovement/bin:/Users/vintrin/bin:/Users/nkondrat/vintrin-env/home_dir/python:/apollo/env/SDETools/bin:/apollo/env/GordianKnot/bin:/apollo/env/OctaneBrazilTools/bin:/apollo/env/envImprovement/jdk1.8/bin:/Users/nkondrat/apps/phantomjs-2.1.1-macosx/bin:/apollo/env/AmazonAwsCli/bin/:~/.rodar/bin:/Users/nkondrat/vintrin-env/home_dir/js/cli:/Users/vintrin/software/flutter/bin
Viktors-MacBook-Pro:flutter_sandbox vintrino$
```
<p>The Intellij project is set to use Android33 API</p>
<p><img src="https://i.stack.imgur.com/3BWxf.png" alt="enter image description here" /></p>
<p>The SDK is set here in Intellij</p>
<p><img src="https://i.stack.imgur.com/ieNbe.png" alt="enter image description here" /></p>
<p>And the SDK is said to be installed by Android Studio</p>
<p><img src="https://i.stack.imgur.com/wZEBH.jpg" alt="enter image description here" /></p>
<p>Running the following from intellij terminal to check java installation</p>
```Viktors-MacBook-Pro:flutter_sandbox vintrino$ $JAVA_HOME/bin/java --version
openjdk 11.0.17 2022-10-18
OpenJDK Runtime Environment Homebrew (build 11.0.17+0)
OpenJDK 64-Bit Server VM Homebrew (build 11.0.17+0, mixed mode)
```
<p>However for whatever reason when IntelliJ builds it tries to use java that doesn't exist at path:</p>
```/Users/vintrin/Library/AndroidStudio/sdk/bin/java
```
<p>The flutter doctor command is happy for android</p>
```mac> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.10, on macOS 11.4 20F71 darwin-x64, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
```

How do I resolve java not being found?

Body:
Hitting a bit of a wall here when trying to build a brand new flutter sandbox application within IntelliJ for Android.

The error that I get is the following:

java: Cannot run program "/Users/vintrin/Library/AndroidStudio/sdk/bin/java" (in directory "/Users/vintrin/Library/Caches/JetBrains/IntelliJIdea2022.3/compile-server"): error=2, No such file or directory

This file /Users/vintrin/Library/AndroidStudio/sdk/bin/java in fact does NOT exist.

I am starting the IntelliJ from my terminal to get all the environment variables to be recognized by IntelliJ using

open -na "IntelliJ IDEA.app"

Below you can see the print out of the values from within the IntelliJ terminal:

Viktors-MacBook-Pro:flutter_sandbox vintrino$ echo $JAVA_HOME
/usr/local/Cellar/openjdk@11/11.0.17
Viktors-MacBook-Pro:flutter_sandbox vintrino$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/usr/local/opt/coreutils/libexec/gnubin:/usr/local/opt/findutils/libexec/gnubin:/Users/vintrin/.nvm/versions/node/v15.14.0/bin:/Users/vintrin/Library/AndroidStudio/sdk/emulator:/Users/vintrin/Library/AndroidStudio/sdk/tools:/Users/vintrin/Library/AndroidStudio/sdk/tools/bin:/Users/vintrin/Library/AndroidStudio/sdk/platform-tools:/Users/vintrin/Library/AndroidStudio/sdk/cmdline-tools/latest/bin:/Users/vintrin/.toolbox/bin:/apollo/env/envImprovement/bin:/Users/vintrin/bin:/Users/nkondrat/vintrin-env/home_dir/python:/apollo/env/SDETools/bin:/apollo/env/GordianKnot/bin:/apollo/env/OctaneBrazilTools/bin:/apollo/env/envImprovement/jdk1.8/bin:/Users/nkondrat/apps/phantomjs-2.1.1-macosx/bin:/apollo/env/AmazonAwsCli/bin/:~/.rodar/bin:/Users/nkondrat/vintrin-env/home_dir/js/cli:/Users/vintrin/software/flutter/bin
Viktors-MacBook-Pro:flutter_sandbox vintrino$

The Intellij project is set to use Android33 API

The SDK is set here in Intellij

And the SDK is said to be installed by Android Studio

Running the following from intellij terminal to check java installation

Viktors-MacBook-Pro:flutter_sandbox vintrino$ $JAVA_HOME/bin/java --version
openjdk 11.0.17 2022-10-18
OpenJDK Runtime Environment Homebrew (build 11.0.17+0)
OpenJDK 64-Bit Server VM Homebrew (build 11.0.17+0, mixed mode)

However for whatever reason when IntelliJ builds it tries to use java that doesn't exist at path:

/Users/vintrin/Library/AndroidStudio/sdk/bin/java

The flutter doctor command is happy for android

mac> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.10, on macOS 11.4 20F71 darwin-x64, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)

How do I resolve java not being found?


问:
How to add a horizontal repeating categorical bar plot to existing diagram in MS Excel
I have two sets of time dependant data:
Column B is some kind of numerical value, represented by a line.
Column C is a categorical value (which will repeat throughout the timeline).

I would like to disply column C as exactly one horizontal bar with the value written into the bar:
barplot

Is this possible with one diagram?

I tried to add a stacked horizontal bar, but only values with numbers will be dislayed.
Categorical values won't show up.

Unfortunately, this has to work in Excel, so no Python or R  is possible.


问:
How to control a ball object in Three.js
I'm creating some sort of interactive 3d website.

I finally managed to load a 3d model into my website.
We are provided with a sphere that can be controlled with the arrowkeys.
I tried many things to replace that sphere with my imported ball object but it doesn't run correctly.

Anyone that can explain me how I can make this work.

This is the code that controls and create the sphere:

```<code>import {
  PointerLockControls,
  Sphere,
  useKeyboardControls,
} from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import { RigidBody } from "@react-three/rapier";
import { useRef } from "react";
import { Vector3 } from "three";
import { playerBall as Ball } from "Examples/Stef/World/Ball";

import { PLAYER } from "Examples/Player.config";

const RapierWorldPlayer = (props: any) => {
  const moveBackwardOn = useKeyboardControls((state) => state.moveBackward);
  const moveForwardOn = useKeyboardControls((state) => state.moveForward);
  const moveLeftOn = useKeyboardControls((state) => state.moveLeft);
  const moveRightOn = useKeyboardControls((state) => state.moveRight);

  const playerRef = useRef<any>(null!);
  const pointerRef = useRef<any>(null!);

  useFrame(() => {
    const camera = pointerRef.current.getObject();
    const player = playerRef.current;

    // Move Player.
    const playerVelocity = player.linvel(); // Get linear velocity.
    const velocityVector = new Vector3(
      (moveRightOn ? 1 : moveLeftOn ? -1 : 0) * PLAYER.VELOCITY.RIGHT_DIRECTION,
      0, // Camera quaternion should not affect velocity on gravity axis.
      (moveForwardOn ? -1 : moveBackwardOn ? 1 : 0) *
        PLAYER.VELOCITY.FORWARD_DIRECTION
    );
    // Match velocityVector direction to Camera direction.
    velocityVector.applyQuaternion(camera.quaternion);
    velocityVector.y = playerVelocity.y; // Add velocity on gravity axis back after applying camera quaternion.

    // Reset player angular velocity if no movement detected.
    if (!moveBackwardOn && !moveForwardOn && !moveLeftOn && !moveRightOn) {
      player.setAngvel(new Vector3());
    }

    // Apply linear velocity to Player.
    player.setLinvel(velocityVector);

    // Match Camera position to Player position.
    camera.position.copy(player.translation());
    camera.position.x -= 0;
    camera.position.y += 3.25; // 1.75m
    camera.position.z -= -8;
  });

  return (
    <group name="Player">
      <PointerLockControls ref={pointerRef} />

      <RigidBody
        colliders="ball"
        mass={PLAYER.MASS}
        position={PLAYER.POSITION}
        ref={playerRef}
        type="dynamic"
      >
        //This is the sphere that can be controlled.
        <Sphere args={[PLAYER.SIZE, 14, 14]}>
          <meshBasicMaterial color={0x000000} wireframe={true} />
        </Sphere>
      </RigidBody>
    </group>
  );
};

export { RapierWorldPlayer };
</code>```

I tried to import a component of the ball between the RigidBody tags but that didn't satisfied me..

My import code:

```<code>import { RigidBody } from "@react-three/rapier";
import { useGLTF } from "@react-three/drei";
import Bal from './Models/Bal.glb';
import { PLAYER } from "Examples/Player.config";

const playerBall = () => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { nodes }: any = useGLTF(Bal, true);

  return (
    <group name='Bal' position={PLAYER.POSITION}>
      <RigidBody>
        {nodes.Scene.children.map((sceneChild: any) => {
          if (sceneChild.children.length > 0) {
            return sceneChild.children.map((child: any) => (
              <mesh
                key={child.uuid}
                geometry={child.geometry}
                material={child.material}
                rotation={sceneChild.rotation}
                scale={sceneChild.scale}
                position={sceneChild.position}
              />
            ));
          } else {
            return (
              <mesh
              key={sceneChild.uuid}
              geometry={sceneChild.geometry}
              material={sceneChild.material}
              rotation={sceneChild.rotation}
              scale={sceneChild.scale}
              position={sceneChild.position}
            />
            );
          }
        })}
      </RigidBody>
    </group>
  )
}
export { playerBall } ;
</code>```

Body:
I'm creating some sort of interactive 3d website.

I finally managed to load a 3d model into my website.
We are provided with a sphere that can be controlled with the arrowkeys.
I tried many things to replace that sphere with my imported ball object but it doesn't run correctly.

Anyone that can explain me how I can make this work.

This is the code that controls and create the sphere:

import {
  PointerLockControls,
  Sphere,
  useKeyboardControls,
} from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import { RigidBody } from "@react-three/rapier";
import { useRef } from "react";
import { Vector3 } from "three";
import { playerBall as Ball } from "Examples/Stef/World/Ball";

import { PLAYER } from "Examples/Player.config";

const RapierWorldPlayer = (props: any) => {
  const moveBackwardOn = useKeyboardControls((state) => state.moveBackward);
  const moveForwardOn = useKeyboardControls((state) => state.moveForward);
  const moveLeftOn = useKeyboardControls((state) => state.moveLeft);
  const moveRightOn = useKeyboardControls((state) => state.moveRight);

  const playerRef = useRef<any>(null!);
  const pointerRef = useRef<any>(null!);

  useFrame(() => {
    const camera = pointerRef.current.getObject();
    const player = playerRef.current;

    // Move Player.
    const playerVelocity = player.linvel(); // Get linear velocity.
    const velocityVector = new Vector3(
      (moveRightOn ? 1 : moveLeftOn ? -1 : 0) * PLAYER.VELOCITY.RIGHT_DIRECTION,
      0, // Camera quaternion should not affect velocity on gravity axis.
      (moveForwardOn ? -1 : moveBackwardOn ? 1 : 0) *
        PLAYER.VELOCITY.FORWARD_DIRECTION
    );
    // Match velocityVector direction to Camera direction.
    velocityVector.applyQuaternion(camera.quaternion);
    velocityVector.y = playerVelocity.y; // Add velocity on gravity axis back after applying camera quaternion.

    // Reset player angular velocity if no movement detected.
    if (!moveBackwardOn && !moveForwardOn && !moveLeftOn && !moveRightOn) {
      player.setAngvel(new Vector3());
    }

    // Apply linear velocity to Player.
    player.setLinvel(velocityVector);

    // Match Camera position to Player position.
    camera.position.copy(player.translation());
    camera.position.x -= 0;
    camera.position.y += 3.25; // 1.75m
    camera.position.z -= -8;
  });

  return (
    <group name="Player">
      <PointerLockControls ref={pointerRef} />

      <RigidBody
        colliders="ball"
        mass={PLAYER.MASS}
        position={PLAYER.POSITION}
        ref={playerRef}
        type="dynamic"
      >
        //This is the sphere that can be controlled.
        <Sphere args={[PLAYER.SIZE, 14, 14]}>
          <meshBasicMaterial color={0x000000} wireframe={true} />
        </Sphere>
      </RigidBody>
    </group>
  );
};

export { RapierWorldPlayer };

I tried to import a component of the ball between the RigidBody tags but that didn't satisfied me..

My import code:

import { RigidBody } from "@react-three/rapier";
import { useGLTF } from "@react-three/drei";
import Bal from './Models/Bal.glb';
import { PLAYER } from "Examples/Player.config";

const playerBall = () => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { nodes }: any = useGLTF(Bal, true);

  return (
    <group name='Bal' position={PLAYER.POSITION}>
      <RigidBody>
        {nodes.Scene.children.map((sceneChild: any) => {
          if (sceneChild.children.length > 0) {
            return sceneChild.children.map((child: any) => (
              <mesh
                key={child.uuid}
                geometry={child.geometry}
                material={child.material}
                rotation={sceneChild.rotation}
                scale={sceneChild.scale}
                position={sceneChild.position}
              />
            ));
          } else {
            return (
              <mesh
              key={sceneChild.uuid}
              geometry={sceneChild.geometry}
              material={sceneChild.material}
              rotation={sceneChild.rotation}
              scale={sceneChild.scale}
              position={sceneChild.position}
            />
            );
          }
        })}
      </RigidBody>
    </group>
  )
}
export { playerBall } ;


问:
Disable Chrome browser extension autoupdate on Pixel Chromebook
Is it possible to disable autoupdates for the Chrome browser on Google Pixelbook chromebooks? This related question describes the procedure for Windows, Mac OS, and Ubuntu for Chromium. But I'd like to disable Chrome browser extension autoupdates on my Pixelbook.</p>


问:
Cyrillic letters not decoding properly from Request.Querystring
Given the following URL:

https://www.somedomain.com/uploads/6612/ce30d0c5-987a-47da-a044-fa102cea67db/c/768588207/%d1%81%d0%bd%d0%b8%d0%bd%d0%b3%d0%bc%d0%be%d0%ba.png

Where the filename is passed to the ASHX handler as filename query parameter, doing:

```<code>context.Response.Write(Request.Querystring["path"])
</code>```

Returns:

```<code>ÑÐ½Ð¸Ð½Ð³Ð¼Ð¾Ðº.png
</code>```

The raw querystring when writing Request.Querystring shows the path parameter as:

```<code>%c3%91%c2%81%c3%90%c2%bd%c3%90%c2%b8%c3%90%c2%bd%c3%90%c2%b3%c3%90%c2%bc%c3%90%c2%be%c3%90%c2%ba.png
</code>```

It all works fine for normal latin characters.

How can I correctly return снингмок.png from the querystring?

Body:
Given the following URL:

https://www.somedomain.com/uploads/6612/ce30d0c5-987a-47da-a044-fa102cea67db/c/768588207/%d1%81%d0%bd%d0%b8%d0%bd%d0%b3%d0%bc%d0%be%d0%ba.png

Where the filename is passed to the ASHX handler as filename query parameter, doing:

context.Response.Write(Request.Querystring["path"])

Returns:

ÑÐ½Ð¸Ð½Ð³Ð¼Ð¾Ðº.png

The raw querystring when writing Request.Querystring shows the path parameter as:

%c3%91%c2%81%c3%90%c2%bd%c3%90%c2%b8%c3%90%c2%bd%c3%90%c2%b3%c3%90%c2%bc%c3%90%c2%be%c3%90%c2%ba.png

It all works fine for normal latin characters.

How can I correctly return снингмок.png from the querystring?


问:
Wordpress Elementor Reusable components
I want to create reusable blocks with Elementor similar to VueJS and React. The blocks should be the same. Only the content will be different. I try to do it with template functionality, but I cannot add content outside it.</p>

Title: Wordpress Elementor Reusable components


问:
Disabling strict mode in Expo
Is there a way to disable strict mode in Expo?

Currently it is not possible to use Automatic Batching in React 18 in Expo without building the application because it does not work in strict mode.

While testing, I found that the problem with Automatic Batching only occurs when executing asynchronous code.

```<code>import {useEffect, useState} from "react";

let rerender = 0
function App() {
    rerender++
    console.log("rerender",rerender)
    const [stateOne,setStateOne] = useState(null)
    const [stateTwo,setStateTwo] = useState(false)
    const [stateThree,setStateThree] = useState('')
    useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/todos/1").then(() => {
            setStateOne({});
            setStateTwo(true)
            setStateThree('test');
        });
    }, []);
    return (
        <div></div>
    );
}

export default App;
</code>```

In this snippet, Automatic Batching does not work as long as strict mode is enabled.

Title: Disabling strict mode in Expo

Body:
Is there a way to disable strict mode in Expo?

Currently it is not possible to use Automatic Batching in React 18 in Expo without building the application because it does not work in strict mode.

While testing, I found that the problem with Automatic Batching only occurs when executing asynchronous code.

import {useEffect, useState} from "react";

let rerender = 0
function App() {
    rerender++
    console.log("rerender",rerender)
    const [stateOne,setStateOne] = useState(null)
    const [stateTwo,setStateTwo] = useState(false)
    const [stateThree,setStateThree] = useState('')
    useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/todos/1").then(() => {
            setStateOne({});
            setStateTwo(true)
            setStateThree('test');
        });
    }, []);
    return (

    );
}

export default App;

In this snippet, Automatic Batching does not work as long as strict mode is enabled.


问:
How do i set a countdown date as a variable?
I am wondering if it is actually possible to set a date in a countdown timer format.

```<code><p>Add date in number form</p>
<h1 id="timer"></h1>
<form id="set">
<input id="year" type="input" placeholder="year">
<input id="month" type="input" placeholder="month">
<input id="day" type="input" placeholder="day">
<input id="hours" type="input" placeholder="hours">
<input id="minutes" type="input" placeholder="Minutes">
<input id="seconds" type="input" placeholder="seconds">
  <input id="milliseconds" type="input" placeholder="milliseconds">
  <input onclick="submit" id="submit" type="button" placeholder="Set">
</form>
<script>
function submit() {
 var y = document.getElementById("year");
 var mo = document.getElementById("month");
 var d = document.getElementById("day");
 var h = document.getElementById("hours");
 var m = document.getElementById("minutes");
 var s = document.getElementById("seconds");
 var ms = document.getElementById("milliseconds");
 // Set the date we're counting down to
var countDownDate = new Date("mo d, y h:m:s:ms").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "Done";
  }
}, 1000);
</script>
</code>```

I was expecting it to write out the date and start counting down. The countdown is from W3Schools "How To - JavaScript countdown timer"

Body:
I am wondering if it is actually possible to set a date in a countdown timer format.

Add date in number form

<form id="set">
<input id="year" type="input" placeholder="year">
<input id="month" type="input" placeholder="month">
<input id="day" type="input" placeholder="day">
<input id="hours" type="input" placeholder="hours">
<input id="minutes" type="input" placeholder="Minutes">
<input id="seconds" type="input" placeholder="seconds">
  <input id="milliseconds" type="input" placeholder="milliseconds">
  <input onclick="submit" id="submit" type="button" placeholder="Set">
</form>

I was expecting it to write out the date and start counting down. The countdown is from W3Schools "How To - JavaScript countdown timer"


问:
How does StepMeterRegistry publish method execute in spring-boot?
```<code>package io.micrometer.core.instrument;
public interface Meter {
 ///...

 default <T> T match(Function<Gauge, T> visitGauge, Function<Counter, T> visitCounter, Function<Timer, T> visitTimer,
            Function<DistributionSummary, T> visitSummary, Function<LongTaskTimer, T> visitLongTaskTimer,
            Function<TimeGauge, T> visitTimeGauge, Function<FunctionCounter, T> visitFunctionCounter,
            Function<FunctionTimer, T> visitFunctionTimer, Function<Meter, T> visitMeter) {
        if (this instanceof TimeGauge) {
            return visitTimeGauge.apply((TimeGauge) this);
        }
        else if (this instanceof Gauge) {
            return visitGauge.apply((Gauge) this);
        }
        else if (this instanceof Counter) {
            return visitCounter.apply((Counter) this);
        }
        else if (this instanceof Timer) {
            return visitTimer.apply((Timer) this);
        }
        else if (this instanceof DistributionSummary) {
            return visitSummary.apply((DistributionSummary) this);
        }
        else if (this instanceof LongTaskTimer) {
            return visitLongTaskTimer.apply((LongTaskTimer) this);
        }
        else if (this instanceof FunctionCounter) {
            return visitFunctionCounter.apply((FunctionCounter) this);
        }
        else if (this instanceof FunctionTimer) {
            return visitFunctionTimer.apply((FunctionTimer) this);
        }
        else {
            return visitMeter.apply(this);
        }
    }

 //...
}

public class XyzMeterRegistry extends StepMeterRegistry {
 //...
    @Override
    protected void publish() {
        for (List<Meter> batch : MeterPartition.partition(this, config.batchSize())) {
            try {
                // @formatter:off
                httpClient.post(config.uri())
                        .withBasicAuthentication(config.userName(), config.password())
                        .withJsonContent(
                                batch.stream().flatMap(m -> m.match(
                                        this::writeGauge,
                                        this::writeCounter,
                                        this::writeTimer,
                                        this::writeSummary,
                                        this::writeLongTaskTimer,
                                        this::writeTimeGauge,
                                        this::writeFunctionCounter,
                                        this::writeFunctionTimer,
                                        this::writeCustomMetric)
                                ).collect(Collectors.joining(",", "[", "]"))
                        )
                        // @formatter:on
                        .send()
                        .onSuccess(response -> logger.debug("successfully sent {} metrics to kairos.", batch.size()))
                        .onError(response -> logger.error("failed to send metrics to kairos: {}", response.body()));
            }
            catch (Throwable t) {
                logger.warn("failed to send metrics to kairos", t);
            }
        }
    }

    Stream<String> writeGauge(Gauge gauge) {
        double value = gauge.value();
        if (Double.isFinite(value)) {
            return Stream.of(writeMetric(gauge.getId(), config().clock().wallTime(), value));
        }
        return Stream.empty();
    }

    Stream<String> writeCounter(Counter counter) {
        return Stream.of(writeMetric(counter.getId(), config().clock().wallTime(), counter.count()));
    }

  Stream<String> writeTimer(Timer timer) {
        long wallTime = config().clock().wallTime();
        return Stream.of(writeMetric(idWithSuffix(timer.getId(), "count"), wallTime, timer.count()),
                writeMetric(idWithSuffix(timer.getId(), "max"), wallTime, timer.max(getBaseTimeUnit())),
                writeMetric(idWithSuffix(timer.getId(), "avg"), wallTime, timer.mean(getBaseTimeUnit())),
                writeMetric(idWithSuffix(timer.getId(), "sum"), wallTime, timer.totalTime(getBaseTimeUnit())));
    }

    Stream<String> writeFunctionCounter(FunctionCounter counter) {
        double count = counter.count();
        if (Double.isFinite(count)) {
            return Stream.of(writeMetric(counter.getId(), config().clock().wallTime(), count));
        }
        return Stream.empty();
    }
  //...etc.,
}
</code>```

How the above match( ) is called from MeterRegistryComponent's publish method?
//How does here m.match(//....) is taking parameters from MeterRegistryComponent's publish method?**
//And what is the role of flatMap here?**

I just want to write custom meterregistry in which need to publish metrics using publish method

Body:
package io.micrometer.core.instrument;
public interface Meter {
 ///...

 default <T> T match(Function<Gauge, T> visitGauge, Function<Counter, T> visitCounter, Function<Timer, T> visitTimer,
            Function<DistributionSummary, T> visitSummary, Function<LongTaskTimer, T> visitLongTaskTimer,
            Function<TimeGauge, T> visitTimeGauge, Function<FunctionCounter, T> visitFunctionCounter,
            Function<FunctionTimer, T> visitFunctionTimer, Function<Meter, T> visitMeter) {
        if (this instanceof TimeGauge) {
            return visitTimeGauge.apply((TimeGauge) this);
        }
        else if (this instanceof Gauge) {
            return visitGauge.apply((Gauge) this);
        }
        else if (this instanceof Counter) {
            return visitCounter.apply((Counter) this);
        }
        else if (this instanceof Timer) {
            return visitTimer.apply((Timer) this);
        }
        else if (this instanceof DistributionSummary) {
            return visitSummary.apply((DistributionSummary) this);
        }
        else if (this instanceof LongTaskTimer) {
            return visitLongTaskTimer.apply((LongTaskTimer) this);
        }
        else if (this instanceof FunctionCounter) {
            return visitFunctionCounter.apply((FunctionCounter) this);
        }
        else if (this instanceof FunctionTimer) {
            return visitFunctionTimer.apply((FunctionTimer) this);
        }
        else {
            return visitMeter.apply(this);
        }
    }

 //...
}

public class XyzMeterRegistry extends StepMeterRegistry {
 //...
    @Override
    protected void publish() {
        for (List<Meter> batch : MeterPartition.partition(this, config.batchSize())) {
            try {
                // @formatter:off
                httpClient.post(config.uri())
                        .withBasicAuthentication(config.userName(), config.password())
                        .withJsonContent(
                                batch.stream().flatMap(m -> m.match(
                                        this::writeGauge,
                                        this::writeCounter,
                                        this::writeTimer,
                                        this::writeSummary,
                                        this::writeLongTaskTimer,
                                        this::writeTimeGauge,
                                        this::writeFunctionCounter,
                                        this::writeFunctionTimer,
                                        this::writeCustomMetric)
                                ).collect(Collectors.joining(",", "[", "]"))
                        )
                        // @formatter:on
                        .send()
                        .onSuccess(response -> logger.debug("successfully sent {} metrics to kairos.", batch.size()))
                        .onError(response -> logger.error("failed to send metrics to kairos: {}", response.body()));
            }
            catch (Throwable t) {
                logger.warn("failed to send metrics to kairos", t);
            }
        }
    }

    Stream<String> writeGauge(Gauge gauge) {
        double value = gauge.value();
        if (Double.isFinite(value)) {
            return Stream.of(writeMetric(gauge.getId(), config().clock().wallTime(), value));
        }
        return Stream.empty();
    }

    Stream<String> writeCounter(Counter counter) {
        return Stream.of(writeMetric(counter.getId(), config().clock().wallTime(), counter.count()));
    }

  Stream<String> writeTimer(Timer timer) {
        long wallTime = config().clock().wallTime();
        return Stream.of(writeMetric(idWithSuffix(timer.getId(), "count"), wallTime, timer.count()),
                writeMetric(idWithSuffix(timer.getId(), "max"), wallTime, timer.max(getBaseTimeUnit())),
                writeMetric(idWithSuffix(timer.getId(), "avg"), wallTime, timer.mean(getBaseTimeUnit())),
                writeMetric(idWithSuffix(timer.getId(), "sum"), wallTime, timer.totalTime(getBaseTimeUnit())));
    }

    Stream<String> writeFunctionCounter(FunctionCounter counter) {
        double count = counter.count();
        if (Double.isFinite(count)) {
            return Stream.of(writeMetric(counter.getId(), config().clock().wallTime(), count));
        }
        return Stream.empty();
    }
  //...etc.,
}

How the above match( ) is called from MeterRegistryComponent's publish method?
//How does here m.match(//....) is taking parameters from MeterRegistryComponent's publish method?**
//And what is the role of flatMap here?**

I just want to write custom meterregistry in which need to publish metrics using publish method


问:
Category on chartjs graph shows undefined
```<code>// Get a reference to the form element
const form = document.querySelector('form');

// Get a reference to the canvas element
const canvas = document.querySelector('#myChart');

const chart2Canvas = document.querySelector('#chart2');

console.log(chart2Canvas)

// Declare variables that will hold the input values
let homeworkHours = 0;
let extraStudyHours = 0;
let hobbiesHours = 0;
let sportsHours = 0;
let socialActivityHours = 0;
let breaksHours = 0;

// Add an event listener to the form to listen for submit events
form.addEventListener('submit', (event) => {
  // Prevent the default form submission behavior
  event.preventDefault();

  // Get the values of the form inputs
const homeworkInput = document.querySelector('#homework');
const extraStudyInput = document.querySelector('#extra-study');
const hobbiesInput = document.querySelector('#hobbies');
const sportsInput = document.querySelector('#sports');
const socialActivityInput = document.querySelector('#social-activity');
const breaksInput = document.querySelector('#breaks');

  // Convert the input values to numbers
homeworkHours = parseInt(homeworkInput.value, 10);
extraStudyHours = parseInt(extraStudyInput.value, 10);
hobbiesHours = parseInt(hobbiesInput.value, 10);
sportsHours = parseInt(sportsInput.value, 10);
socialActivityHours = parseInt(socialActivityInput.value, 10);
breaksHours = parseInt(breaksInput.value, 10);

  // Calculate the total number of hours spent on activities
  const totalHours = homeworkHours + extraStudyHours + hobbiesHours + sportsHours + socialActivityHours + breaksHours;

  // Create a chart using the Chart.js library
  const chart = new Chart(canvas, {
    type: 'pie',
    data: {
      labels: ['Homework', 'Extra Study', 'Hobbies', 'Sports', 'Social Activities', 'Breaks'],
      datasets: [{
        data: [homeworkHours, extraStudyHours, hobbiesHours, sportsHours, socialActivityHours, breaksHours],
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#00FF00', '#0000FF', '#FFFF00'],
        hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#00FF00', '#0000FF', '#FFFF00'],
      }],
    },
    options: {
      responsive: false,
      maintainAspectRatio: false,
      aspectRatio: 1.5/1, // width:height
      title: {
        display: true,
      text: `Total Hours: ${totalHours}`,

      },

    },

  });

  const chart2 = new Chart(chart2Canvas, {
    type: 'bar',
    data: {
      labels: ['Homework', 'Extra Study', 'Hobbies', 'Sports', 'Social Activities', 'Breaks'],
      datasets: [{
        data: [homeworkHours, extraStudyHours, hobbiesHours, sportsHours, socialActivityHours, breaksHours],
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#E7E9ED', '#F9CB9C']
      }]
    },
    options: {
      responsive: false,
      maintainAspectRatio: false,
      aspectRatio: 1.5/1,
      title: {
        display: true,
        text: 'Hours Spent on Activities'
      },
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });

The Homework category for the bar chart keeps showing an undefined category even though it is defined. Not sure what the problem is, however, is it something to do with the scope of the variables? I've ran my code through console.log and there does not seem to be any referencing mistakes.

My HTML code is here in case there is a problem with it.

<canvas id="myChart" width="400" height="400"></canvas>
        <canvas id="chart2" width="400" height="400"></canvas>

        <script src="dashboard.js"></script>

        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
</code>```

I've tried running the canvas id through console.log on JS to see if there is a referencing mistake. I've tried to think of other reasons as to why it may not work, such as trying to access the elements before the DOM has finished loading, or is it something to do with the global and local variables in my program?

Body:
// Get a reference to the form element
const form = document.querySelector('form');

// Get a reference to the canvas element
const canvas = document.querySelector('#myChart');

const chart2Canvas = document.querySelector('#chart2');

console.log(chart2Canvas)

// Declare variables that will hold the input values
let homeworkHours = 0;
let extraStudyHours = 0;
let hobbiesHours = 0;
let sportsHours = 0;
let socialActivityHours = 0;
let breaksHours = 0;

// Add an event listener to the form to listen for submit events
form.addEventListener('submit', (event) => {
  // Prevent the default form submission behavior
  event.preventDefault();

  // Get the values of the form inputs
const homeworkInput = document.querySelector('#homework');
const extraStudyInput = document.querySelector('#extra-study');
const hobbiesInput = document.querySelector('#hobbies');
const sportsInput = document.querySelector('#sports');
const socialActivityInput = document.querySelector('#social-activity');
const breaksInput = document.querySelector('#breaks');

  // Convert the input values to numbers
homeworkHours = parseInt(homeworkInput.value, 10);
extraStudyHours = parseInt(extraStudyInput.value, 10);
hobbiesHours = parseInt(hobbiesInput.value, 10);
sportsHours = parseInt(sportsInput.value, 10);
socialActivityHours = parseInt(socialActivityInput.value, 10);
breaksHours = parseInt(breaksInput.value, 10);

  // Calculate the total number of hours spent on activities
  const totalHours = homeworkHours + extraStudyHours + hobbiesHours + sportsHours + socialActivityHours + breaksHours;

  // Create a chart using the Chart.js library
  const chart = new Chart(canvas, {
    type: 'pie',
    data: {
      labels: ['Homework', 'Extra Study', 'Hobbies', 'Sports', 'Social Activities', 'Breaks'],
      datasets: [{
        data: [homeworkHours, extraStudyHours, hobbiesHours, sportsHours, socialActivityHours, breaksHours],
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#00FF00', '#0000FF', '#FFFF00'],
        hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#00FF00', '#0000FF', '#FFFF00'],
      }],
    },
    options: {
      responsive: false,
      maintainAspectRatio: false,
      aspectRatio: 1.5/1, // width:height
      title: {
        display: true,
      text: `Total Hours: ${totalHours}`,

      },

    },

  });

  const chart2 = new Chart(chart2Canvas, {
    type: 'bar',
    data: {
      labels: ['Homework', 'Extra Study', 'Hobbies', 'Sports', 'Social Activities', 'Breaks'],
      datasets: [{
        data: [homeworkHours, extraStudyHours, hobbiesHours, sportsHours, socialActivityHours, breaksHours],
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#E7E9ED', '#F9CB9C']
      }]
    },
    options: {
      responsive: false,
      maintainAspectRatio: false,
      aspectRatio: 1.5/1,
      title: {
        display: true,
        text: 'Hours Spent on Activities'
      },
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });

The Homework category for the bar chart keeps showing an undefined category even though it is defined. Not sure what the problem is, however, is it something to do with the scope of the variables? I've ran my code through console.log and there does not seem to be any referencing mistakes.

My HTML code is here in case there is a problem with it.

<canvas id="myChart" width="400" height="400"></canvas>
        <canvas id="chart2" width="400" height="400"></canvas>

I've tried running the canvas id through console.log on JS to see if there is a referencing mistake. I've tried to think of other reasons as to why it may not work, such as trying to access the elements before the DOM has finished loading, or is it something to do with the global and local variables in my program?


Title: Pandas - Sum of variant number of products

Body:
I have two dataframes:

First one contains the information about number of daily arrivals of people in reference to some particular day of interest e.g. '-2' column header refers to number of people arriving on a day that is 2 days prior to my day of interest etc. These arrivals are split between two groups ('Rest of US' and 'International') in terms of a multiindex. Each row of a dataframe showcases different expected number of arrivals based on the number of tickets owned. To sum up, a single value of that dataframe showcases the number of people arriving on a certain day, given particular group of interest and the number of ticket holdings we consider.

import pandas as pd
import numpy as np

arrivals_US=np.array(
   [[0.00000000e+00, 1.32853314e+03, 7.92624282e+03, 2.36446211e+04,
     4.70225402e+04, 7.01360136e+04, 8.36885523e+04, 8.32165654e+04,
     7.09262060e+04, 5.28946471e+04, 3.50642212e+04, 2.09198795e+04,
     1.13464885e+04, 5.64124825e+03, 2.58896895e+03, 1.10330043e+03,
     4.38831214e+02, 1.63633610e+02, 5.74273229e+01, 1.90344814e+01,
     5.97698863e+00, 1.78298388e+00],
    [0.00000000e+00, 5.95406456e+03, 2.65918120e+04, 5.93816593e+04,
     8.84026873e+04, 9.87051626e+04, 8.81666331e+04, 6.56277324e+04,
     4.18720044e+04, 2.33758901e+04, 1.16000548e+04, 5.18077143e+03,
     2.10346912e+03, 7.82869343e+02, 2.68955436e+02, 8.57998806e+01,
     2.55464064e+01, 7.13089804e+00, 1.87339647e+00, 4.64827256e-01,
     1.09262813e-01, 2.43992667e-02]])
arrivals_Int = np.array(
   [[1.80595142e+02, 1.01558052e+03, 2.85556902e+03, 5.35278380e+03,
     7.52537259e+03, 8.46381767e+03, 7.93274228e+03, 6.37284860e+03,
     4.47973074e+03, 2.79909538e+03, 1.57407707e+03, 8.04714088e+02,
     3.77110526e+02, 1.63129911e+02, 6.55260304e+01, 2.45657991e+01,
     8.63414246e+00, 2.85613404e+00, 8.92307156e-01, 2.64100407e-01,
     7.42587051e-02, 1.98854935e-02],
    [3.33606865e+03, 1.20883137e+04, 2.19011273e+04, 2.64530626e+04,
     2.39633048e+04, 1.73663061e+04, 1.04878615e+04, 5.42899758e+03,
     2.45901062e+03, 9.90030648e+02, 3.58739652e+02, 1.18172777e+02,
     3.56834584e+01, 9.94613456e+00, 2.57428744e+00, 6.21865585e-01,
     1.40833925e-01, 3.00185083e-02, 6.04292696e-03, 1.15245636e-03,
     2.08797472e-04, 3.60277122e-05]])
arrivals = [arrivals_US, arrivals_Int]
days=list(range(-5,17))
tickets=[1,2]
arrivals_df = pd.concat([pd.DataFrame(dict(zip(days,arrival_type.T)), index=tickets) for arrival_type in arrivals], axis=1, keys=["Rest of US", "International"])

Second one has similar structure as the first one but instead of the number of arrivals, it represents a distribution of number of days stayed given the group type and number of tickets owned e.g. on average 24% of people who are being part of group 'Rest of US' and having a single ticket will stay for 3 days etc.

stays_dist_US=np.array(
   [[4.43244820e-03, 5.39982734e-02, 2.42003472e-01, 3.98996272e-01,
     2.42003472e-01, 5.39982734e-02, 4.43244820e-03, 1.33848338e-04,
     1.48692072e-06, 6.07670514e-09, 9.13595666e-12, 5.05295484e-15,
     1.02811648e-18, 7.69563998e-23, 2.11910601e-27, 2.14667422e-32,
     7.99991029e-38, 1.09675497e-43, 5.53145805e-50, 1.02630195e-56,
     7.00513005e-64, 1.75898756e-71],
    [1.33830425e-04, 4.43185500e-03, 5.39910468e-02, 2.41971084e-01,
     3.98942874e-01, 2.41971084e-01, 5.39910468e-02, 4.43185500e-03,
     1.33830425e-04, 1.48672173e-06, 6.07589189e-09, 9.13473400e-12,
     5.05227860e-15, 1.02797889e-18, 7.69461007e-23, 2.11882241e-27,
     2.14638693e-32, 7.99883965e-38, 1.09660819e-43, 5.53071778e-50,
     1.02616460e-56, 7.00419255e-64]])
stays_dist_Int = np.array(
   [[5.05227106e-15, 9.13472036e-12, 6.07588282e-09, 1.48671951e-06,
     1.33830225e-04, 4.43184839e-03, 5.39909662e-02, 2.41970723e-01,
     3.98942278e-01, 2.41970723e-01, 5.39909662e-02, 4.43184839e-03,
     1.33830225e-04, 1.48671951e-06, 6.07588282e-09, 9.13472036e-12,
     5.05227106e-15, 1.02797735e-18, 7.69459859e-23, 2.11881924e-27,
     2.14638372e-32, 7.99882771e-38],
    [1.02797735e-18, 5.05227106e-15, 9.13472036e-12, 6.07588282e-09,
     1.48671951e-06, 1.33830225e-04, 4.43184839e-03, 5.39909662e-02,
     2.41970723e-01, 3.98942278e-01, 2.41970723e-01, 5.39909662e-02,
     4.43184839e-03, 1.33830225e-04, 1.48671951e-06, 6.07588282e-09,
     9.13472036e-12, 5.05227106e-15, 1.02797735e-18, 7.69459859e-23,
     2.11881924e-27, 2.14638372e-32]])
stays_dist = [stays_dist_US, stays_dist_Int]
len_of_stay = list(range(1,23))
tickets=[1,2]
stays_df = pd.concat([pd.DataFrame(dict(zip(len_of_stay,stays_dist_type.T)), index=tickets) for stays_dist_type in stays_dist], axis=1, keys=["Rest of US", "International"])

I would like to create a 3rd dataframe which would depict number of departures on each day (having exactly the same structure of columns and index as the 1st one), by doing some sort of 'variant sum of products' (not sure how to name it) for example:

number of 'Rest of US' people leaving at day '-4', given that they have k number of tickets should be represented as a product of number of these type of people arriving at day '-5' (value from the 1st dataframe) and percentage of these type of people leaving after single day (value from my length of stay distribution - 2nd dataframe),

number of 'Rest of US' people leaving at day '-3', given that they have k number of tickets should be represented as sum of two products:

Number of people arriving at day '-5' and percentage of people staying for 2 days,

Number of people arriving at day '-4' and percentage of people staying for 1 day,

number of 'Rest of US' people leaving at day '-2', given that they have k number of tickets should be represented as sum of three products:

Number of people arriving at day '-5' and percentage of people staying for 3 days,

Number of people arriving at day '-4' and percentage of people staying for 2 days,

Number of people arriving at day '-3' and percentage of people staying for 1 day.

and so it goes all the way till all days are considered for given group and then the same is repeated for the next one.

So far I've done it in Excel by manually expanding the formula with each new day I was considering:

example of the calculation in excel for day '-2'

I tried to replicate it in Python with some for loops but it's messy and probably not efficient.

Is there any clever way one can do this with some pandas/numpy methods?

Thank you for any help and suggestions!


问:
What event ID gets stored in a google calendar event when the event is created with the google calendar API?
I am writing a VBA script in Outlook that will add a calendar event to a google calendar each time the event is added to the Outlook calendar.  I have this functionality working and this is the code I am using (in the code below, xxxxxxxxxxxxxxx is my google email which is associated with my google calendar and the variable accessToken is a valid token I generate in the OAuth 2.0 Playground while developing):

```<code>    ' build the json string which will be sent to the google API

        Dim d As New Scripting.Dictionary

        d.Add "kind", "calendar#event"
        d.Add "summary", "Event Title/Summary"
        d.Add "location", Item.Location
        d.Add "id", LCase(Item.EntryID)
        d.Add "description", Item.Subject

        Dim d2(4) As New Scripting.Dictionary

        d2(0).Add "dateTime", Item.Start
        d.Add "start", d2(0)
        d2(1).Add "dateTime", Item.End
        d.Add "end", d2(1)

        Dim Json As String
        Json = JsonConverter.ConvertToJson(d, Whitespace:=" ")
    MsgBox (LCase(Item.EntryID))
    ' send the json string via POST
    Set httpCall = CreateObject("MSXML2.ServerXMLHTTP")
    Dim sURL As String
    sURL = "https://www.googleapis.com/calendar/v3/calendars/xxxxxxxxxxxxxxx/events?sendNotifications=false&fields=etag%2ChtmlLink%2Cid&pp=1&access_token=" + accessToken
    httpCall.Open "POST", sURL, False
    httpCall.setRequestHeader "Content-Type", "application/json;charset=UTF-8"
    httpCall.Send Json
    Dim sReturn As String
    sReturn = httpCall.responseText
    MsgBox (sReturn)
</code>```

After I add an event to my Outlook calendar, the above code runs.  The result of the first MsgBox looks like this:

This is the value of the event ID in Outlook.  I pass this along to google in the hopes that google creates the event in my google calendar with the same event ID.

When google returns, this is the response text that is sent back:

As you can see, google returned a structure with 3 fields, etag, id, and htmlLink.  The value in id is the same value I sent so I assumed that would be the event ID on the google calendar.

My next step was to delete the event in Outlook and have the event deleted in the google calendar by using the API.  This is the code that I use to issue the delete request:

```<code>Set httpCall = CreateObject("MSXML2.ServerXMLHTTP")
Dim sURL As String
MsgBox (LCase(Item.EntryID))
sURL = "https://www.googleapis.com/calendar/v3/calendars/xxxxxxxxxxxxxxx/events/" + LCase(Item.EntryID) + "?access_token=" + access token
httpCall.Open "DELETE", sURL, False
httpCall.setRequestHeader "Content-Type", "application/json;charset=UTF-8"
httpCall.Send
Dim sReturn As String
sReturn = httpCall.responseText
MsgBox (sReturn)
</code>```

The first message box displays the event ID in Outlook which matches the first image I provided.
However, when this code runs, this is what google returns:

Am I correct in concluding that the google event ID is not the event ID I sent?  Is the google event ID the eid variable that was returned as part of the htmllink?  And if that is the case, then I assume I would need to store that eid value in the Outlook event somewhere and pass that to google on a delete request.

Any clarification would be greatly appreciated.

Body:
I am writing a VBA script in Outlook that will add a calendar event to a google calendar each time the event is added to the Outlook calendar.  I have this functionality working and this is the code I am using (in the code below, xxxxxxxxxxxxxxx is my google email which is associated with my google calendar and the variable accessToken is a valid token I generate in the OAuth 2.0 Playground while developing):

    ' build the json string which will be sent to the google API

        Dim d As New Scripting.Dictionary

        d.Add "kind", "calendar#event"
        d.Add "summary", "Event Title/Summary"
        d.Add "location", Item.Location
        d.Add "id", LCase(Item.EntryID)
        d.Add "description", Item.Subject

        Dim d2(4) As New Scripting.Dictionary

        d2(0).Add "dateTime", Item.Start
        d.Add "start", d2(0)
        d2(1).Add "dateTime", Item.End
        d.Add "end", d2(1)

        Dim Json As String
        Json = JsonConverter.ConvertToJson(d, Whitespace:=" ")
    MsgBox (LCase(Item.EntryID))
    ' send the json string via POST
    Set httpCall = CreateObject("MSXML2.ServerXMLHTTP")
    Dim sURL As String
    sURL = "https://www.googleapis.com/calendar/v3/calendars/xxxxxxxxxxxxxxx/events?sendNotifications=false&fields=etag%2ChtmlLink%2Cid&pp=1&access_token=" + accessToken
    httpCall.Open "POST", sURL, False
    httpCall.setRequestHeader "Content-Type", "application/json;charset=UTF-8"
    httpCall.Send Json
    Dim sReturn As String
    sReturn = httpCall.responseText
    MsgBox (sReturn)

After I add an event to my Outlook calendar, the above code runs.  The result of the first MsgBox looks like this:

This is the value of the event ID in Outlook.  I pass this along to google in the hopes that google creates the event in my google calendar with the same event ID.

When google returns, this is the response text that is sent back:

As you can see, google returned a structure with 3 fields, etag, id, and htmlLink.  The value in id is the same value I sent so I assumed that would be the event ID on the google calendar.

My next step was to delete the event in Outlook and have the event deleted in the google calendar by using the API.  This is the code that I use to issue the delete request:

Set httpCall = CreateObject("MSXML2.ServerXMLHTTP")
Dim sURL As String
MsgBox (LCase(Item.EntryID))
sURL = "https://www.googleapis.com/calendar/v3/calendars/xxxxxxxxxxxxxxx/events/" + LCase(Item.EntryID) + "?access_token=" + access token
httpCall.Open "DELETE", sURL, False
httpCall.setRequestHeader "Content-Type", "application/json;charset=UTF-8"
httpCall.Send
Dim sReturn As String
sReturn = httpCall.responseText
MsgBox (sReturn)

The first message box displays the event ID in Outlook which matches the first image I provided.
However, when this code runs, this is what google returns:

Am I correct in concluding that the google event ID is not the event ID I sent?  Is the google event ID the eid variable that was returned as part of the htmllink?  And if that is the case, then I assume I would need to store that eid value in the Outlook event somewhere and pass that to google on a delete request.

Any clarification would be greatly appreciated.


问:
TinyMCE text editor's toolbar location in Angular project
I am using TinyMCE text editor in Angular project. I have followed all steps in TinyMCE Angular integration quick start guide and used TinyMCE Self-hosted method. So far following these steps went nice and fairly simple text editor pops up in my project as it should. My project uses the version "@tinymce/tinymce-angular": "^7.0.0"

I am having a problem with toolbar location. I need to set it below the text editor, not above as it is by default. The guide tells me to include toolbar_location: 'bottom' in the options. But if I do that I get an error.

HTML template:

```<code><editor [init]="DescriptionTextEditor"></editor>
</code>```

Typescript file:

```<code>export class TextEditorComponent implements OnInit {

public DescriptionTextEditor= {
    base_url: '/tinymce',
    suffix: '.min',
    menubar: false,
    statusbar: false,
    plugins:
        'link lists'
    ,
    toolbar:
        ' bold italic underline | bullist | link | removeformat',
    toolbar_location: 'bottom'
};

constructor() { }

ngOnInit(): void {
}
</code>```

}

If I save the file as above, I get an error:

Compiled with problems:

ERROR

src/app/.../description.component.html:9:46 - error TS2322: Type '{
base_url: string; suffix: string; menubar: boolean; statusbar:
boolean; plugins: string; toolbar: string; toolbar_location: string;
}' is not assignable to type 'RawEditorOptions'.   Types of property
'toolbar_location' are incompatible.
Type 'string' is not assignable to type 'ToolbarLocation | undefined'.

9     [init]="DescriptionTextEditor">
~~~~

src/app/.../description.component.ts:7:15
7  templateUrl: './description.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component DescriptionComponent.

If I remove toolbar_location: 'bottom' remove the options in TS file then text editor works fine. Only adding this feature breaks it.

Body:
I am using TinyMCE text editor in Angular project. I have followed all steps in TinyMCE Angular integration quick start guide and used TinyMCE Self-hosted method. So far following these steps went nice and fairly simple text editor pops up in my project as it should. My project uses the version "@tinymce/tinymce-angular": "^7.0.0"

I am having a problem with toolbar location. I need to set it below the text editor, not above as it is by default. The guide tells me to include toolbar_location: 'bottom' in the options. But if I do that I get an error.

HTML template:

<editor [init]="DescriptionTextEditor"></editor>

Typescript file:

export class TextEditorComponent implements OnInit {

public DescriptionTextEditor= {
    base_url: '/tinymce',
    suffix: '.min',
    menubar: false,
    statusbar: false,
    plugins:
        'link lists'
    ,
    toolbar:
        ' bold italic underline | bullist | link | removeformat',
    toolbar_location: 'bottom'
};

constructor() { }

ngOnInit(): void {
}

}

If I save the file as above, I get an error:

Compiled with problems:

ERROR

src/app/.../description.component.html:9:46 - error TS2322: Type '{
base_url: string; suffix: string; menubar: boolean; statusbar:
boolean; plugins: string; toolbar: string; toolbar_location: string;
}' is not assignable to type 'RawEditorOptions'.   Types of property
'toolbar_location' are incompatible.
Type 'string' is not assignable to type 'ToolbarLocation | undefined'.

9     [init]="DescriptionTextEditor">
~~~~

src/app/.../description.component.ts:7:15
7  templateUrl: './description.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component DescriptionComponent.

If I remove toolbar_location: 'bottom' remove the options in TS file then text editor works fine. Only adding this feature breaks it.


问:
snmpv2 packing the pdu with agent information
I'm following this tutorial on how to create a simple application.  https://net-snmp.sourceforge.io/wiki/index.php/TUT:Simple_Application and I'm setting up to snmpv2c and using my own ip address and oid number. But I keep getting a timeout at the function call snmp_synch_response.

However, if I pack the snmp_pdu struct with version, community and community_len I'm able to create the pdu and not get a timeout. Which is leading to the confusion, because I thought the snmp_session is the struct that holds the info of the agent we want to talk to and the pdu holds the oids? or am I missing something else?

In addition, if for some reason I need to pack the snmp_pdu with the agent information how will it affect when using snmpv3. Since snmp_pdu struct does not have the fields securityAuthProto, securityName etc. Which is what I eventually would like to implement as well.

I followed the online tutorial https://net-snmp.sourceforge.io/wiki/index.php/TUT:Simple_Application

when I pack the pdu with the version, community and community_len I do not get a timeout, but the snmp_session is the struct that should contain the agent info?


问:
Can I automatically clean deprecated @types/ packages?
I'm upgrading an old typescript project. Many years ago, most packages had corresponding @types packages. Nowadays, typings are usually included in the main package, therefore typing packages got obsolete.

A typical example is yup. Many years ago it needed @types/yup, but now it's deprecated.

I have 30+ typing packages in my project, and because I don't want to manually clean them, I'm asking:

What if I just leave them in pakages.json? I guess there is a big chance they would mislead typescript and IDE, right?

Is there a command or script to list or clean deprecated packages?


问:
What is WPARAM and LPARAM in C++ winapi
So I've been trying to undersatand why do I put WPARAM and LPARAM when I'm making a C++ window application and I couldn't understand why.
Can someone help me with that?</p>

Title: What is WPARAM and LPARAM in C++ winapi


问:
Renpy/Python - VariableValue screen lag/not showing correct values
I'm trying to make a bar which value is a VariableValue. Depending on the value CUSTOM_ITEM_PRICE, a list of DISPLAY_PERCENTAGES changes.

To explain what I'm trying to do, I'm making a shop system where instead of just buying an item, you put an upfront investment and the shop will return an item of varying quality to you. The higher the investment you put, the more likely you'll get a better quality item. There are 6 qualities: Cheap, Simple, Fine, Elegant, Ornate, Masterwork.

Here is the code for calculating the DISPLAY_PERCENTAGES:

```<code>    QUALITY_TO_INDEX = {
                "Cheap": 0,
                "Simple": 1,
                "Fine": 2,
                "Elegant": 3,
                "Ornate": 4,
                "Masterwork": 5
    }

    APPAREL_MIN_MAX = {
                "Cheap": (28, 2000),
                "Simple": (322, 3500),
                "Fine": (600, 5000),
                "Elegant": (1200, 6000),
                "Ornate": (2500, 7000),
                "Masterwork": (4000, 6000)
    }

    CUSTOM_ITEM_PRICE = 350 #ill change this into an input number based on hbar in game frontend later

    DISPLAY_PERCENTAGES = [0, 0, 0, 0, 0, 0]

    def count_custom_chance(price):
        AVAIL_QUALITIES = []
        POSSIBLE_PERCENTAGES = []
        CUSTOM_ORDER_WEIGHTS = []

        for key, value in APPAREL_MIN_MAX.items():
            min_value = value[0]
            if price > min_value:
                AVAIL_QUALITIES.append(key)

        min_value = [tup[0] for tup in APPAREL_MIN_MAX.values()]
        max_value = [tup[1] for tup in APPAREL_MIN_MAX.values()]

        idx = QUALITY_TO_INDEX[AVAIL_QUALITIES[0]]

        count = 0
        while count < len(AVAIL_QUALITIES):
            qual_min_weight = price - min_value[idx]
            qual_max_weight = price - max_value[idx]
            idx += 1
            count += 1

            qweight = min([qual_min_weight, abs(qual_max_weight)])
            CUSTOM_ORDER_WEIGHTS.append(qweight)

        for weight in CUSTOM_ORDER_WEIGHTS:
            percent = (weight/(sum(CUSTOM_ORDER_WEIGHTS)))*100
            POSSIBLE_PERCENTAGES.append(percent)

        count = 0
        for quality in AVAIL_QUALITIES:
            DISPLAY_PERCENTAGES[QUALITY_TO_INDEX.get(quality)] = round(POSSIBLE_PERCENTAGES[count], 2)
            count += 1
</code>```

DISPLAY_PERCENTAGES will return as a list of six items corresponding to the quality of the item. If you put 350 gold, the DISPLAY_PERCENTAGES should be [92, 8, 0, 0, 0, 0]. I want to display that list on a screen.

This is the code for the displaying the screen

```<code>screen tailor_hud():

    tag second

    add "gui/main_hud/tailor_hud.jpg" xoffset glist_posX yoffset glist_posY+62

    bar:
        xoffset glist_posX+32
        yoffset glist_posY+560
        base_bar "gui/bar/shop_price.png"
        thumb "gui/bar/mini_thumb.png"
        thumb_offset 7
        xysize (380, 30)
        left_gutter 10
        right_gutter 22
        #Important line below, I suppose
        value VariableValue("CUSTOM_ITEM_PRICE", 4650, offset=350, action=Function(count_custom_chance, CUSTOM_ITEM_PRICE), step=50, force_step=True)

    text "[CUSTOM_ITEM_PRICE]" xoffset glist_posX+178 yoffset glist_posY+528 size 21 font "font/maian.ttf" color gold_color

    vbox:
        for txt in DISPLAY_PERCENTAGES:
            textbutton str(txt):
                action NullAction()
        xalign 0.3
        yalign 0.5
</code>```

The problem is when first showing the screen, all values of DISPLAY_PERCENTAGES is its default:

After moving the bar value, DISPLAY_PERCENTAGES updates itself but the values are wrong:

The correct values for putting 450 gold should be [76.73, 23.27, 0, 0, 0, 0].

And finally the most mind-boggling from me is when I play around with the bar, the values get really messed up. Here is the values after going back to the default 350 gold:

Many thanks beforehand for any advice. I'm still on my second month in learning code and renpy, so hopefully my code isn't just a jumbly mess.

Body:
I'm trying to make a bar which value is a VariableValue. Depending on the value CUSTOM_ITEM_PRICE, a list of DISPLAY_PERCENTAGES changes.

To explain what I'm trying to do, I'm making a shop system where instead of just buying an item, you put an upfront investment and the shop will return an item of varying quality to you. The higher the investment you put, the more likely you'll get a better quality item. There are 6 qualities: Cheap, Simple, Fine, Elegant, Ornate, Masterwork.

Here is the code for calculating the DISPLAY_PERCENTAGES:

    QUALITY_TO_INDEX = {
                "Cheap": 0,
                "Simple": 1,
                "Fine": 2,
                "Elegant": 3,
                "Ornate": 4,
                "Masterwork": 5
    }

    APPAREL_MIN_MAX = {
                "Cheap": (28, 2000),
                "Simple": (322, 3500),
                "Fine": (600, 5000),
                "Elegant": (1200, 6000),
                "Ornate": (2500, 7000),
                "Masterwork": (4000, 6000)
    }

    CUSTOM_ITEM_PRICE = 350 #ill change this into an input number based on hbar in game frontend later

    DISPLAY_PERCENTAGES = [0, 0, 0, 0, 0, 0]

    def count_custom_chance(price):
        AVAIL_QUALITIES = []
        POSSIBLE_PERCENTAGES = []
        CUSTOM_ORDER_WEIGHTS = []

        for key, value in APPAREL_MIN_MAX.items():
            min_value = value[0]
            if price > min_value:
                AVAIL_QUALITIES.append(key)

        min_value = [tup[0] for tup in APPAREL_MIN_MAX.values()]
        max_value = [tup[1] for tup in APPAREL_MIN_MAX.values()]

        idx = QUALITY_TO_INDEX[AVAIL_QUALITIES[0]]

        count = 0
        while count < len(AVAIL_QUALITIES):
            qual_min_weight = price - min_value[idx]
            qual_max_weight = price - max_value[idx]
            idx += 1
            count += 1

            qweight = min([qual_min_weight, abs(qual_max_weight)])
            CUSTOM_ORDER_WEIGHTS.append(qweight)

        for weight in CUSTOM_ORDER_WEIGHTS:
            percent = (weight/(sum(CUSTOM_ORDER_WEIGHTS)))*100
            POSSIBLE_PERCENTAGES.append(percent)

        count = 0
        for quality in AVAIL_QUALITIES:
            DISPLAY_PERCENTAGES[QUALITY_TO_INDEX.get(quality)] = round(POSSIBLE_PERCENTAGES[count], 2)
            count += 1

DISPLAY_PERCENTAGES will return as a list of six items corresponding to the quality of the item. If you put 350 gold, the DISPLAY_PERCENTAGES should be [92, 8, 0, 0, 0, 0]. I want to display that list on a screen.

This is the code for the displaying the screen

screen tailor_hud():

    tag second

    add "gui/main_hud/tailor_hud.jpg" xoffset glist_posX yoffset glist_posY+62

    bar:
        xoffset glist_posX+32
        yoffset glist_posY+560
        base_bar "gui/bar/shop_price.png"
        thumb "gui/bar/mini_thumb.png"
        thumb_offset 7
        xysize (380, 30)
        left_gutter 10
        right_gutter 22
        #Important line below, I suppose
        value VariableValue("CUSTOM_ITEM_PRICE", 4650, offset=350, action=Function(count_custom_chance, CUSTOM_ITEM_PRICE), step=50, force_step=True)

    text "[CUSTOM_ITEM_PRICE]" xoffset glist_posX+178 yoffset glist_posY+528 size 21 font "font/maian.ttf" color gold_color

    vbox:
        for txt in DISPLAY_PERCENTAGES:
            textbutton str(txt):
                action NullAction()
        xalign 0.3
        yalign 0.5

The problem is when first showing the screen, all values of DISPLAY_PERCENTAGES is its default:

After moving the bar value, DISPLAY_PERCENTAGES updates itself but the values are wrong:

The correct values for putting 450 gold should be [76.73, 23.27, 0, 0, 0, 0].

And finally the most mind-boggling from me is when I play around with the bar, the values get really messed up. Here is the values after going back to the default 350 gold:

Many thanks beforehand for any advice. I'm still on my second month in learning code and renpy, so hopefully my code isn't just a jumbly mess.


问:
git submodule error - picking up latest commit instead of a specific commit
I have a repository with a submodule which includes 3 files:

As you see here, the branch specified in .gitmodules is 'develop' and the ref specified in vsts-cicd.yml is 'develop'.

The git command I use to update the commit is:

git submodule update --remote --merge

My understanding was that when we do a deployment, it will get the changes from 'public' submodule up to the commit specified in 'public' (in this case: 1ff703eda1b357efdecbffb2422b6fcc99a48557). But what I noticed is that, if I have a new commit in 'develop' in 'public', it will pick that latest commit from 'develop' even though 'public' submodule has an old commit '1ff703eda1b357efdecbffb2422b6fcc99a48557'. Is that how submodule works? Please let me know what I am missing?

Note: When I run

```<code>cd submodule; git log
</code>```

I see the latest commit listed as 1ff703eda1b357efdecbffb2422b6fcc99a48557 (which is correct)

Body:
I have a repository with a submodule which includes 3 files:

As you see here, the branch specified in .gitmodules is 'develop' and the ref specified in vsts-cicd.yml is 'develop'.

The git command I use to update the commit is:

git submodule update --remote --merge

My understanding was that when we do a deployment, it will get the changes from 'public' submodule up to the commit specified in 'public' (in this case: 1ff703eda1b357efdecbffb2422b6fcc99a48557). But what I noticed is that, if I have a new commit in 'develop' in 'public', it will pick that latest commit from 'develop' even though 'public' submodule has an old commit '1ff703eda1b357efdecbffb2422b6fcc99a48557'. Is that how submodule works? Please let me know what I am missing?

Note: When I run

cd submodule; git log

I see the latest commit listed as 1ff703eda1b357efdecbffb2422b6fcc99a48557 (which is correct)


问:
How to check a collision between a circle and a polygon, but just are just draws, in pygame?
I have these two class and I want to check if there's any collision between them:
I wanted to make a simple collision between those two, even if it is with both of them with square hitboxes. The bullets are also in a list bullets = [].</p>
```<code>class Enemies(object):
    def __init__(self, rank):
        self.rank = rank
        if self.rank == 1:
            self.points = [(-20, 20), (20, 20), (5, 30), (-5, 30)]
        elif self.rank == 2:
            self.points = [(-25, 20), (25, 20), (10, 30), (-10, 30)]
        elif self.rank == 3:
            self.points = [(-35, 20), (35, 20), (20, 30), (-20, 30)]
        elif self.rank == 4:
            self.points = [(-45, 20), (45, 20), (30, 30), (-30, 30)]
        elif self.rank == 5:
            self.points = [(-55, 20), (55, 20), (40, 30), (-40, 30)]
        self.x = 1100
        self.y = 300
        self.speed = 1
        self.spawn_delay = 2000

    def update(self):
        self.x -= self.speed

    def draw(self, screen, color):
        points = [(x + self.x, y + self.y) for x, y in self.points]
        pygame.draw.polygon(screen, color, points, 0)

class Bullet(object):
    def __init__(self, player, time):
        self.x = player.x + 25 * math.cos(player.angle)
        self.y = player.y - 25 * math.sin(player.angle)
        self.angle = player.angle
        self.initial_velocity = 50
        self.time = time
        self.g = 9.8
        self.active = True
        self.last_shoot_time = 0
        self.radius = 5

    def update(self):
        self.x += + self.initial_velocity * self.time * math.cos(self.angle)
        self.y -= + self.initial_velocity * self.time * math.sin(self.angle) - 0.5 * self.g * self.time ** 2
        screen_width = 1000
        screen_height = 380
        if self.x < 0 or self.x > screen_width or self.y < 0 or self.y > screen_height:
            self.active = False

    def draw(self, screen, color):
        pygame.draw.circle(screen, color, (int(self.x), int(self.y)), self.radius)```
</code>```

Body:
I have these two class and I want to check if there's any collision between them:
I wanted to make a simple collision between those two, even if it is with both of them with square hitboxes. The bullets are also in a list bullets = [].

class Enemies(object):
    def __init__(self, rank):
        self.rank = rank
        if self.rank == 1:
            self.points = [(-20, 20), (20, 20), (5, 30), (-5, 30)]
        elif self.rank == 2:
            self.points = [(-25, 20), (25, 20), (10, 30), (-10, 30)]
        elif self.rank == 3:
            self.points = [(-35, 20), (35, 20), (20, 30), (-20, 30)]
        elif self.rank == 4:
            self.points = [(-45, 20), (45, 20), (30, 30), (-30, 30)]
        elif self.rank == 5:
            self.points = [(-55, 20), (55, 20), (40, 30), (-40, 30)]
        self.x = 1100
        self.y = 300
        self.speed = 1
        self.spawn_delay = 2000

    def update(self):
        self.x -= self.speed

    def draw(self, screen, color):
        points = [(x + self.x, y + self.y) for x, y in self.points]
        pygame.draw.polygon(screen, color, points, 0)

class Bullet(object):
    def __init__(self, player, time):
        self.x = player.x + 25 * math.cos(player.angle)
        self.y = player.y - 25 * math.sin(player.angle)
        self.angle = player.angle
        self.initial_velocity = 50
        self.time = time
        self.g = 9.8
        self.active = True
        self.last_shoot_time = 0
        self.radius = 5

    def update(self):
        self.x += + self.initial_velocity * self.time * math.cos(self.angle)
        self.y -= + self.initial_velocity * self.time * math.sin(self.angle) - 0.5 * self.g * self.time ** 2
        screen_width = 1000
        screen_height = 380
        if self.x < 0 or self.x > screen_width or self.y < 0 or self.y > screen_height:
            self.active = False

    def draw(self, screen, color):
        pygame.draw.circle(screen, color, (int(self.x), int(self.y)), self.radius)```


问:
How to use namespace properly in PHP?
I have this file root/core/Router.php

```<code><?php
    namespace Core;

    class Router {

        protected $url;
        protected $controller;

        private function parseURL() {
            // threat the $this->url; for example ["r", "product"]
        }

        private function request() {
            $this->controller = Controller::get($this->url[1]);
        }

        public function __construct() {
            $this->parseURL();
            $this->request();
        }

    }
?>
</code>```

then file root/core/Controller.php

```<code><?php
    namespace Core;

    class Controller {

        public static function model($name, $params = []) {
            $model = "\\Model\\$name";
            return new $model($params);
        }

        public static function view($name, $params = []) {
            require_once APP_DIR . "view/" . $name . ".php";
        }

        public static function get($name, $params = []) {
            require_once APP_DIR . "controller/" . $name . ".php";
            $name = "\\Controller\\$name";
            return new $name($params);
        }

    }
?>
</code>```

then root/controler/Product.php

```<code><?php
    namespace Controller;
    use Core\Controller;
    use Model\Product;

    class Product {

        public function get() {

            $ret['state'] = 510;
            $productModel = new Product;
            $products = $productModel->getAll();

            if(isset($products)) {
                $ret['products'] = $products;
                $ret['state'] = 200;
            }

            return $ret;

        }

    }
?>

</code>```

then file root/model/Product.php

```<code><?php
    namespace Model;

    class Product {

        public function add($values) {
            return Database::insert("product", $values);
        }
    }
?>
</code>```

and root/core/Model.php

```<code><?php
    namespace Core;

    class Model {

        protected $table = null;

        public function getAll() {
          // some code to collect data
        }

    }

?>
</code>```

What i want to achive is that every Controller in root/controller/*.php able to load any Model in root/model/*.php but class inside root/model/*.php must able to access (inheritance/extends) the Model class inside root/core/Model.php i firstly asked on chatGPT for some AI Generated answer, that the reason why i get this far.

Then i get this error, when the AI keep giving the same answer.

```<code>Fatal error: Cannot declare class Controller\Product because the name is already in use in C:\xampp\htdocs\app\shop\controller\Product.php on line 6
</code>```

I actually realize that the simple way probably with naming the class so ther no conflict between it but i became aware how to properly using the namespace if its such features in php. Those files loaded without any autoloader, so i just require_once each file in root/init.php file.

I read few documentations but hard to implement in multiple files and directorys.

I Apreciate any feedback, thanks

Title: How to use namespace properly in PHP?

Body:
I have this file root/core/Router.php

<?php
    namespace Core;

    class Router {

        protected $url;
        protected $controller;

        private function parseURL() {
            // threat the $this->url; for example ["r", "product"]
        }

        private function request() {
            $this->controller = Controller::get($this->url[1]);
        }

        public function __construct() {
            $this->parseURL();
            $this->request();
        }

    }
?>

then file root/core/Controller.php

<?php
    namespace Core;

    class Controller {

        public static function model($name, $params = []) {
            $model = "\\Model\\$name";
            return new $model($params);
        }

        public static function view($name, $params = []) {
            require_once APP_DIR . "view/" . $name . ".php";
        }

        public static function get($name, $params = []) {
            require_once APP_DIR . "controller/" . $name . ".php";
            $name = "\\Controller\\$name";
            return new $name($params);
        }

    }
?>

then root/controler/Product.php

<?php
    namespace Controller;
    use Core\Controller;
    use Model\Product;

    class Product {

        public function get() {

            $ret['state'] = 510;
            $productModel = new Product;
            $products = $productModel->getAll();

            if(isset($products)) {
                $ret['products'] = $products;
                $ret['state'] = 200;
            }

            return $ret;

        }

    }
?>

then file root/model/Product.php

<?php
    namespace Model;

    class Product {

        public function add($values) {
            return Database::insert("product", $values);
        }
    }
?>

and root/core/Model.php

<?php
    namespace Core;

    class Model {

        protected $table = null;

        public function getAll() {
          // some code to collect data
        }

    }

?>

What i want to achive is that every Controller in root/controller/*.php able to load any Model in root/model/*.php but class inside root/model/*.php must able to access (inheritance/extends) the Model class inside root/core/Model.php i firstly asked on chatGPT for some AI Generated answer, that the reason why i get this far.

Then i get this error, when the AI keep giving the same answer.

Fatal error: Cannot declare class Controller\Product because the name is already in use in C:\xampp\htdocs\app\shop\controller\Product.php on line 6

I actually realize that the simple way probably with naming the class so ther no conflict between it but i became aware how to properly using the namespace if its such features in php. Those files loaded without any autoloader, so i just require_once each file in root/init.php file.

I read few documentations but hard to implement in multiple files and directorys.

I Apreciate any feedback, thanks


问:
Is there a way to trick an InstallShield it's running on a different processor?
I have an M1 Mac running Parallels 18.  It is running the ARM version of Windows 11, and everything is running great.

I have an application that I am trying to install that checks to make sure what processor it's running on.  During the installshield process it pops up and say "This application needs a Pentium III or better". Yes this program has been around for a while, it is has been updated in the last couple months, but they have clearly never updated the installer. I believe the installer is also 32bit not 64.

So I am confident the application will actually run once it's installed.  But I can't get past the installer.

Can I trick the installer into thinking it's running on a x86/x64?

I have changed the values by running 'set' for each of the values

```<code>PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 158 Stepping 13, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=9e0d
</code>```

I have also updated the values in

```<code>HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment
</code>```

But no matter what I do when I run

```<code>ECHO %PROCESSOR_ARCHITECTURE%
it returns: ARM64
</code>```

If I run the the same command in the 32bit cmd prompt it does return
x86

Not sure what else I'm missing.

Body:
I have an M1 Mac running Parallels 18.  It is running the ARM version of Windows 11, and everything is running great.

I have an application that I am trying to install that checks to make sure what processor it's running on.  During the installshield process it pops up and say "This application needs a Pentium III or better". Yes this program has been around for a while, it is has been updated in the last couple months, but they have clearly never updated the installer. I believe the installer is also 32bit not 64.

So I am confident the application will actually run once it's installed.  But I can't get past the installer.

Can I trick the installer into thinking it's running on a x86/x64?

I have changed the values by running 'set' for each of the values

PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 158 Stepping 13, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=9e0d

I have also updated the values in

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment

But no matter what I do when I run

ECHO %PROCESSOR_ARCHITECTURE%
it returns: ARM64

If I run the the same command in the 32bit cmd prompt it does return
x86

Not sure what else I'm missing.


问:
While running a batch file ,for some reason I couldn't see any response from my Process.Start()
The batch file is not giving any response.

The below is the code

```<code>SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
    password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\users\Beulah_joe\Mybuilds\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "Joe";
psi.Password = password;
Process.Start(psi);
</code>```

I am expecting some output or error message

Body:
The batch file is not giving any response.

The below is the code

SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
    password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\users\Beulah_joe\Mybuilds\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "Joe";
psi.Password = password;
Process.Start(psi);

I am expecting some output or error message


问:
AVFoundation is playing a video (hevc/h265 with .mp4 as extension), but without image
My code works for other video types (like h264 with .mp4), but it was the customer's camera that recorded this video with h265/hevc in .mp4 format.

My code for playing the video:

```<code>let playerController: AVPlayerViewController = AVPlayerViewController()
  playerController.player = AVPlayer(url: url)
     DispatchQueue.main.async {
       self.present(playerController, animated: true, completion: {
         playerController.player?.play()
  })
}
</code>```

Screenshot with in-app with the screen open and view all black

Does anyone know how can I execute this video with these specifications?

Or could to explain to me why can't I execute this video?

Tests:

iOS 16.1 (didn't work)

iOS 15.0 (didn't work)

iOS 14.0 (didn't work)

iOS 13.0 (didn't work)

Note 1: -> Others formats did work, only the h265 with .mp4 that don't work

Note 2: -> Downloading the client video from my server, the video was played normally

Note 3: -> I can execute this video with VLC, but I want to execute it with AVFoundation which is the pattern of the project.

Body:
My code works for other video types (like h264 with .mp4), but it was the customer's camera that recorded this video with h265/hevc in .mp4 format.

My code for playing the video:

let playerController: AVPlayerViewController = AVPlayerViewController()
  playerController.player = AVPlayer(url: url)
     DispatchQueue.main.async {
       self.present(playerController, animated: true, completion: {
         playerController.player?.play()
  })
}

Screenshot with in-app with the screen open and view all black

Does anyone know how can I execute this video with these specifications?

Or could to explain to me why can't I execute this video?

Tests:

iOS 16.1 (didn't work)

iOS 15.0 (didn't work)

iOS 14.0 (didn't work)

iOS 13.0 (didn't work)

Note 1: -> Others formats did work, only the h265 with .mp4 that don't work

Note 2: -> Downloading the client video from my server, the video was played normally

Note 3: -> I can execute this video with VLC, but I want to execute it with AVFoundation which is the pattern of the project.


问:
I am getting an error while running test on headspin environment:

org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: 'GET /window/current/size' cannot be proxied to UiAutomator2 server because the instrumentation process is not running (probably crashed). Check the server log and/or the logcat output for more details

I am not using appium server provided by headspin


问:
Why media queries on smartphones with high resolution?
I started to learn HTML/PHP and now I am at the chapter responsive webdesign.

With the media query the output can be adapted to desktop and mobile devices. For example with "media="screen and (max-width: 640px)". So far, so good. The resolutions of smartphones are often higher or just as high as those of desktop monitors. As you can see here

https://screensiz.es/phone ... eg. Apple iPhone 7 Plus - 1080 x 1920

My question now is, why a media query for example with 640px, if the resolution of smartphones is anyway as high as that of desktop monitors?