问:
Trying to "land" cylinders onto terrain in three.js
I want these cylinders to rest just on top of the terrain. I've tried using raycasters of different orientation similar to  but the raytracer distance and point measurements don't seem correct - when I apply them, the cylinders fall through the bottom of the grid.  It's as if they are looking at the non-transformed, non-displacement map mesh.  How to get the intersects to line up perfectly with the actual displacement map mesh

https://github.com/ledlogic/terrain

```<code>/* from https://www.youtube.com/watch?v=2AQLMZwQpDo */

import './style.css'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import * as dat from 'dat.gui'

const loader = new THREE.TextureLoader()
const heightImg = loader.load('/height.png')
const textureImg = loader.load('/texture.jpg')
const alphaImg = loader.load('/alpha-02.png')

// Debug
const gui = new dat.GUI()

// Canvas
const canvas = document.querySelector('canvas.webgl')

// Scene
const scene = new THREE.Scene()

// Objects
const width = 3;
const height = 3;
const widthSegments = 1500;
const heightSegments = 1500;
const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments)

// Materials
const material = new THREE.MeshStandardMaterial({
    color: 'gray',
    map: textureImg,
    displacementMap: heightImg,
    displacementScale: 0.5,
    depthTest: true
})

// Mesh
const planeMesh = new THREE.Mesh(geometry, material);
scene.add(planeMesh);
planeMesh.rotation.x = -Math.PI/2

// Lights
const pointLight = new THREE.PointLight('#dcdcff', 2)
pointLight.position.x = 3
pointLight.position.y = 3
pointLight.position.z = 3
scene.add(pointLight)

// Sizes
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () => {
    // Update sizes
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight

    // Update camera
    camera.aspect = sizes.width / sizes.height
    camera.updateProjectionMatrix()

    // Update renderer
    renderer.setSize(sizes.width, sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

// Base camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
camera.position.y = 1
scene.add(camera)

// Renderer
const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})
renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

// Cylinder
var gridMin = -1.4
var gridMax = 1.4
var gridDelta = 0.2
var vector = new THREE.Vector3(0, 0, -1)
for (var x=gridMin;x<gridMax;x+=gridDelta) {
    for (var z=gridMin;z<gridMax;z+=gridDelta) {
        const cylinderGeometry = new THREE.CylinderGeometry( 0.01, 0.01, 0.05, 20 );
        const cylinderMaterial = new THREE.MeshStandardMaterial( {color: 'gray'} );
        const cylinderMesh = new THREE.Mesh( cylinderGeometry, cylinderMaterial );
        cylinderMesh.position.x = x
        cylinderMesh.position.y = 0.5
        cylinderMesh.position.z = z

        // fix y positions.
        /*
        var raycaster = new THREE.Raycaster();
        raycaster.set(cylinderMesh.position, vector);
        var velocity = new THREE.Vector3();
        var intersects = raycaster.intersectObject(planeMesh);
        if (intersects.length) {
            var d = intersects[0].distance;
            //cylinderMesh.translateY(-d);
        }
        */
        scene.add(cylinderMesh);
    }
}

var mwdelta = 0;
document.addEventListener( 'mousewheel', (event) => {
    mwdelta +=event.deltaY;
});

// Clock
let cameraRadius = 3
const clock = new THREE.Clock()
const tick = () => {
    const elapsedTime = clock.getElapsedTime()

    var t = 0.125 * elapsedTime
    var zoomRadius = cameraRadius + mwdelta / 500
    camera.position.x = zoomRadius * Math.sin(t)
    camera.position.z = zoomRadius * Math.cos(t)
    camera.rotation.y = t

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}
tick()
</code>```

Body:
I want these cylinders to rest just on top of the terrain. I've tried using raycasters of different orientation similar to  but the raytracer distance and point measurements don't seem correct - when I apply them, the cylinders fall through the bottom of the grid.  It's as if they are looking at the non-transformed, non-displacement map mesh.  How to get the intersects to line up perfectly with the actual displacement map mesh

https://github.com/ledlogic/terrain

/* from https://www.youtube.com/watch?v=2AQLMZwQpDo */

import './style.css'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import * as dat from 'dat.gui'

const loader = new THREE.TextureLoader()
const heightImg = loader.load('/height.png')
const textureImg = loader.load('/texture.jpg')
const alphaImg = loader.load('/alpha-02.png')

// Debug
const gui = new dat.GUI()

// Canvas
const canvas = document.querySelector('canvas.webgl')

// Scene
const scene = new THREE.Scene()

// Objects
const width = 3;
const height = 3;
const widthSegments = 1500;
const heightSegments = 1500;
const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments)

// Materials
const material = new THREE.MeshStandardMaterial({
    color: 'gray',
    map: textureImg,
    displacementMap: heightImg,
    displacementScale: 0.5,
    depthTest: true
})

// Mesh
const planeMesh = new THREE.Mesh(geometry, material);
scene.add(planeMesh);
planeMesh.rotation.x = -Math.PI/2

// Lights
const pointLight = new THREE.PointLight('#dcdcff', 2)
pointLight.position.x = 3
pointLight.position.y = 3
pointLight.position.z = 3
scene.add(pointLight)

// Sizes
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () => {
    // Update sizes
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight

    // Update camera
    camera.aspect = sizes.width / sizes.height
    camera.updateProjectionMatrix()

    // Update renderer
    renderer.setSize(sizes.width, sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

// Base camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
camera.position.y = 1
scene.add(camera)

// Renderer
const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})
renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

// Cylinder
var gridMin = -1.4
var gridMax = 1.4
var gridDelta = 0.2
var vector = new THREE.Vector3(0, 0, -1)
for (var x=gridMin;x<gridMax;x+=gridDelta) {
    for (var z=gridMin;z<gridMax;z+=gridDelta) {
        const cylinderGeometry = new THREE.CylinderGeometry( 0.01, 0.01, 0.05, 20 );
        const cylinderMaterial = new THREE.MeshStandardMaterial( {color: 'gray'} );
        const cylinderMesh = new THREE.Mesh( cylinderGeometry, cylinderMaterial );
        cylinderMesh.position.x = x
        cylinderMesh.position.y = 0.5
        cylinderMesh.position.z = z

        // fix y positions.
        /*
        var raycaster = new THREE.Raycaster();
        raycaster.set(cylinderMesh.position, vector);
        var velocity = new THREE.Vector3();
        var intersects = raycaster.intersectObject(planeMesh);
        if (intersects.length) {
            var d = intersects[0].distance;
            //cylinderMesh.translateY(-d);
        }
        */
        scene.add(cylinderMesh);
    }
}

var mwdelta = 0;
document.addEventListener( 'mousewheel', (event) => {
    mwdelta +=event.deltaY;
});

// Clock
let cameraRadius = 3
const clock = new THREE.Clock()
const tick = () => {
    const elapsedTime = clock.getElapsedTime()

    var t = 0.125 * elapsedTime
    var zoomRadius = cameraRadius + mwdelta / 500
    camera.position.x = zoomRadius * Math.sin(t)
    camera.position.z = zoomRadius * Math.cos(t)
    camera.rotation.y = t

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}
tick()


来源: stackexchange

问:
Trying to send an image from the local file system to a Discord channel
I am stuck working out why images are not going through on the message.send() call.

I am able to get the text, but nothing else. Channel permissions are correct, as currently the bot has Administrator permissions.

This is the code to get my bot send an image on !random command:

  client.on('messageCreate', msg => {
      if (msg.content === '!random') {
        // Find the channel with the specified name
        const channel = client.channels.cache.find(ch => ch.name === 'mod-default-log');

        console.log('Channel:', channel); // log the channel object

        try {
          // Declare the attachment as a collection
          const attachment = new Collection([{
            file: fs.readFileSync('./images/1b509fe1549a1c08861ebc00dd39b68ec29c2758.png'),
            name: 'image.png'
          }]);

          console.log('Attachment:', attachment); // log the attachment object

          // Send the message with the attachment
          channel.send('This is a message with a file attachment from a URL!', attachment);
        } catch (error) {
          console.error(error.message); // log error message
        }
      }
  });
```
<p>This is my <code>Intents</code> defining:</p>
<pre class="lang-js prettyprint-override"><code>const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,

]});
</code>```

I have enabled debugging to try and work out why am I unable to get my bot send images.

When trying to pass the collection the debugging returns this is the result:

```<code>Attachment: Collection(1) [Map] { undefined => undefined }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am stuck working out why images are not going through on the message.send() call.

I am able to get the text, but nothing else. Channel permissions are correct, as currently the bot has Administrator permissions.

This is the code to get my bot send an image on !random command:

  client.on('messageCreate', msg => {
      if (msg.content === '!random') {
        // Find the channel with the specified name
        const channel = client.channels.cache.find(ch => ch.name === 'mod-default-log');

        console.log('Channel:', channel); // log the channel object

        try {
          // Declare the attachment as a collection
          const attachment = new Collection([{
            file: fs.readFileSync('./images/1b509fe1549a1c08861ebc00dd39b68ec29c2758.png'),
            name: 'image.png'
          }]);

          console.log('Attachment:', attachment); // log the attachment object

          // Send the message with the attachment
          channel.send('This is a message with a file attachment from a URL!', attachment);
        } catch (error) {
          console.error(error.message); // log error message
        }
      }
  });

This is my Intents defining:

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,

]});

I have enabled debugging to try and work out why am I unable to get my bot send images.

When trying to pass the collection the debugging returns this is the result:

Attachment: Collection(1) [Map] { undefined => undefined }


问:
Error running selenium in android using termux
I am using SELENIUM IN MY ANDROID PHONE USING TERMUX

HERE IS MY CODE

`
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option('androidPackage', 'com.android.chrome')

driver=webdriver.Chrome('./chromedriver', options=options)

driver.get('https://google.com')
driver.quit()`

And THIS IS THE ERROR I M GETTING

```<code>/storage/emulated/0/Download/Instagram-Bot-Scrape-DM-Users-main/Instagram-Bot-Scrape-DM-Users-main/hh.py:5: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome('./chromedriver', options=options)
Traceback (most recent call last):
  File "/storage/emulated/0/Download/Instagram-Bot-Scrape-DM-Users-main/Instagram-Bot-Scrape-DM-Users-main/hh.py", line 5, in <module>
    driver = webdriver.Chrome('./chromedriver', options=options)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    super().__init__(
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/selenium/webdriver/chromium/webdriver.py", line 103, in __init__

</code>```

Body:
I am using SELENIUM IN MY ANDROID PHONE USING TERMUX

HERE IS MY CODE

`
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option('androidPackage', 'com.android.chrome')

driver=webdriver.Chrome('./chromedriver', options=options)

driver.get('https://google.com')
driver.quit()`

And THIS IS THE ERROR I M GETTING

/storage/emulated/0/Download/Instagram-Bot-Scrape-DM-Users-main/Instagram-Bot-Scrape-DM-Users-main/hh.py:5: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome('./chromedriver', options=options)
Traceback (most recent call last):
  File "/storage/emulated/0/Download/Instagram-Bot-Scrape-DM-Users-main/Instagram-Bot-Scrape-DM-Users-main/hh.py", line 5, in <module>
    driver = webdriver.Chrome('./chromedriver', options=options)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    super().__init__(
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/selenium/webdriver/chromium/webdriver.py", line 103, in __init__


问:
Request to Tensorflow Serving Server got timeout error for models using grpc python API

Synopsis

10 models for computer vision was deployed to tensorflow serving server (TSS) running on Ubuntu 22.04.
TSS installed as system service on the dedicated server having MSI RTX3060 12 Gb on board. System configuration and TSS service file below.

Problem

Request send via the tensorflow-serving grpc api randomly got status code DEADLINE_EXCEEDED or UNAVAILABLE sometimes on the first request but more often after some number (1...4) of successful requests or after some period of inactivity ( 1 hour or more ).
No OMM or service dump happened. GPU memory occupation is near 6 Gb. Service logs seems to have no problem indication, no warnings also (debug level 3).
Some experiments and results in detail see below.

System

[OS] Ubuntu 22.04.1 LTS

[CPU] 11th Gen Intel(R) Core(TM) i5-11400F @ 2.60GHz

[GPU] MSI GeForce RTX 3060 12G

[RAM] 16Gb

[SSD] NVME 1Tb

[Tensorflow] Version 2.9.1

[CUDA] Version 11.7

[CUDNN] Version 8.6.0.163-1+cuda11.8

[TensorRT] Not used while building tensorflow-serving

TSS service file

```<code>[Unit]
Description=Tensorflow Serving Service
After=network-online.target

[Service]
User=root

Environment="PATH=/usr/local/bin:/usr/bin:/usr/sbin:/usr/local/sbin:/usr/local/cuda/bin:/usr/bin/model_servers"
Environment="LD_LIBRARY_PATH=/usr/local/cuda-11.7/lib64"
Environment="CUDA_VISIBLE_DEVICES=0"
Environment="TF_FORCE_GPU_ALLOW_GROWTH=true"
ExecStart=/usr/bin/model_servers/tensorflow_model_server --port=8504 --model_config_file=/mnt/data/models/export/frman.conf

[Install]
WantedBy=multi-user.target
</code>```

Hints

Tensorflow serving service intializes after network on host is available․

Service configured to allocate gpu memory when it needed (environment variable - TF_FORCE_GPU_ALLOW_GROWTH=true).

Hypotesis - actions

The problem is lost packets on the network

Requests to TSS was monitored with wireshark from client side and with GNOME system monitor in server side. NO problem detected.

Timeout value for single request on client side of tensorflow_serving.apis.prediction_service_pb2_grpc.PredictionServiceStub object increased .

stub.Predict(request, timeout * len(images))

The grpс channel is being checked for readiness before data transmission to begin

Interceptors for grpc requests added. Procedure repeat request with exponential backoff but nevertheless it returned status code DEADLINE_EXCEEDED or UNAVAILABLE randomly.

```<code>        options_grpc = [
            ('grpc.max_send_message_length', 100 * 1024 * 1024),
            ('grpc.max_receive_message_length', 100 * 1024 * 1024),
            ('grpc.default_compression_algorithm', grpc.Compression.Gzip),
            ('grpc.grpc.default_compression_level', CompressionLevel.high)
        ]
        interceptors = (
            RetryOnRpcErrorClientInterceptor(
                max_attempts=5,
                sleeping_policy=ExponentialBackoff(init_backoff_ms=1000, max_backoff_ms=32000, multiplier=2),
                status_for_retry=(grpc.StatusCode.DEADLINE_EXCEEDED, grpc.StatusCode.UNKNOWN, grpc.StatusCode.UNAVAILABLE),
            ),
        )
        channel = grpc.insecure_channel(f"{host}:{port}", options=options_grpc)
        grpc.channel_ready_future(channel).result(timeout=5)
        channel = grpc.intercept_channel(channel, *interceptors)
</code>```

The problem is in the models themselves
Was noticed that problems mostly arise with models with U2net architecture. U2net uses some custom operations and was assumed that the problem arises from the fact that at the first request time outed because these operations for loading ops are too long.
That was found on the TSS service log file. To resolve this we try:

Add a warm-up that kind of models at the service startup, so all custom network operations loaded into memory before inference.

Custom operations in U2Net was eliminated by converting the models to onnx format and then to tensorflow saved model format. So, after that there is no need for the TSS to load network custom ops at startup. Model warm up added also.

The problem with the lack of memory - There was noticed another alarming message in TSS service log:

```<code>tensorflow_model_server[62029]: 2022-12-20 14:10:13.900599: W external/org_tensorflow/tensorflow/tsl/framework/bfc_allocator.cc:360] Garbage collection: deallocate free memory regions (i.e., allocations) so that we can re-allocate a larger region to avoid OOM due to memory fragmentation. If you see this message frequently, you are running near the threshold of the available device memory and re-allocation may incur great performance overhead. You may try smaller batch sizes to observe the performance impact. Set TF_ENABLE_GPU_GARBAGE_COLLECTION=false if you'd like to disable this feature.
</code>```

It looks line not enough memory for inference on GPU. To solve this we try to limit image batch size to 1(one) image for TSS and to set environment variable - TF_FORCE_GPU_ALLOW_GROWTH=true.
Memory consumption not increased after that. But random timeout (DEADLINE_EXCEEDED) error not dissapied.

Conclusion - Issue NOT Resolved

Thus, the problem is still in place especially when TSS inference segmentaion models (like U2Net).
Not Root of the problem was found.
Difficult to reproduce error as of its random type.

What else should be worth to check or configure to resolve the issue?

Body:
Synopsis

10 models for computer vision was deployed to tensorflow serving server (TSS) running on Ubuntu 22.04.
TSS installed as system service on the dedicated server having MSI RTX3060 12 Gb on board. System configuration and TSS service file below.

Problem

Request send via the tensorflow-serving grpc api randomly got status code DEADLINE_EXCEEDED or UNAVAILABLE sometimes on the first request but more often after some number (1...4) of successful requests or after some period of inactivity ( 1 hour or more ).
No OMM or service dump happened. GPU memory occupation is near 6 Gb. Service logs seems to have no problem indication, no warnings also (debug level 3).
Some experiments and results in detail see below.

System

[OS] Ubuntu 22.04.1 LTS

[CPU] 11th Gen Intel(R) Core(TM) i5-11400F @ 2.60GHz

[GPU] MSI GeForce RTX 3060 12G

[RAM] 16Gb

[SSD] NVME 1Tb

[Tensorflow] Version 2.9.1

[CUDA] Version 11.7

[CUDNN] Version 8.6.0.163-1+cuda11.8

[TensorRT] Not used while building tensorflow-serving

TSS service file

[Unit]
Description=Tensorflow Serving Service
After=network-online.target

[Service]
User=root

Environment="PATH=/usr/local/bin:/usr/bin:/usr/sbin:/usr/local/sbin:/usr/local/cuda/bin:/usr/bin/model_servers"
Environment="LD_LIBRARY_PATH=/usr/local/cuda-11.7/lib64"
Environment="CUDA_VISIBLE_DEVICES=0"
Environment="TF_FORCE_GPU_ALLOW_GROWTH=true"
ExecStart=/usr/bin/model_servers/tensorflow_model_server --port=8504 --model_config_file=/mnt/data/models/export/frman.conf

[Install]
WantedBy=multi-user.target

Hints

Tensorflow serving service intializes after network on host is available․

Service configured to allocate gpu memory when it needed (environment variable - TF_FORCE_GPU_ALLOW_GROWTH=true).

Hypotesis - actions

The problem is lost packets on the network

Requests to TSS was monitored with wireshark from client side and with GNOME system monitor in server side. NO problem detected.

Timeout value for single request on client side of tensorflow_serving.apis.prediction_service_pb2_grpc.PredictionServiceStub object increased .

stub.Predict(request, timeout * len(images))

The grpс channel is being checked for readiness before data transmission to begin

Interceptors for grpc requests added. Procedure repeat request with exponential backoff but nevertheless it returned status code DEADLINE_EXCEEDED or UNAVAILABLE randomly.

        options_grpc = [
            ('grpc.max_send_message_length', 100 * 1024 * 1024),
            ('grpc.max_receive_message_length', 100 * 1024 * 1024),
            ('grpc.default_compression_algorithm', grpc.Compression.Gzip),
            ('grpc.grpc.default_compression_level', CompressionLevel.high)
        ]
        interceptors = (
            RetryOnRpcErrorClientInterceptor(
                max_attempts=5,
                sleeping_policy=ExponentialBackoff(init_backoff_ms=1000, max_backoff_ms=32000, multiplier=2),
                status_for_retry=(grpc.StatusCode.DEADLINE_EXCEEDED, grpc.StatusCode.UNKNOWN, grpc.StatusCode.UNAVAILABLE),
            ),
        )
        channel = grpc.insecure_channel(f"{host}:{port}", options=options_grpc)
        grpc.channel_ready_future(channel).result(timeout=5)
        channel = grpc.intercept_channel(channel, *interceptors)

The problem is in the models themselves
Was noticed that problems mostly arise with models with U2net architecture. U2net uses some custom operations and was assumed that the problem arises from the fact that at the first request time outed because these operations for loading ops are too long.
That was found on the TSS service log file. To resolve this we try:

Add a warm-up that kind of models at the service startup, so all custom network operations loaded into memory before inference.

Custom operations in U2Net was eliminated by converting the models to onnx format and then to tensorflow saved model format. So, after that there is no need for the TSS to load network custom ops at startup. Model warm up added also.

The problem with the lack of memory - There was noticed another alarming message in TSS service log:

tensorflow_model_server[62029]: 2022-12-20 14:10:13.900599: W external/org_tensorflow/tensorflow/tsl/framework/bfc_allocator.cc:360] Garbage collection: deallocate free memory regions (i.e., allocations) so that we can re-allocate a larger region to avoid OOM due to memory fragmentation. If you see this message frequently, you are running near the threshold of the available device memory and re-allocation may incur great performance overhead. You may try smaller batch sizes to observe the performance impact. Set TF_ENABLE_GPU_GARBAGE_COLLECTION=false if you'd like to disable this feature.

It looks line not enough memory for inference on GPU. To solve this we try to limit image batch size to 1(one) image for TSS and to set environment variable - TF_FORCE_GPU_ALLOW_GROWTH=true.
Memory consumption not increased after that. But random timeout (DEADLINE_EXCEEDED) error not dissapied.

Conclusion - Issue NOT Resolved

Thus, the problem is still in place especially when TSS inference segmentaion models (like U2Net).
Not Root of the problem was found.
Difficult to reproduce error as of its random type.

What else should be worth to check or configure to resolve the issue?


问:
Sparse implementation of SLSQP
I have a nonlinear optimization problem for ~300 variables and 20,000 constraints, where every gradient vector of the constraints has at most 5 nonzero entries. A very sparse system, which I have to solve millions of times (for random initial values). The SLSQP algorithm from the NLopt library works fine, but slowly. Is there an implementation of SLSQP, which can take advantage of the sparsity, and works faster?

I tried the Active Set Method to reduce the number of inequality constraints. That reduced the running time 30 fold. I'd like another 30 fold speedup, without rewritng the SLSQP algorithm myself.

Title: Sparse implementation of SLSQP


问:
JBPM - Unable to upload local business-application-kjar to business central
Below is my environment details:

1] Business Application( Default app created from https://start.jbpm.org/ with version - 7.59.0)
2] RHPAM (version 7.12 installed)

I am trying to upload the business-application/business-application-kjar in business central but getting below error.

Error: **There are no projects available to import. Check the URL, the credentials, and if there's a master branch in the repository. **

Reference link which I was following: https://docs.jbpm.org/7.73.0.Final/jbpm-docs/html_single/#_import_your_business_assets_project_into_business_central

I want to work with Creating a self-contained Red Hat Decision Manager Spring Boot JAR file


问:
.NET6 Selenium4, is there any form to use http POST, when using Navigation().GoToUrl() method?
When trying to bypass a bot detection system, I notice that if a make the initial HTTP request using a POST method instead the GET. I can effectively surpass the bot detector.

I was searching around for a solution but I only find a Python approach.

I tried to build manually the Selenium source code with the necessary changes in dotnet/src/webdriver/Remote/W3CWireProtocolCommandInfoRepository.cs

```<code>protected override void InitializeCommandDictionary()
{
    this.TryAddCommand(DriverCommand.Get, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/url"));
    this.TryAddCommand(DriverCommand.GetCurrentUrl, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/url"));
}
</code>```

But I couldn’t handle the building. So anyone have a solution for this?

Body:
When trying to bypass a bot detection system, I notice that if a make the initial HTTP request using a POST method instead the GET. I can effectively surpass the bot detector.

I was searching around for a solution but I only find a Python approach.

I tried to build manually the Selenium source code with the necessary changes in dotnet/src/webdriver/Remote/W3CWireProtocolCommandInfoRepository.cs

protected override void InitializeCommandDictionary()
{
    this.TryAddCommand(DriverCommand.Get, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/url"));
    this.TryAddCommand(DriverCommand.GetCurrentUrl, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/url"));
}

But I couldn’t handle the building. So anyone have a solution for this?


问:
pyusb Device configuration Errno 16
An error occurred when executing the following script using pyusb.

```<code>import usb.core
import usb.util
import sys

dev = usb.core.find(idVendor=0x1234, idProduct=0x1234)

if dev is None:
    raise ValueError('Device not found')

print(dev)

dev.set_configuration()
</code>```

The error content is as follows.

aise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 16] Resource busy

I was able to get and print the correct Device object, but I got a problem with the configuration() part of the last line.

how can i solve this problem

[Environment]

python3

pyusb

kali linux

libusb-1.0-0:arm64

Title: pyusb Device configuration Errno 16

Body:
An error occurred when executing the following script using pyusb.

import usb.core
import usb.util
import sys

dev = usb.core.find(idVendor=0x1234, idProduct=0x1234)

if dev is None:
    raise ValueError('Device not found')

print(dev)

dev.set_configuration()

The error content is as follows.

aise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 16] Resource busy

I was able to get and print the correct Device object, but I got a problem with the configuration() part of the last line.

how can i solve this problem

[Environment]

python3

pyusb

kali linux

libusb-1.0-0:arm64


问:
WeightWatcher use for validating Deep Neural Network (https://github.com/CalculatedContent/WeightWatcher)
I am using Distilbert model for text classification. In order to validate the model, I am using WeightWatcher (https://github.com/CalculatedContent/WeightWatcher) which tells us that which layers are overtrained or undertrained.

As per this information, I would like to do trainable = False for the layers which are overtrained or success trained and would like to train the layers which are undertrained.

How can I do trainable =False at key and value layers of distilbert model?

I am able to do trainable = False at encoder level. But unable to do it at key, value and query level layers.


问:
Add shadowDOM to React component
How to add shadowDOM to whole react component Instead of having just one line html code

```<code><span class="app-container">
  <p>Shadow DOM text with open mode <p>
</span>
</code>```

within script

```<code>const shadowEl = document.querySelector(".app-container");
const shadow = shadowEl.attachShadow({mode: 'open'});
</code>```
```<code> const para = document.createElement("p");
 para.innerHTML = document.querySelector(".app-container").innerHTML;
 shadow.appendChild(para);
</code>```

The above code works fine for just html. But I don't know how to implement shadowDOM to react component in website.

Title: Add shadowDOM to React component

Body:
How to add shadowDOM to whole react component Instead of having just one line html code

Shadow DOM text with open mode

within script

const shadowEl = document.querySelector(".app-container");
const shadow = shadowEl.attachShadow({mode: 'open'});

 const para = document.createElement("p");
 para.innerHTML = document.querySelector(".app-container").innerHTML;
 shadow.appendChild(para);

The above code works fine for just html. But I don't know how to implement shadowDOM to react component in website.


问:
Why is this MongoDB search returning empty array?
I'm trying to create an autocomplete form on a front end where the user types in letters for a person's name. I had this working about a year ago, but when I came back it was just returning empty. Here I created a search index on Atlas. The name of the index is default.

```<code>{
  "mappings": {
    "dynamic": false,
    "fields": {
      "searchName": [
        {
          "foldDiacritics": false,
          "maxGrams": 10,
          "minGrams": 2,
          "tokenization": "edgeGram",
          "type": "autocomplete"
        }
      ]
    }
  }
}
</code>```

The documents look like this

```<code>{
    "_id": "/players/a/abernbr01.shtml",
    "url": "/players/a/abernbr01.shtml",
    "name": "Brent Abernathy",
    "image": "https://www.baseball-reference.com/req/202108020/images/headshots/0/0de5346d_sabr.jpg",
    "teams": [{
        "name": "TBD",
        "years": [2001, 2002, 2003]
    }],
    "searchName": "brent abernathy"
}
</code>```

And this is the query running

```<code>[
  {
    $search: {
      index: 'default',
      autocomplete: {
        query: 'abern',
        path: 'searchName',
      }
    }
  }
]
</code>```

Body:
I'm trying to create an autocomplete form on a front end where the user types in letters for a person's name. I had this working about a year ago, but when I came back it was just returning empty. Here I created a search index on Atlas. The name of the index is default.

{
  "mappings": {
    "dynamic": false,
    "fields": {
      "searchName": [
        {
          "foldDiacritics": false,
          "maxGrams": 10,
          "minGrams": 2,
          "tokenization": "edgeGram",
          "type": "autocomplete"
        }
      ]
    }
  }
}

The documents look like this

{
    "_id": "/players/a/abernbr01.shtml",
    "url": "/players/a/abernbr01.shtml",
    "name": "Brent Abernathy",
    "image": "https://www.baseball-reference.com/req/202108020/images/headshots/0/0de5346d_sabr.jpg",
    "teams": [{
        "name": "TBD",
        "years": [2001, 2002, 2003]
    }],
    "searchName": "brent abernathy"
}

And this is the query running

[
  {
    $search: {
      index: 'default',
      autocomplete: {
        query: 'abern',
        path: 'searchName',
      }
    }
  }
]


问:
Django static are not getting load on AWS using Nginx
i have a website build on Django. everything is working fine on local machine but the static file are not getting load on production. Django project is running fine on Debug=False I did install

```<code>whitenoise==6.2.0

</code>```

the error

django settings

```<code> SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ["*"]

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_ORIGINS = [
    "http://54.234.143.251",
]
CSRF_TRUSTED_ORIGINS = [
    "http://54.234.143.251",
]

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # app

    "applipsync",
    "store",
    # packages
    "whitenoise.runserver_nostatic",
    "rest_framework",
    "django_q",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "crispy_forms",
]
CRISPY_TEMPLATE_PACK = "bootstrap4"

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware", #add whitenoise
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "core.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "core.wsgi.application"

# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

ACCOUNT_EMAIL_REQUIRED = True

# Make email verification mandatory to avoid junk email accounts
ACCOUNT_EMAIL_VERIFICATION = "mandatory"

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""

AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",
    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
]

LOGIN_REDIRECT_URL = "/"
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True

# settings.py example
Q_CLUSTER = {
    "name": "pdm",
    "workers": 1,
    "recycle": 500,
    "timeout": 60,
    "retry": 120,
    "compress": True,
    "save_limit": 250,
    "queue_limit": 500,
    "cpu_affinity": 1,
    "label": "Django Q",
    "daemonize_workers": False,
    "orm": "default",
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

# settings.py

STATIC_URL = "static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

# PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root

print("BASE_DIR ", BASE_DIR)
print("------------------------------------------")
print(STATIC_ROOT)

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), "templates").replace("\\", "/"),
)

</code>```

path in aws

Nginx configuration

```<code>server {
    listen 80;
    server_name 54.234.143.251;
    client_max_body_size 100M;
    sendfile on;
    # to avoid any error while fetching fevicon
    location = /favicon.ico { access_log off;
        log_not_found off;
    }

    location /static/ {
        autoindex on;
        alias /home/ubuntu/lipsync-website/app/staticfiles/;
    }

    location /media/ {
        autoindex on;
        alias /home/ubuntu/lipsync-website/app/media/;
    }
    location / {
        # communicate via socket file created by Gunicorn
        # proxy_pass http://unix:/home/ubuntu/lipsync-website/app/core.sock;
        proxy_pass  http://0.0.0.0:8000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}
</code>```

i did change the path of nginx but still the static files are not getting load on production.

Body:
i have a website build on Django. everything is working fine on local machine but the static file are not getting load on production. Django project is running fine on Debug=False I did install

whitenoise==6.2.0

the error

django settings

 SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ["*"]

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_ORIGINS = [
    "http://54.234.143.251",
]
CSRF_TRUSTED_ORIGINS = [
    "http://54.234.143.251",
]

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # app

    "applipsync",
    "store",
    # packages
    "whitenoise.runserver_nostatic",
    "rest_framework",
    "django_q",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "crispy_forms",
]
CRISPY_TEMPLATE_PACK = "bootstrap4"

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware", #add whitenoise
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "core.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "core.wsgi.application"

# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

ACCOUNT_EMAIL_REQUIRED = True

# Make email verification mandatory to avoid junk email accounts
ACCOUNT_EMAIL_VERIFICATION = "mandatory"

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""

AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",
    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
]

LOGIN_REDIRECT_URL = "/"
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True

# settings.py example
Q_CLUSTER = {
    "name": "pdm",
    "workers": 1,
    "recycle": 500,
    "timeout": 60,
    "retry": 120,
    "compress": True,
    "save_limit": 250,
    "queue_limit": 500,
    "cpu_affinity": 1,
    "label": "Django Q",
    "daemonize_workers": False,
    "orm": "default",
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

# settings.py

STATIC_URL = "static/"
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

# PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root

print("BASE_DIR ", BASE_DIR)
print("------------------------------------------")
print(STATIC_ROOT)

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), "templates").replace("\\", "/"),
)

path in aws

Nginx configuration

server {
    listen 80;
    server_name 54.234.143.251;
    client_max_body_size 100M;
    sendfile on;
    # to avoid any error while fetching fevicon
    location = /favicon.ico { access_log off;
        log_not_found off;
    }

    location /static/ {
        autoindex on;
        alias /home/ubuntu/lipsync-website/app/staticfiles/;
    }

    location /media/ {
        autoindex on;
        alias /home/ubuntu/lipsync-website/app/media/;
    }
    location / {
        # communicate via socket file created by Gunicorn
        # proxy_pass http://unix:/home/ubuntu/lipsync-website/app/core.sock;
        proxy_pass  http://0.0.0.0:8000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

i did change the path of nginx but still the static files are not getting load on production.


问:
What is the difference between Request Duration (istio_request_duration_milliseconds) reported by source proxy and destination proxy?
I was looking at metrics exported by istio. I am especially interested in the Request Duration (istio_request_duration_milliseconds) metric.

I want to know what is the value of Request Duration (istio_request_duration_milliseconds) reported by client istio proxy (reporter="source") and server istio proxy (reporter = "destination").

Also, what should I set the reporter value to (source or destination) when I want to know the latency of http requests?

For example, this is one the queries I can see in grafana dashboard provided by istio.

```<code>label_join((histogram_quantile(0.99, sum(rate(istio_request_duration_milliseconds_bucket{reporter="source"}[1m])) by (le, destination_workload, destination_workload_namespace)) / 1000) or histogram_quantile(0.99, sum(rate(istio_request_duration_seconds_bucket{reporter="source"}[1m])) by (le, destination_workload, destination_workload_namespace)), "destination_workload_var", ".", "destination_workload", "destination_workload_namespace")
</code>```

But this query doesn't work for me. When I change the reporter to destination in the above query, it works.

So, I'm really confused as to which one is correct. If I have to calculate latency, which one should I consider? reporter=source or reporter=destination? or both will have the same value for latency?

Body:
I was looking at metrics exported by istio. I am especially interested in the Request Duration (istio_request_duration_milliseconds) metric.

I want to know what is the value of Request Duration (istio_request_duration_milliseconds) reported by client istio proxy (reporter="source") and server istio proxy (reporter = "destination").

Also, what should I set the reporter value to (source or destination) when I want to know the latency of http requests?

For example, this is one the queries I can see in grafana dashboard provided by istio.

label_join((histogram_quantile(0.99, sum(rate(istio_request_duration_milliseconds_bucket{reporter="source"}[1m])) by (le, destination_workload, destination_workload_namespace)) / 1000) or histogram_quantile(0.99, sum(rate(istio_request_duration_seconds_bucket{reporter="source"}[1m])) by (le, destination_workload, destination_workload_namespace)), "destination_workload_var", ".", "destination_workload", "destination_workload_namespace")

But this query doesn't work for me. When I change the reporter to destination in the above query, it works.

So, I'm really confused as to which one is correct. If I have to calculate latency, which one should I consider? reporter=source or reporter=destination? or both will have the same value for latency?


问:
how does javascript know which button I'm pressing?
```<code>  function render(ourCart) {
    ourCart.forEach(function(item) {
      const renderCart = document.createElement('div');
      renderCart.innerText = item.name + ' $' + item.price;
      cart.appendChild(renderCart);
      const addButton = document.createElement('button');
      addButton.innerText = 'Add';
      renderCart.appendChild(addButton);
      renderCart.onclick = function() {
        total = total + (+item.price);
        console.log(item.name);
        console.log(item.price);
      }
    })
  }
</code>```

this function is supposed to render the name and price of a product and also an 'add' button that adds up the prices of all the products. After a lot of trying I decided to look up the solution which uses '.onclick = function () {}' inside the forEach loop as shown in the screenshot.

render output
this works perfectly fine. I can press the button next to 'apple' twice for example and console.log(total) gives me 3*2 = 6. But, my question is how does javascript know that I'm pressing the button next to apple and not egg? I'm not using any id here to give each button a specific function or anything. The forEach loop goes over all the objects in the array and goes over the .onclick = function() thing twice in this case (two objects in my example array). Does this store a temporary value in the onclick function or something? Any help is appreciated!

Body:
  function render(ourCart) {
    ourCart.forEach(function(item) {
      const renderCart = document.createElement('div');
      renderCart.innerText = item.name + ' $' + item.price;
      cart.appendChild(renderCart);
      const addButton = document.createElement('button');
      addButton.innerText = 'Add';
      renderCart.appendChild(addButton);
      renderCart.onclick = function() {
        total = total + (+item.price);
        console.log(item.name);
        console.log(item.price);
      }
    })
  }

this function is supposed to render the name and price of a product and also an 'add' button that adds up the prices of all the products. After a lot of trying I decided to look up the solution which uses '.onclick = function () {}' inside the forEach loop as shown in the screenshot.

render output
this works perfectly fine. I can press the button next to 'apple' twice for example and console.log(total) gives me 3*2 = 6. But, my question is how does javascript know that I'm pressing the button next to apple and not egg? I'm not using any id here to give each button a specific function or anything. The forEach loop goes over all the objects in the array and goes over the .onclick = function() thing twice in this case (two objects in my example array). Does this store a temporary value in the onclick function or something? Any help is appreciated!


问:
Assertion failure on isFast “getting fast-math flag on invalid op”, Trying to check if fast option is set for an instruction LLVM
Hi I am writing a transformation pass to check where on some conditional call instruction I would like to check If fast option is set for that call, instruction and disable it. For example on below call inst, I would like to disable the fast option.

```<code>  %call3 = call fast fastcc noundef <8 x float> @_ZL13_mm256_mul_psDv8_fS_(<8 x float> noundef %0, <8 x float> noundef %power.0)

</code>```

Below is my pass, Don’t mind If I miss something trivial, I’m at a very early stage in compiler dev.

Header file contents :

```<code>#include "llvm/IR/PassManager.h"

namespace llvm {

class RemoveFastFlagsToPreventFmaPass: public PassInfoMixin<RemoveFastFlagsToPreventFmaPass> {
public:
    PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
};
} // namespace llvm

</code>```
```<code>#include "llvm/Transforms/Scalar/RemoveFastFlagsToPreventFma.h"
#include "llvm/IR/Instructions.h"
#define Status(b) outs()<<(b?"Yes\n":"No\n")
using namespace llvm;
using namespace std;

bool fastflags_for_intrfma = false;

bool IsArithmeticIntrinsicCall(const Instruction &i){
    return 1;
}

PreservedAnalyses RemoveFastFlagsToPreventFmaPass::run(Module &M, ModuleAnalysisManager &AM){
    for(Function &F : M){
        for(BasicBlock &b : F){
            for(Instruction &i : b){
               CallInst *call = dyn_cast<CallInst>(&i);
               if(fastflags_for_intrfma==false and (call!=nullptr) and IsArithmeticIntrinsicCall(i)){ // Ignore the working of IsArithmeticIntrinsicCall I wrote it for completeness sake.
                    if(i.isFast()) i.setFast(false);
               }
            }
        }
    }
    for(Function &F : M){
        for(BasicBlock &b : F){
            for(Instruction &i : b){
               CallInst *call = dyn_cast<CallInst>(&i);
               if(fastflags_for_intrfma==false and (call!=nullptr) and IsArithmeticIntrinsicCall(i)){
                  Status(i.isFast());
               }
            }
        }
    }
    return PreservedAnalyses::all();
}
</code>```

The Assertion failure :

```<code>opt: llvm-project/llvm/lib/IR/Instruction.cpp:250: bool llvm::Instruction::isFast() const: Assertion `isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"' failed.

</code>```

The langrefLLVM LangRef suggests that call instruction may use fast flag, but how should I be certain of it, I am assuming this assertion failure is caused because of incompatibility.

Edit :

I figured out what went wrong. Thanks for looking into this. Below is the fix.

```<code> for(Instruction &i : b){
  auto FMAop = dyn_cast<FPMathOperator>(&i);
  auto callinst = dyn_cast<CallInst>(&i);
  if(FMAop!=nullptr and callinst!=nullptr and FMAop->isFast() and IsArithmeticIntrinsicCall(i)){
   i.setFast(false);
  }
 }
</code>```

Body:
Hi I am writing a transformation pass to check where on some conditional call instruction I would like to check If fast option is set for that call, instruction and disable it. For example on below call inst, I would like to disable the fast option.

  %call3 = call fast fastcc noundef <8 x float> @_ZL13_mm256_mul_psDv8_fS_(<8 x float> noundef %0, <8 x float> noundef %power.0)

Below is my pass, Don’t mind If I miss something trivial, I’m at a very early stage in compiler dev.

Header file contents :

#include "llvm/IR/PassManager.h"

namespace llvm {

class RemoveFastFlagsToPreventFmaPass: public PassInfoMixin<RemoveFastFlagsToPreventFmaPass> {
public:
    PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
};
} // namespace llvm

#include "llvm/Transforms/Scalar/RemoveFastFlagsToPreventFma.h"
#include "llvm/IR/Instructions.h"
#define Status(b) outs()<<(b?"Yes\n":"No\n")
using namespace llvm;
using namespace std;

bool fastflags_for_intrfma = false;

bool IsArithmeticIntrinsicCall(const Instruction &i){
    return 1;
}

PreservedAnalyses RemoveFastFlagsToPreventFmaPass::run(Module &M, ModuleAnalysisManager &AM){
    for(Function &F : M){
        for(BasicBlock &b : F){
            for(Instruction &i : b){
               CallInst *call = dyn_cast<CallInst>(&i);
               if(fastflags_for_intrfma==false and (call!=nullptr) and IsArithmeticIntrinsicCall(i)){ // Ignore the working of IsArithmeticIntrinsicCall I wrote it for completeness sake.
                    if(i.isFast()) i.setFast(false);
               }
            }
        }
    }
    for(Function &F : M){
        for(BasicBlock &b : F){
            for(Instruction &i : b){
               CallInst *call = dyn_cast<CallInst>(&i);
               if(fastflags_for_intrfma==false and (call!=nullptr) and IsArithmeticIntrinsicCall(i)){
                  Status(i.isFast());
               }
            }
        }
    }
    return PreservedAnalyses::all();
}

The Assertion failure :

opt: llvm-project/llvm/lib/IR/Instruction.cpp:250: bool llvm::Instruction::isFast() const: Assertion `isa<FPMathOperator>(this) && "getting fast-math flag on invalid op"' failed.

The langrefLLVM LangRef suggests that call instruction may use fast flag, but how should I be certain of it, I am assuming this assertion failure is caused because of incompatibility.

Edit :

I figured out what went wrong. Thanks for looking into this. Below is the fix.

 for(Instruction &i : b){
  auto FMAop = dyn_cast<FPMathOperator>(&i);
  auto callinst = dyn_cast<CallInst>(&i);
  if(FMAop!=nullptr and callinst!=nullptr and FMAop->isFast() and IsArithmeticIntrinsicCall(i)){
   i.setFast(false);
  }
 }


问:
apollo federation Can I process this remotely like a hook resolver before request?
My question is as in the title.

When configuring the gateway using apollo federation, there are query parameters that I do not want to expose to the supergraph.

Can I process this remotely like a hook resolver before request?


问:
mic-to-speech package getting terminated without any error
```<code>const MicToSpeech = require('mic-to-speech');

let micToSpeech = new MicToSpeech();

micToSpeech.on('speech', function(buffer) {
  console.log('buffer of speech received');
});

micToSpeech.start();
console.log('Listening for speech')
</code>```

runnung this by node app

but this getting terminated, without entering into on(), beacause on() should be involk by calling start()

Body:
const MicToSpeech = require('mic-to-speech');

let micToSpeech = new MicToSpeech();

micToSpeech.on('speech', function(buffer) {
  console.log('buffer of speech received');
});

micToSpeech.start();
console.log('Listening for speech')

runnung this by node app

but this getting terminated, without entering into on(), beacause on() should be involk by calling start()


问:
When attempting to crop image that is partially hidden below the viewport, jcrop jumps down the page
So i’ve got a task where i have used jcrop to to select areas on an image. But i have run into this
particular issue where if the jcrop container is partially hidden below the screen it scrolls down when trying to make a selection. I don't know where to look or how to fix it.

Here's how you can recreate it
Head over to this website
View it in responsive design mode with a screen size such that half of the image is hidden below the viewport, Then try selecting an area.

I am using vanilla jcrop alongside React. I referred to this issue on github but it was no help.


问:
String state machine @WithStateMachine where project has 2 state machines
our project has 2 state machines (meaning we have 2 sets of enums for states)
and we want to use @WithStateMachine annotation

we have created this meta annotation below as described in the tutorials in order to be type safe

```<code>@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@OnTransition
public @interface StatesOnTransition {

    ProjStates1[] source() default {};

    ProjStates1[] target() default {};
}
</code>```

and we have this function were this annotation is applied

```<code> @StatesOnTransition(target = ProjStates1.STATE3)
 public void moveToSomeState() {
   // do something when state machine is going into ProjStates.STATE3 state
 }
</code>```

The issue is that on the second state machine that we have we have collision with enum values
and in this case the function moveToSomeState is called also for changes on the other state machine. How can we avoid it? (without checking for the state machine ID )

```<code>public enum ProjStates1{
   STATE1
   STATE2
   STATE3
}

public enum ProjStates2{
   STATE3
   STATE4
   STATE5
}
</code>```

as you can see in the 2 enums above the value "STATE3" exists in both enums and in this case when any one of the state machines ritches this values, the moveToSomeState will be called

Body:
our project has 2 state machines (meaning we have 2 sets of enums for states)
and we want to use @WithStateMachine annotation

we have created this meta annotation below as described in the tutorials in order to be type safe

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@OnTransition
public @interface StatesOnTransition {

    ProjStates1[] source() default {};

    ProjStates1[] target() default {};
}

and we have this function were this annotation is applied

 @StatesOnTransition(target = ProjStates1.STATE3)
 public void moveToSomeState() {
   // do something when state machine is going into ProjStates.STATE3 state
 }

The issue is that on the second state machine that we have we have collision with enum values
and in this case the function moveToSomeState is called also for changes on the other state machine. How can we avoid it? (without checking for the state machine ID )

public enum ProjStates1{
   STATE1
   STATE2
   STATE3
}

public enum ProjStates2{
   STATE3
   STATE4
   STATE5
}

as you can see in the 2 enums above the value "STATE3" exists in both enums and in this case when any one of the state machines ritches this values, the moveToSomeState will be called


问:
How to get custom claims in access token not id token?
In my application, I created few attributes and added those custom attributes in optional claims section selecting both access token and id token.

In Manifest file of application, claims added to both types: access token and id token. But the generated access token didn't have added custom attributes. I can see those in id token but my requirement is to get custom attributes in both access token and id token.

What am I missing? Any way to achieve this?


问:
In GitHub branching strategy if there a A,B,C feature branches we want develop
You can see clear explanation in picture If we have A,B,C features in UAT branch but I want to merge only A,B features to master branch what is the strategy we have to use ?textbranching

I need appropriate strategy


问:
Generate divs in random coordinates and random sizes without overlapping
The assignment requires me to create divs with random size and coordinates inside of a parent div. Additionally each of these divs have to be movable on click but also their collision must be prevented so on collision they must be stopped. Additionally, vanilla JavaScript is to be used only. So no additional libraries, or even HTML canvas can be used.

I have finished the displaying of the divs with random size and coordinates but can't prevnt them from overlapping and don't know where to start with the moving option. Here is the code for more clear picture:

HTML:

const container = document.querySelector('.wrapper')

function backgroundColor() {
  var color = '#d1d11d';
  return color;
}

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function addDiv() {
  var div = document.createElement("div");
  const clear = document.getElementById('clear')

  div.className = 'box';
  div.style.top = getRndInteger(1, 800) + 'px';
  div.style.left = getRndInteger(1, 800) + 'px';
  div.style.height = getRndInteger(1, 100) + 'px';
  div.style.width = getRndInteger(1, 100) + 'px';
  div.style.background = backgroundColor();
  document.querySelector('.wrapper').appendChild(div);

  clear.addEventListener('click', () => {
    div.remove();
  });
}

document.querySelector('#create').addEventListener('click', addDiv);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  position: absolute;
}

.wrapper {
  height: 900px;
  width: 900px;
  background-color: blue;
  position: relative;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">

  <button id="create">pressme</button>
  <button id="clear">clear</button>
  <button id="drag">drag</button>

```

Body:
The assignment requires me to create divs with random size and coordinates inside of a parent div. Additionally each of these divs have to be movable on click but also their collision must be prevented so on collision they must be stopped. Additionally, vanilla JavaScript is to be used only. So no additional libraries, or even HTML canvas can be used.

I have finished the displaying of the divs with random size and coordinates but can't prevnt them from overlapping and don't know where to start with the moving option. Here is the code for more clear picture:

HTML:

const container = document.querySelector('.wrapper')

function backgroundColor() {
  var color = '#d1d11d';
  return color;
}

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function addDiv() {
  var div = document.createElement("div");
  const clear = document.getElementById('clear')

  div.className = 'box';
  div.style.top = getRndInteger(1, 800) + 'px';
  div.style.left = getRndInteger(1, 800) + 'px';
  div.style.height = getRndInteger(1, 100) + 'px';
  div.style.width = getRndInteger(1, 100) + 'px';
  div.style.background = backgroundColor();
  document.querySelector('.wrapper').appendChild(div);

  clear.addEventListener('click', () => {
    div.remove();
  });
}

document.querySelector('#create').addEventListener('click', addDiv);

.box {
  position: absolute;
}

.wrapper {
  height: 900px;
  width: 900px;
  background-color: blue;
  position: relative;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">

  <button id="create">pressme</button>
  <button id="clear">clear</button>
  <button id="drag">drag</button>


问:
Create a Razor pay monthly Subscription(not a payment)
I want to integrate a Razorpay monthly subscription to my app but I can't achieve that by reading docs of Razorpay android SDK integration, it is too much confusing and lacks information about how to use their services. not proper and complete demo for referring and understanding about it.

I want to know which steps I should follow for a recurring payment system using Razorpay.

**most of the confusing things are **

status  of subscription after checkout.

next Due of subscription.

How to renew a subscription.

entity What to add and what to not.

start_at and end_at add manually?

Can we create 10 min subscription for testing as what we want?

what I have done for that.

Initialize Object.

Create a plan in the dashboard.

Create a subscription(don't know about start_at entity).

Checkout using subscription_id.

Guide me if anyone has done this before, a helping hand will be appreciated

What I have tried

Create a subscription

```<code>// Calender API ( to set future date after 3 days)
val calendar = Calendar.getInstance()
calendar[Calendar.HOUR] = 0
calendar[Calendar.MINUTE] = 0
calendar[Calendar.SECOND] = 0
calendar.add(Calendar.DATE, 3)
Log.d(TAG, "calendar:    " + calendar.time)
// ------------
// ------------

val requestJSON = JSONObject()
requestJSON.put("plan_id", keyPlan)
requestJSON.put("total_count", 1)
requestJSON.put("quantity", 1)
requestJSON.put("start_at", calendar.timeInMillis / 1000)

val notesJSON = JSONObject()
notesJSON.put(
    "name",
    activity.resources.getString(com.razorpay.R.string.app_name)
)
notesJSON.put(
    "email",
    ""
)
requestJSON.put("notes", notesJSON)
val subscription: Subscription =
    razorpayClient.subscriptions.create(requestJSON)
subscriptionResponse = Gson().fromJson(
    subscription.toString(),
    SubscriptionResponse::class.java
)

editor.putString("_id", subscriptionResponse.id)
editor.commit()
</code>```

Checkout created subscription

```<code>val options = JSONObject()
options.put(
    "name",
    activity.resources.getString(com.razorpay.R.string.app_name)
)
options.put("description", "1 Month Subscription")
options.put("subscription_id", sharePref.getString("_id", ""))
val prefill = JSONObject()
prefill.put(
    "email",
    ""
)
options.put("prefill", prefill)
val readOnly = JSONObject()
// readOnly.put("contact", true);
readOnly.put("email", true)
options.put("readonly", readOnly)
options.put(
    "image",
    ""
)
options.put("theme.color", "#080637")
val retryObj = JSONObject()
retryObj.put("enabled", true)
retryObj.put("max_count", 3)
options.put("retry", retryObj)

activity.runOnUiThread {
    checkout.open(activity, options)
}
</code>```

Body:
I want to integrate a Razorpay monthly subscription to my app but I can't achieve that by reading docs of Razorpay android SDK integration, it is too much confusing and lacks information about how to use their services. not proper and complete demo for referring and understanding about it.

I want to know which steps I should follow for a recurring payment system using Razorpay.

**most of the confusing things are **

status  of subscription after checkout.

next Due of subscription.

How to renew a subscription.

entity What to add and what to not.

start_at and end_at add manually?

Can we create 10 min subscription for testing as what we want?

what I have done for that.

Initialize Object.

Create a plan in the dashboard.

Create a subscription(don't know about start_at entity).

Checkout using subscription_id.

Guide me if anyone has done this before, a helping hand will be appreciated

What I have tried

Create a subscription

// Calender API ( to set future date after 3 days)
val calendar = Calendar.getInstance()
calendar[Calendar.HOUR] = 0
calendar[Calendar.MINUTE] = 0
calendar[Calendar.SECOND] = 0
calendar.add(Calendar.DATE, 3)
Log.d(TAG, "calendar:    " + calendar.time)
// ------------
// ------------

val requestJSON = JSONObject()
requestJSON.put("plan_id", keyPlan)
requestJSON.put("total_count", 1)
requestJSON.put("quantity", 1)
requestJSON.put("start_at", calendar.timeInMillis / 1000)

val notesJSON = JSONObject()
notesJSON.put(
    "name",
    activity.resources.getString(com.razorpay.R.string.app_name)
)
notesJSON.put(
    "email",
    ""
)
requestJSON.put("notes", notesJSON)
val subscription: Subscription =
    razorpayClient.subscriptions.create(requestJSON)
subscriptionResponse = Gson().fromJson(
    subscription.toString(),
    SubscriptionResponse::class.java
)

editor.putString("_id", subscriptionResponse.id)
editor.commit()

Checkout created subscription

val options = JSONObject()
options.put(
    "name",
    activity.resources.getString(com.razorpay.R.string.app_name)
)
options.put("description", "1 Month Subscription")
options.put("subscription_id", sharePref.getString("_id", ""))
val prefill = JSONObject()
prefill.put(
    "email",
    ""
)
options.put("prefill", prefill)
val readOnly = JSONObject()
// readOnly.put("contact", true);
readOnly.put("email", true)
options.put("readonly", readOnly)
options.put(
    "image",
    ""
)
options.put("theme.color", "#080637")
val retryObj = JSONObject()
retryObj.put("enabled", true)
retryObj.put("max_count", 3)
options.put("retry", retryObj)

activity.runOnUiThread {
    checkout.open(activity, options)
}


问:
Is there any way to block notification programatically in android wear os?
```<code> val intent = Intent(Settings.ACTION_ALL_APPS_NOTIFICATION_SETTINGS)
            if (intent.resolveActivity(context.packageManager) != null) {
                context.startActivity(intent)
            }
</code>```

What i am doing is , sending intent to notification setting to switch off the notification but it's not working. Can anyone suggests me something better ?

Is there any way to open notification setting programatically in wear  os ?

Body:
 val intent = Intent(Settings.ACTION_ALL_APPS_NOTIFICATION_SETTINGS)
            if (intent.resolveActivity(context.packageManager) != null) {
                context.startActivity(intent)
            }

What i am doing is , sending intent to notification setting to switch off the notification but it's not working. Can anyone suggests me something better ?

Is there any way to open notification setting programatically in wear  os ?


问:
Funtion on ImageDraw cannot output anything
i'm stuck about 3 hours on my python script, it keep produce error.

This script will output new data per line on csv, and output badge images with specific width and length, and draw output QR code result from the beginning of the script, include all field information to the container image.

it produce error, whenever i give argument 'text' with [2:]

```<code>Error: ImageDraw.textbbox() missing 1 required positional argument: 'text'
</code>```

here is my full code of python script

    # Add the "Scan to Connect" text to the Container image
    draw = ImageDraw.Draw(container)
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_SMALL)
    text_width, text_height = draw.textbbox('Scan to Connect', font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), SCAN_TOP_DISTANCE), 'Scan to Connect', font=font, fill=BLACK)

    #Add the Full Name to the Container image
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_MEDIUM)
    text_width, text_height = draw.textbbox(full_name, font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), NAME_TOP_DISTANCE), full_name, font=font, fill=BLUE)

    #Add the Company Name to the Container image
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_MEDIUM)
    text_width, text_height = draw.textbbox(company_name, font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), COMPANY_TOP_DISTANCE), company_name, font=font, fill=BLACK)

    #Add the Job Title to the Container image
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_MEDIUM)
    text_width, text_height = draw.textbbox(job_title, font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), JOB_TOP_DISTANCE), job_title, font=font, fill=BLACK)

    #Add the "Delegate" text to the Container image
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_MEDIUM)
    text_width, text_height = draw.textbbox('Delegate', font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), JOB_TOP_DISTANCE + 100), 'Delegate', font=font, fill=BLACK)```

Body:
i'm stuck about 3 hours on my python script, it keep produce error.

This script will output new data per line on csv, and output badge images with specific width and length, and draw output QR code result from the beginning of the script, include all field information to the container image.

it produce error, whenever i give argument 'text' with [2:]

Error: ImageDraw.textbbox() missing 1 required positional argument: 'text'

here is my full code of python script

    # Add the "Scan to Connect" text to the Container image
    draw = ImageDraw.Draw(container)
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_SMALL)
    text_width, text_height = draw.textbbox('Scan to Connect', font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), SCAN_TOP_DISTANCE), 'Scan to Connect', font=font, fill=BLACK)

    #Add the Full Name to the Container image
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_MEDIUM)
    text_width, text_height = draw.textbbox(full_name, font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), NAME_TOP_DISTANCE), full_name, font=font, fill=BLUE)

    #Add the Company Name to the Container image
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_MEDIUM)
    text_width, text_height = draw.textbbox(company_name, font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), COMPANY_TOP_DISTANCE), company_name, font=font, fill=BLACK)

    #Add the Job Title to the Container image
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_MEDIUM)
    text_width, text_height = draw.textbbox(job_title, font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), JOB_TOP_DISTANCE), job_title, font=font, fill=BLACK)

    #Add the "Delegate" text to the Container image
    font = ImageFont.truetype(FONT_PATH, FONT_SIZE_MEDIUM)
    text_width, text_height = draw.textbbox('Delegate', font=font)[2:]
    draw.text((int((WIDTH - text_width) / 2), JOB_TOP_DISTANCE + 100), 'Delegate', font=font, fill=BLACK)


问:
Is there better option than storing compressed base64 string to rxdb loki indexeddb to increase performace?
So I am developing PWA with svelte + vite for taking reports which has picture and text in it's form, now all that data is saved on rxdb+lokijs+indexeddb, before I save the picture, I would compress it with svelte image encoder with 50% compression, and then the compressed base64 string would then be compressed again with lz-string.

Now the case here is, if a user has a high end device (Poco F1 with snapdragon 845) then there is no problem in saving the reports until let's say 100 reports before they decompress the compressed lz-string data call the backend API and save it to server DB and delete the one on Indexeddb, but when the user has a low end device such as (Xiaomi A1 with snapdragon 625) then after about 30 to 40 reports the device starts to get slower because of the amount of data saved,

I normally tested pictures with the original length of 100000 compressed it to 40000 and compressed it again to 17000

I am currently trying to search for a way to save the data to client device as picture.jpg and then just save the filename and directory in indexed DB, but I haven't got a good example out of it from the internet

If anyone have another approach on facing this problem that you would suggest to me, I would really appreciate it

I should also point out that the app must be a PWA and works offline because the user usually has lack of network when taking reports


问:
Raster to matrix in R returns NA,Rayshader
So i am downloading the elevation data for a shapefile, which i have saved in my pc. But for some reason. I use this shapefile to download the elevation data in R using elevatr package. To plot this elevation data in raysahder,we need this to be converted into a matrix form but somehow all i get back is NAs.
Heres the code:

```<code>
arw = readOGR("Shape file/american water/American_River_Watershed.shp")
dem_arw =elevatr::get_elev_raster(arw,z = 10,clip = "location")
raster_to_matrix(dem_arw)

</code>```

The output i get is NAs only or simple matrix number entries like:

I have tried other shapefiles too and updating the Rayshader package too but still i get this. This worked almost a week ago but now all of a sudden it doesn't.
Please any help or suggestion would be much appreciated.

Body:
So i am downloading the elevation data for a shapefile, which i have saved in my pc. But for some reason. I use this shapefile to download the elevation data in R using elevatr package. To plot this elevation data in raysahder,we need this to be converted into a matrix form but somehow all i get back is NAs.
Heres the code:

arw = readOGR("Shape file/american water/American_River_Watershed.shp")
dem_arw =elevatr::get_elev_raster(arw,z = 10,clip = "location")
raster_to_matrix(dem_arw)

The output i get is NAs only or simple matrix number entries like:

I have tried other shapefiles too and updating the Rayshader package too but still i get this. This worked almost a week ago but now all of a sudden it doesn't.
Please any help or suggestion would be much appreciated.


问:
React Native making app interactive together with RN navigation
I am making the app reactive by passing up argument from  feature to main App.js like this.
But how do I do that if I am using react navigation native?

Here is Focus feature, I want it to pass 'addSubject' from 'Home' screen:

export const Focus = ({addSubject}) => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen
          name="Home"
          options={{
            title: 'My home',
            headerStyle: {
              backgroundColor: '#f4511e',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {
              fontWeight: 'bold',
            },
          }}
          component={HomeScreen}
        />
```
<p>Here is Home screen, I need to go with 'navigation' but</p>
<pre class="lang-js prettyprint-override"><code>{addSubject}
</code>```

Should be there too somewhere

function HomeScreen({navigation}) {
  const [subject, setSubject] = useState(null);
  console.log(subject);
  return (
    <View
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: colors.darkBlue,
      }}>
      <Text style={styles.text}>Home Screen</Text>
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.textInput}
          label="What would you like to do ?"
          onChangeText={setSubject}
        />
        <View style={styles.button}>
          <RoundedButton
            title="+"
            size={50}
            onPress={() => addSubject(subject)}
          />
        </View>
```
<p>Here is main App.js which I want to pass value to:</p>
<pre class="lang-js prettyprint-override"><code>export default function App() {
  const [currentSubject, setCurrentSubject] = useState(null);
  return (
    <SafeAreaView style={styles.container}>
      {!currentSubject ? (
        <Focus addSubject={setCurrentSubject} />
      ) : (
        <View>
          <Text style={{color: '#fff'}}>I am going to render the timer</Text>
        </View>
      )}
    </SafeAreaView>
  );
}
</code>```

Thanks!

Different zones to place the {addSubject} to move information up to the App.js.

Body:
I am making the app reactive by passing up argument from  feature to main App.js like this.
But how do I do that if I am using react navigation native?

Here is Focus feature, I want it to pass 'addSubject' from 'Home' screen:

export const Focus = ({addSubject}) => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen
          name="Home"
          options={{
            title: 'My home',
            headerStyle: {
              backgroundColor: '#f4511e',
            },
            headerTintColor: '#fff',
            headerTitleStyle: {
              fontWeight: 'bold',
            },
          }}
          component={HomeScreen}
        />

Here is Home screen, I need to go with 'navigation' but

{addSubject}

Should be there too somewhere

function HomeScreen({navigation}) {
  const [subject, setSubject] = useState(null);
  console.log(subject);
  return (
    <View
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: colors.darkBlue,
      }}>
      <Text style={styles.text}>Home Screen</Text>
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.textInput}
          label="What would you like to do ?"
          onChangeText={setSubject}
        />
        <View style={styles.button}>
          <RoundedButton
            title="+"
            size={50}
            onPress={() => addSubject(subject)}
          />
        </View>

Here is main App.js which I want to pass value to:

export default function App() {
  const [currentSubject, setCurrentSubject] = useState(null);
  return (
    <SafeAreaView style={styles.container}>
      {!currentSubject ? (
        <Focus addSubject={setCurrentSubject} />
      ) : (
        <View>
          <Text style={{color: '#fff'}}>I am going to render the timer</Text>
        </View>
      )}
    </SafeAreaView>
  );
}

Thanks!

Different zones to place the {addSubject} to move information up to the App.js.


问:
How can i start activity as a pip mode
i have a activity to show pip but when i intent to this activity app showed a bad animation how can i fix that ?

```<code>val a = Intent(activityContext, PipActivity::class.java)
        a.putExtra("url", url)
        a.putExtra("title", title)
        a.putExtra("duration", player?.currentPosition)
        startActivity(a)
</code>```

and show pip in this

```<code>  fun enterPIPMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
            && packageManager
                .hasSystemFeature(
                    PackageManager.FEATURE_PICTURE_IN_PICTURE
                )
        ) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                enterPictureInPictureMode(
                    PictureInPictureParams.Builder().build()
                )
            }

        }
    }
</code>```

Title: How can i start activity as a pip mode

Body:
i have a activity to show pip but when i intent to this activity app showed a bad animation how can i fix that ?

val a = Intent(activityContext, PipActivity::class.java)
        a.putExtra("url", url)
        a.putExtra("title", title)
        a.putExtra("duration", player?.currentPosition)
        startActivity(a)

and show pip in this

  fun enterPIPMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
            && packageManager
                .hasSystemFeature(
                    PackageManager.FEATURE_PICTURE_IN_PICTURE
                )
        ) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                enterPictureInPictureMode(
                    PictureInPictureParams.Builder().build()
                )
            }

        }
    }


问:
Android Native Flashlight Is not working in android 10 and above
Flash Light is working as expected below android 10 but as soon as i installed my game in android 10 its stop working.

```<code>
 internal AndroidJavaObject camera = null;
    public AndroidCamera()
    {
        WebCamDevice[] devices = WebCamTexture.devices;
        //        Debug.Log("Camera Name:" + devices.Length);
        open();
    }
    public void open()
    {
        if (camera == null)
        {
#if (UNITY_ANDROID && !UNITY_EDITOR)
            try
            {
                //AndroidJavaClass cameraClass = new AndroidJavaClass("android.hardware.Camera") ;
                AndroidJavaClass cameraClass = new AndroidJavaClass("android.hardware.camera2") ;
                    if(cameraClass != null)
                        camera = cameraClass.CallStatic<AndroidJavaObject>("open");
            }
            catch(Exception e)
            {
                Debug.Log("Permission: "+ e);
            }
#endif
        }
    }
    public void release()
    {
        if (camera != null)
        {
            LEDOff();
            camera.Call("release");
            camera = null;
        }
    }
    public void startPreview()
    {
        if (camera != null)
        {
            Debug.Log("AndroidCamera::startPreview()");
            camera.Call("startPreview");
        }
    }
    public void stopPreview()
    {
        if (camera != null)
        {
            Debug.Log("AndroidCamera::stopPreview()");
            LEDOff();
            camera.Call("stopPreview");
        }
    }

    private void setFlashMode(string mode)
    {
        if (camera != null)
        {
            AndroidJavaObject cameraParameters = camera.Call<AndroidJavaObject>("getParameters");
            cameraParameters.Call("setFlashMode", mode);
            camera.Call("setParameters", cameraParameters);
        }
    }

    public void LEDOn()
    {
        if (camera != null)
        {
            setFlashMode("torch");
        }
    }

    public void LEDOff()
    {
        if (camera != null)
        {
            setFlashMode("off");
        }
    }

</code>```

I also change "android.hardware.Camera" to "android.hardware.camera2" as the API "android.hardware.Camera" is depricated defined here Android Guide

I ask user permission to access camera and initialize my object after the user gave access to the camera i am using runtime permission for the access request as defined here Unity Runtime Request.

Body:
Flash Light is working as expected below android 10 but as soon as i installed my game in android 10 its stop working.

 internal AndroidJavaObject camera = null;
    public AndroidCamera()
    {
        WebCamDevice[] devices = WebCamTexture.devices;
        //        Debug.Log("Camera Name:" + devices.Length);
        open();
    }
    public void open()
    {
        if (camera == null)
        {
#if (UNITY_ANDROID && !UNITY_EDITOR)
            try
            {
                //AndroidJavaClass cameraClass = new AndroidJavaClass("android.hardware.Camera") ;
                AndroidJavaClass cameraClass = new AndroidJavaClass("android.hardware.camera2") ;
                    if(cameraClass != null)
                        camera = cameraClass.CallStatic<AndroidJavaObject>("open");
            }
            catch(Exception e)
            {
                Debug.Log("Permission: "+ e);
            }
#endif
        }
    }
    public void release()
    {
        if (camera != null)
        {
            LEDOff();
            camera.Call("release");
            camera = null;
        }
    }
    public void startPreview()
    {
        if (camera != null)
        {
            Debug.Log("AndroidCamera::startPreview()");
            camera.Call("startPreview");
        }
    }
    public void stopPreview()
    {
        if (camera != null)
        {
            Debug.Log("AndroidCamera::stopPreview()");
            LEDOff();
            camera.Call("stopPreview");
        }
    }

    private void setFlashMode(string mode)
    {
        if (camera != null)
        {
            AndroidJavaObject cameraParameters = camera.Call<AndroidJavaObject>("getParameters");
            cameraParameters.Call("setFlashMode", mode);
            camera.Call("setParameters", cameraParameters);
        }
    }

    public void LEDOn()
    {
        if (camera != null)
        {
            setFlashMode("torch");
        }
    }

    public void LEDOff()
    {
        if (camera != null)
        {
            setFlashMode("off");
        }
    }

I also change "android.hardware.Camera" to "android.hardware.camera2" as the API "android.hardware.Camera" is depricated defined here Android Guide

I ask user permission to access camera and initialize my object after the user gave access to the camera i am using runtime permission for the access request as defined here Unity Runtime Request.


问:
How to remove black background from the image which is converted from Base 64 string
We are converting Base64 string to image (Histogram graph) and its also happening properly.

Only issue is with histogram graph background color is coming in black shed()).

So i need help to convert image (histogram graph) into transparent background ()).

Please let me know how i can achieve this in C# Langauge

Need solution for this one


问:
Has my PDF rendered correctly?. And how to validate wheather it is rendered correctly using PDFBox
I am working with project in which I am handling PDF file in order to verify the valies generated in report but, when I opened it on chrome as well as in adobe pdfviewer
it feels little off:
pic:

A) In Adobe:

B) In chrome:

As you can see in both of the mediums the column  after "Alaram Value" i.e "Low Limit" isn't visible very well. So I decided to view it in java using PDFBox.Using PDFBox in java I view it in java there too the output was shady

Console O/P:

Here too if you can see the value after "Alarm Value " i.e "Low Value" isn't rendered aptly
P.S: Console O/P is of the same page as shown in the above screenshots. So is there anyway to handle this scenario and also is there any way to validate the rendered pdf/ validate the downloaded pdf is corrent or not

Java Code:

```<code>File file = new File(System.getProperty("user.dir") + "//Download//" + "random" + ".pdf");
        if (file.exists()) {
            System.out.println("Its"+true   );
            PDDocument doc = PDDocument.load(file);
            PDFTextStripper pdfStripper = new PDFTextStripper();
            pdfStripper.setStartPage(1);
            pdfStripper.setEndPage(1);

            int count = doc.getNumberOfPages();
            PDDocumentInformation pdd = doc.getDocumentInformation();
            System.out.println("tile"+pdfStripper.getText(doc));
            System.out.println(count);
            doc.close();
        }
</code>```

POM.xml:

```<code><!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.27</version>
        </dependency>

    </dependencies>
</code>```

Please help me if you can

Body:
I am working with project in which I am handling PDF file in order to verify the valies generated in report but, when I opened it on chrome as well as in adobe pdfviewer
it feels little off:
pic:

A) In Adobe:

B) In chrome:

As you can see in both of the mediums the column  after "Alaram Value" i.e "Low Limit" isn't visible very well. So I decided to view it in java using PDFBox.Using PDFBox in java I view it in java there too the output was shady

Console O/P:

Here too if you can see the value after "Alarm Value " i.e "Low Value" isn't rendered aptly
P.S: Console O/P is of the same page as shown in the above screenshots. So is there anyway to handle this scenario and also is there any way to validate the rendered pdf/ validate the downloaded pdf is corrent or not

Java Code:

File file = new File(System.getProperty("user.dir") + "//Download//" + "random" + ".pdf");
        if (file.exists()) {
            System.out.println("Its"+true   );
            PDDocument doc = PDDocument.load(file);
            PDFTextStripper pdfStripper = new PDFTextStripper();
            pdfStripper.setStartPage(1);
            pdfStripper.setEndPage(1);

            int count = doc.getNumberOfPages();
            PDDocumentInformation pdd = doc.getDocumentInformation();
            System.out.println("tile"+pdfStripper.getText(doc));
            System.out.println(count);
            doc.close();
        }

POM.xml:

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.27</version>
        </dependency>

    </dependencies>

Please help me if you can


问:
why is my mern app deployed on heroku using local server
I deployed my MERN app on heroku it is working fine. However, the deployed app uses my local server. when I stop my local server, the deployed app stops working. What am I doing wrongly?</p>
```<code>Here is my package.json file
{
  "name": "careplan",
  "version": "1.0.0",
  "description": "careApp",
  "main": "app.js",
  "scripts": {
    "start": "node server.js",
    "start:prod": "SET NODE_ENV=production&& server.js",
    "debug": "ndb server.js",
    "dev":"nodemon server.js",
    "heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build"

  },
  "engines": {
    "node": "16.13.1"
  },
  "author": "Oladimeji Shopeyin",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.0.1",
    "cors": "^2.8.5",
    "dotenv": "^14.2.0",
    "express": "^4.17.2",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.13.14",
    "morgan": "^1.10.0",
    "validator": "^13.7.0"
  },
  "devDependencies": {
    "eslint": "^8.7.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.25.4",
    "eslint-plugin-jsx-a11y": "^6.5.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.28.0",
    "nodemon": "^2.0.19",
    "prettier": "^2.5.1"
  }
}
</code>```

Body:
I deployed my MERN app on heroku it is working fine. However, the deployed app uses my local server. when I stop my local server, the deployed app stops working. What am I doing wrongly?

Here is my package.json file
{
  "name": "careplan",
  "version": "1.0.0",
  "description": "careApp",
  "main": "app.js",
  "scripts": {
    "start": "node server.js",
    "start:prod": "SET NODE_ENV=production&& server.js",
    "debug": "ndb server.js",
    "dev":"nodemon server.js",
    "heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build"

  },
  "engines": {
    "node": "16.13.1"
  },
  "author": "Oladimeji Shopeyin",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.0.1",
    "cors": "^2.8.5",
    "dotenv": "^14.2.0",
    "express": "^4.17.2",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.13.14",
    "morgan": "^1.10.0",
    "validator": "^13.7.0"
  },
  "devDependencies": {
    "eslint": "^8.7.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.25.4",
    "eslint-plugin-jsx-a11y": "^6.5.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.28.0",
    "nodemon": "^2.0.19",
    "prettier": "^2.5.1"
  }
}


问:
SSRS Reports GroupBy Parameters value
I am trying to get column values in the parameters.I have a year column and in this column, I have 20 records with the same year 2020 but when I used this value in parameters then it shows 20 times "2020" I want only one time how can I group by this and use it in parameters?

I have tried many things but didn't get any soluion

Title: SSRS Reports GroupBy Parameters value


问:
After using openid "launchpad ID" doing authentication, gerrit's web url has double "/", and web return not found
After using openid "launchpad ID" doing authentication, gerrit's web url has double "/", and web return not found:

Type the following URL into your browser:

"https://gerrit_server"

The launchpad ID authentication page is displayed, after login the web url has one more '/' in the end, like 'https://gerrit_server//'

After deleting one '/' in the end, change to 'https://gerrit_server/', after reload, it's ok


问:
Android studio unit test not found package after bumblebee version update to Dolphin version
I was using android studio bumblebee before,and the following unit test is ok

```<code>package com.coolanalyzer;

import static org.junit.Assert.assertEquals;

import com.coolanalyzer.FrameImage2D;

import org.junit.Test;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() {
        assertEquals(4, 2 + 2);
    }

    @Test
    public void test_ImageData(){
        //arrange

        int[][] twoDim = {{1,1},{2,2},{3,3},{4,4}};

        FrameImage2D myImage = new FrameImage2D(twoDim[0].length, twoDiml.length , twoDim);
        myImage.GetWidth();

    }
}
</code>```

but in android studio  Dolphin it can not be used, and show Cannot resolve symbol 'FrameImage2D' problem, how can i fix it?

I had download Chipmunk version and had same issue.

Body:
I was using android studio bumblebee before,and the following unit test is ok

package com.coolanalyzer;

import static org.junit.Assert.assertEquals;

import com.coolanalyzer.FrameImage2D;

import org.junit.Test;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see Testing documentation
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() {
        assertEquals(4, 2 + 2);
    }

    @Test
    public void test_ImageData(){
        //arrange

        int[][] twoDim = {{1,1},{2,2},{3,3},{4,4}};

        FrameImage2D myImage = new FrameImage2D(twoDim[0].length, twoDiml.length , twoDim);
        myImage.GetWidth();

    }
}

but in android studio  Dolphin it can not be used, and show Cannot resolve symbol 'FrameImage2D' problem, how can i fix it?

I had download Chipmunk version and had same issue.


问:
Is it possible to let TS dynamically distinguish paths?
project

This is what my project looks like, in big project contains lots of small projects there, which share the build config and other common settings.

Now, I want to config the relate path, like '@'. I hope it to point to abc when it's inside the abc folder, and point to cba when it's inside the cba folder...

This can work on build config, and I am wondering if Typescript can support this behavior via tsconfig or some other workaround.

A clear representation of my problem is shown in this project.https://github.com/wuliqun/ts_paths