问:
Can we use webEngage for flutter web?
I'm trying webEngage with flutter web. I tried adding this script in index.html.

```<code><script id='_webengage_script_tag' type='text/javascript'>
    var webengage;
    ! function(w, e, b, n, g) {
        function o(e, t) {
            e[t[t.length - 1]] = function() {
                r.__queue.push([t.join("."), arguments])
            }
        }
        var i, s, r = w[b],
            z = " ",
            l = "init options track screen onReady".split(z),
            a = "feedback survey notification".split(z),
            c = "options render clear abort".split(z),
            p = "Open Close Submit Complete View Click".split(z),
            u = "identify login logout setAttribute".split(z);
        if (!r || !r.__v) {
            for (w[b] = r = {
                    __queue: [],
                    is_spa: 1, //Change this to 0 if you do not wish to use default SPA behaviour of WebEngage SDK
                    __v: "6.0",
                    user: {}
                }, i = 0; i < l.length; i++) o(r, [l[i]]);
            for (i = 0; i < a.length; i++) {
                for (r[a[i]] = {}, s = 0; s < c.length; s++) o(r[a[i]], [a[i], c[s]]);
                for (s = 0; s < p.length; s++) o(r[a[i]], [a[i], "on" + p[s]])
            }
            for (i = 0; i < u.length; i++) o(r.user, ["user", u[i]]);
            setTimeout(function() {
                var f = e.createElement("script"),
                    d = e.getElementById("_webengage_script_tag");
                f.type = "text/javascript", f.async = !0, f.src = ("https:" == e.location.protocol ? "https://ssl.widgets.webengage.com" : "http://cdn.widgets.webengage.com") + "/js/webengage-min-v-6.0.js", d.parentNode.insertBefore(f, d)
            })
        }
    }(window, document, "webengage");
    webengage.init('myCode'); //replace the YOUR_WEBENGAGE_LICENSE_CODE with your WebEngage Account License Code
</script>
</code>```

but when calling webengage.init('myCode'); am getting this error.

%cWebEngage%c %cERROR

Title: Can we use webEngage for flutter web?

Body:
I'm trying webEngage with flutter web. I tried adding this script in index.html.

but when calling webengage.init('myCode'); am getting this error.

%cWebEngage%c %cERROR


来源: stackexchange

问:
Adding data to a JTable from a database
I've created a class 'ProductTable' which is extends to JTable. The purpose of the class is to load data from a database and add all the data to the table when it is instantiating. Below is what I tried.

```<code>public class ProductTable extends JTable {

    static Statement st;
    static Connection conn;
    static ResultSet rs;

    public ProductTable() {

        try {
            conn = ConnectDB.connect();
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(ProductTable.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
               loadProductTable();
        } catch (SQLException ex) {
               Logger.getLogger(ProductTable.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void loadProductTable() throws SQLException {

        String sql = "SELECT product_id, produce_code, product_name, category_id, unit_in_stock, unit_price FROM tblproduct";
        st = conn.prepareStatement(sql);
        rs = st.executeQuery(sql);
        while (rs.next()) {
            Object id = String.valueOf(rs.getInt("product_id"));
            Object code = String.valueOf(rs.getLong("produce_code"));
            Object name = rs.getString("product_name");
            Object category = String.valueOf(rs.getInt("category_id"));
            Object instock = String.valueOf(rs.getFloat("unit_in_stock"));
            Object price = String.valueOf((long) rs.getFloat("unit_price"));

            Object[] objects = new Object[] {id,code,name,category,instock,price};

            setModel(new javax.swing.table.DefaultTableModel(
                    new Object [][] {
                        objects
                    },
                    new String [] {
                        "ID", "CODE", "NAME", "CATEGORY", "IN STOCK", "UNIT PRICE", ""
                    }
            ));

        }
    }
}
</code>```

The problem is when I ran the program from another class, the table only shows the last row of data.

I tried to add the method addRow() at the end of setModel(........).addRow(); but Netbeans says "void type not allowed here".

ContentLicense: CC BY-SA 4.0

Title: Adding data to a JTable from a database

Body:
I've created a class 'ProductTable' which is extends to JTable. The purpose of the class is to load data from a database and add all the data to the table when it is instantiating. Below is what I tried.

public class ProductTable extends JTable {

    static Statement st;
    static Connection conn;
    static ResultSet rs;

    public ProductTable() {

        try {
            conn = ConnectDB.connect();
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(ProductTable.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
               loadProductTable();
        } catch (SQLException ex) {
               Logger.getLogger(ProductTable.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void loadProductTable() throws SQLException {

        String sql = "SELECT product_id, produce_code, product_name, category_id, unit_in_stock, unit_price FROM tblproduct";
        st = conn.prepareStatement(sql);
        rs = st.executeQuery(sql);
        while (rs.next()) {
            Object id = String.valueOf(rs.getInt("product_id"));
            Object code = String.valueOf(rs.getLong("produce_code"));
            Object name = rs.getString("product_name");
            Object category = String.valueOf(rs.getInt("category_id"));
            Object instock = String.valueOf(rs.getFloat("unit_in_stock"));
            Object price = String.valueOf((long) rs.getFloat("unit_price"));

            Object[] objects = new Object[] {id,code,name,category,instock,price};

            setModel(new javax.swing.table.DefaultTableModel(
                    new Object [][] {
                        objects
                    },
                    new String [] {
                        "ID", "CODE", "NAME", "CATEGORY", "IN STOCK", "UNIT PRICE", ""
                    }
            ));

        }
    }
}

The problem is when I ran the program from another class, the table only shows the last row of data.

I tried to add the method addRow() at the end of setModel(........).addRow(); but Netbeans says "void type not allowed here".


问:
My schema.prisma file is too big. Is it possible to modularize it?
My schema.prisma file is too big. Is it possible to modularize it, that is, to have it in modules such as: financial.schema.prisma, billing.schema.prisma, ...?</p>


问:
Is user n/w speed impacts the s2s calls time involved in api call
Let Say two user accessing a same end point in which S2S call is involved. One user is on poor connectivity & other is on good n/w speed. Below is the time taken by servers.

API Response time for user on good Connectivity- T1+T2+delta

API Response time for user on poor Connectivity- T3+T4+delta

It is understood T3 > T1.

What about T2 & T4, will T4 > T2 or it will be same assuming data packets will be sends from Server1 to Server2, & it will depend on Server1 Net Speed only.


问:
What's wrong with creating a dictionary in ClickHouse?
I need to create a dictionary in ClickHouse, which will request data via the API. The dictionary is being created, but when I open it I get errors.

I create a dictionary like this:

```<code>CREATE DICTIONARY IF NOT EXISTS dbName.AppDict
(
    Name String,
    AppType Int32
)
PRIMARY KEY Name
SOURCE(HTTP(
    url 'http://my_service.ru/api/Services/list?Offset=0'
    format 'JSONCompactStringsEachRowWithNamesAndTypes'
    credentials(user 'user' password 'xyz')
))
LAYOUT(COMPLEX_KEY_HASHED())
LIFETIME(60);
</code>```

When I open the dictionary, I get the following error:

```<code>ClickHouse exception, code: 1002, host: localhost, port: 8123; Code: 27. DB::Exception: Cannot parse input: expected '[' before: '{"result":{"totalCount":2,"services":[{"version": "1.0.1","platformOS": "windows","name": "my_service1",: While executing JSONCompactEachRowRowInputFormat. (CANNOT_PARSE_INPUT_ASSERTION_FAILED) (version 21.11.2.2 (official build))
</code>```

by url from http://my_service.ru/api/Services/list?Offset=0 I get the following response:

```<code>{
    "result": {
        "totalCount": 2,
        "services": [
            {
                "version": "1.0.1",
                "platformOS": "windows",
                "name": "my_service1",
                "appType": 0
            },
            {
                "version": "2.0.0",
                "platformOS": "windows",
                "name": "my_service2",
                "appType": 1
            }
        ]
    }
}
</code>```

What needs to be done so that when I open a dictionary I get?

Name
AppType

my_service1
1.0.1

my_service2
2.0.0

Body:
I need to create a dictionary in ClickHouse, which will request data via the API. The dictionary is being created, but when I open it I get errors.

I create a dictionary like this:

CREATE DICTIONARY IF NOT EXISTS dbName.AppDict
(
    Name String,
    AppType Int32
)
PRIMARY KEY Name
SOURCE(HTTP(
    url 'http://my_service.ru/api/Services/list?Offset=0'
    format 'JSONCompactStringsEachRowWithNamesAndTypes'
    credentials(user 'user' password 'xyz')
))
LAYOUT(COMPLEX_KEY_HASHED())
LIFETIME(60);

When I open the dictionary, I get the following error:

ClickHouse exception, code: 1002, host: localhost, port: 8123; Code: 27. DB::Exception: Cannot parse input: expected '[' before: '{"result":{"totalCount":2,"services":[{"version": "1.0.1","platformOS": "windows","name": "my_service1",: While executing JSONCompactEachRowRowInputFormat. (CANNOT_PARSE_INPUT_ASSERTION_FAILED) (version 21.11.2.2 (official build))

by url from http://my_service.ru/api/Services/list?Offset=0 I get the following response:

{
    "result": {
        "totalCount": 2,
        "services": [
            {
                "version": "1.0.1",
                "platformOS": "windows",
                "name": "my_service1",
                "appType": 0
            },
            {
                "version": "2.0.0",
                "platformOS": "windows",
                "name": "my_service2",
                "appType": 1
            }
        ]
    }
}

What needs to be done so that when I open a dictionary I get?

Name
AppType

my_service1
1.0.1

my_service2
2.0.0


问:
Finding code for laravel category subcategories task
Create Category Module with Parent and subcategory. Both Category handle in same table. Table name should be category_master with fields id, cat_parent_id, cat_title, cat_status, created-at, updated_at. Than after get all  parent category with subcategory in frontend give checkbox the all category. max 3 parent category should be checkable at a time

I want code of this task.


问:
How to prevent undefined value $push Mongodb aggregation $group
I tried to push to $push number value($totalTurnaroundTimeCg) in Mongodb aggregation $group. in the value($totalTurnaroundTimeCg) can some time undefined. so i can write the code. how to solve this

Note: joi validation is throwing error allTotalTurnaroundTimeCgs: Joi.number().optional()

My code

```<code>allTotalTurnaroundTimeCgs: {
                        $push: {
                            $cond: [
                                { $ne: ["$totalTurnaroundTimeCg", undefined] },
                                "$totalTurnaroundTimeCg",
                                "$$REMOVE",
                            ],
                        },
                    },
</code>```

Body:
I tried to push to $push number value($totalTurnaroundTimeCg) in Mongodb aggregation $group. in the value($totalTurnaroundTimeCg) can some time undefined. so i can write the code. how to solve this

Note: joi validation is throwing error allTotalTurnaroundTimeCgs: Joi.number().optional()

My code

allTotalTurnaroundTimeCgs: {
                        $push: {
                            $cond: [
                                { $ne: ["$totalTurnaroundTimeCg", undefined] },
                                "$totalTurnaroundTimeCg",
                                "$$REMOVE",
                            ],
                        },
                    },


问:
Traefik Apply Middleware On Domain Names
There's a need to apply a request body size limit to certain domain names via Traefik.

The Traefik middleware is:

```<code>apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: request-limits
spec:
  buffering:
    maxRequestBodyBytes: 10485760
    retryExpression: "IsNetworkError() && Attempts() < 2"
</code>```

And this can be applied globally via:

```<code>additionalArguments:
  - --entrypoints.websecure.http.middlewares=traefik-request-limits@kubernetescrd
</code>```

How can this middleware be applied to certain domain names?

What I've tried - remove the above additionalArguments, and replace it with:

```<code>http:
  routers:
    http-specific:
      rule: "HostRegexp(`{name:(.*-)(service|mock|proxy)\\.(.*)\\.(example\\.com}`)"
      entrypoints:
        - websecure
      middlewares:
        - request-limits
      service:
        - noop@internal
</code>```

However - the above route is not getting created.

Any tips or pointers would be much appreciated.

Traefik Feature Status

List item

https://github.com/traefik/traefik/issues/5098

Body:
There's a need to apply a request body size limit to certain domain names via Traefik.

The Traefik middleware is:

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: request-limits
spec:
  buffering:
    maxRequestBodyBytes: 10485760
    retryExpression: "IsNetworkError() && Attempts() < 2"

And this can be applied globally via:

additionalArguments:
  - --entrypoints.websecure.http.middlewares=traefik-request-limits@kubernetescrd

How can this middleware be applied to certain domain names?

What I've tried - remove the above additionalArguments, and replace it with:

http:
  routers:
    http-specific:
      rule: "HostRegexp(`{name:(.*-)(service|mock|proxy)\\.(.*)\\.(example\\.com}`)"
      entrypoints:
        - websecure
      middlewares:
        - request-limits
      service:
        - noop@internal

However - the above route is not getting created.

Any tips or pointers would be much appreciated.

Traefik Feature Status

List item

https://github.com/traefik/traefik/issues/5098


问:
Best practice for large size image handling/processing with neural network
I have tried some neural network architectures for object classification and recognition. Such neural networks can distinguish cats from dogs, classify numbers from MNIST dataset, and recover private keys from public ones. A feature of such models is a small number of neurons in the last layer, and the input images are scaled to certain rather small sizes, for example, 224x224 pixels. Now I would like to try to solve more complex (for me) problems using a neural network. I'm interested in neural networks for image super resolution. For these purposes, I want to use autoencoders or a fully convolutional network like UNET. At the moment I don't understand how exactly to handle large size images. Is it necessary to feed the complete image to the input of the neural network, or is it necessary to process the image in parts, dividing it into a smaller tile and forming the final image from the fragments received at the output of the network? I think that in the first case, the network will become very large and will not be able to converge to good results in the learning process, and in the second case, artifacts will appear on the final image at the junctions of the resulting fragments. All the papers and articles I've read use small image sizes as examples.

But how then do generative adversarial networks (GAN) models, autoencoders for noise reduction, semantic segmentation, instance segmentation or image upscaling networks work? After all, the output of such a network should be a large image, for example, 2K, 4K, 8K resolution. Do I understand correctly that the number of input and output neurons in such networks is in the millions? How does this affect training time and convergence? Or are there some other ways to process large images with neural networks?


问:
How to securely upload file in Edge or Chrome using Classic ASP without extensions or IE Mode
I have a Classic ASP application that allows the user to upload a file which is then saved to a network location. The problem is that the current versions of Edge and Chrome have instituted security measures that now prevent the file upload to work correctly without using IE Mode (in Edge) or an extension (in Chrome) that bypass the modern browser security functionality. I am currently using the code as seen in How to upload files with asp-classic, which does work, but only if I bypass the security by using IE Mode or the Chrome extension.

I need to modify the ASP page in some way to allow for file uploads. I have found some mention of using ADODB Stream objects but I am not sure how this would be implemented or if it would solve my problem.

Any suggestions would be appreciated.


问:
Use a python script from my nodeJS server when client ask for in CPANEL (NameCheap)
I have a nodeJS app with react frontend. The server use a python script to send to client when client ask for with data.

everything workin' on localhost, but when i try to put it online it's not working...

I host it on namecheap.

I have put the react front end on publicHTML

i have created a nodeJS application linked with the frontend

I have created a python app for run the script

In independant usage everything work, but when i try to use it the nodeJS server don't run the script because i have a module (beautifulsoup bs4) is not imported...

but i have try different way to acces in a good way the script but nothing work...

```<code>// server/index.js

const express = require("express");

const { spawn, exec } = require('child_process');

const PORT = process.env.PORT || 3001;

const app = express();

var bodyParser = require('body-parser')

app.post('/run-script', async (req, res) => {
  try {
      const dataNumber = req.body;
      data = dataNumber.key.replace(/\D/g, "");
      console.log(data)
      //run python script with data
      const pythonProcess = spawn('python', ['./home/bonkxwng/myPythonApp/scrapSms.py', data]);
      let result = '';
      pythonProcess.stdout.on('data', (data) => {
          result += data.toString();

      });
      pythonProcess.stderr.on('data', (data) => {
          console.error(`stderr: ${data}`);
      });
      pythonProcess.on('close', (code) => {
          console.log(`child process exited with code ${code}`);
          res.json({ result });

      });
  } catch (error) {
      console.error(error);
      res.status(500).json({ error });
  }
});

app.get("/api", (req, res) => {
    res.json({ message: "Hello from server!" });
  });

  app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
  });
</code>```
```<code>#scrapSms.py
# -*- coding: utf-8 -*-

import requests
import random
from bs4 import BeautifulSoup
import json
import sys
import cgi

parameter = sys.argv[1]
URL = "http://receive-smss.com/sms/"+parameter+"/"

user_agents = [
  "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0",
  "Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0",
  "Mozilla/5.0 (X11; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0"
  ]
random_user_agent = random.choice(user_agents)
headers = {
    'User-Agent': random_user_agent
}
page = requests.get(URL,headers=headers)

soup = BeautifulSoup(page.content, "html.parser")
job_elements = soup.find_all("table", class_="table table-bordered wrptable tbdif")

for job_element in job_elements:
    for img in job_element.find_all('img'):
        img.decompose()

data = {}
i = 0

result = str(job_elements)

result = result.replace('[','')
result = result.replace(']','')
result = result.replace(';','')
result = result.replace('\r\n','\n')
result = result.replace('\n','')
result = result.replace('table ','table style="border 2px black;"')
result = result.encode(encoding='utf-8', errors='ignore')
print(result)
</code>```

my python app setup

NodeJsSetup

Body:
I have a nodeJS app with react frontend. The server use a python script to send to client when client ask for with data.

everything workin' on localhost, but when i try to put it online it's not working...

I host it on namecheap.

I have put the react front end on publicHTML

i have created a nodeJS application linked with the frontend

I have created a python app for run the script

In independant usage everything work, but when i try to use it the nodeJS server don't run the script because i have a module (beautifulsoup bs4) is not imported...

but i have try different way to acces in a good way the script but nothing work...

// server/index.js

const express = require("express");

const { spawn, exec } = require('child_process');

const PORT = process.env.PORT || 3001;

const app = express();

var bodyParser = require('body-parser')

app.post('/run-script', async (req, res) => {
  try {
      const dataNumber = req.body;
      data = dataNumber.key.replace(/\D/g, "");
      console.log(data)
      //run python script with data
      const pythonProcess = spawn('python', ['./home/bonkxwng/myPythonApp/scrapSms.py', data]);
      let result = '';
      pythonProcess.stdout.on('data', (data) => {
          result += data.toString();

      });
      pythonProcess.stderr.on('data', (data) => {
          console.error(`stderr: ${data}`);
      });
      pythonProcess.on('close', (code) => {
          console.log(`child process exited with code ${code}`);
          res.json({ result });

      });
  } catch (error) {
      console.error(error);
      res.status(500).json({ error });
  }
});

app.get("/api", (req, res) => {
    res.json({ message: "Hello from server!" });
  });

  app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
  });

#scrapSms.py
# -*- coding: utf-8 -*-

import requests
import random
from bs4 import BeautifulSoup
import json
import sys
import cgi

parameter = sys.argv[1]
URL = "http://receive-smss.com/sms/"+parameter+"/"

user_agents = [
  "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0",
  "Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0",
  "Mozilla/5.0 (X11; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0"
  ]
random_user_agent = random.choice(user_agents)
headers = {
    'User-Agent': random_user_agent
}
page = requests.get(URL,headers=headers)

soup = BeautifulSoup(page.content, "html.parser")
job_elements = soup.find_all("table", class_="table table-bordered wrptable tbdif")

for job_element in job_elements:
    for img in job_element.find_all('img'):
        img.decompose()

data = {}
i = 0

result = str(job_elements)

result = result.replace('[','')
result = result.replace(']','')
result = result.replace(';','')
result = result.replace('\r\n','\n')
result = result.replace('\n','')
result = result.replace('table ','table style="border 2px black;"')
result = result.encode(encoding='utf-8', errors='ignore')
print(result)

my python app setup

NodeJsSetup


问:
How to normalize amplitude differeces within the 433Mhz signal burst in GNU Radio Companion?
I'm learning SDR by trying to decode different 433Mhz keyfob signals.

My initial flow for capture and pre-processing looks like this:

What I get on the sink is:

I guess the bits are visible fine and I could proceed to decode it somehow. But I am worried about the big difference in the amplitude: the very beginning of the burst has much higher amplitude in comparison to the rest of the packet. This picture is very consistent (I was not able to get bursts with more balanced amplitudes). If I was speaking about music recording I would look for a compression method. But I don't know what the equivalent in the SDR world is.

I'm not sure if this will be a problem when I'll try to quadrature demod, binary slice and/or clock recover.

Is this a known problem and what is the approach to eliminate it within GNU Radio Companion?


问:
Collision of polygons while they move
I'm creating a game called "Asteroids" and all the objects that I'm drawing are with polygons. I have a few methods to check the collision between two polygons, but it doesn't work all the time. For example, it might be working bad when I check collision when the player of the game is currently moving around the screen.

Here is the code of the class that contains all the methods for game objects collisions. Thanks for the helpers.

```<code>public class Hits
{
   private static boolean isPolygonCollidingWithAnotherPolygon(Polygon p1, Polygon p2) {
      for (int i = 0; i < p1.npoints; i++) {
         Point p = new Point(p1.xpoints[i], p1.ypoints[i]);
         if (p2.contains(p))
            return true;
      }

      for (int i = 0; i < p2.npoints; i++) {
         Point p = new Point(p2.xpoints[i], p2.ypoints[i]);
         if (p1.contains(p))
            return true;
      }

      return false;
   }

   // ball with spaceship
   public static boolean isBallHittingSpaceship(Ball b,Spaceship s)
   {
      return b.isFromShooter && s.getPolygon().contains(b.getX(),b.getY());
   }

   // ball with asteroid
   public static boolean isBallHittingAsteroid(Ball b,Asteroid a)
   {
      return a.getPolygon().contains(b.getX(),b.getY());
   }

   // ball with player
   public static boolean isShooterHittingBall(Ball b, Player player)
   {
      return !b.isFromShooter && player.getPolygon().contains(b.getX(), b.getY());
   }

   // spaceship with asteroid
   public static boolean isSpaceshipHittingAsteroid(Spaceship spaceship ,Asteroid asteroid)
   {
            return isPolygonCollidingWithAnotherPolygon(spaceship.getPolygon(),  asteroid.getPolygon());
   }

   // asteroid with player
   public static boolean isShooterHittingAsteroid(Player player , Asteroid asteroid)
   {
        return isPolygonCollidingWithAnotherPolygon(player.getPolygon(), asteroid.getPolygon());
   }

   // spaceship with player
   public static boolean isSpaceshipHittingShooter(Spaceship spaceship, Player player)
   {
        return isPolygonCollidingWithAnotherPolygon(spaceship.getPolygon(), player.getPolygon());
   }
}
</code>```

As seen in the code, I tried to check every possible point in one polygon, if it's in the other polygon, but still it doesn't work properly.

Title: Collision of polygons while they move

Body:
I'm creating a game called "Asteroids" and all the objects that I'm drawing are with polygons. I have a few methods to check the collision between two polygons, but it doesn't work all the time. For example, it might be working bad when I check collision when the player of the game is currently moving around the screen.

Here is the code of the class that contains all the methods for game objects collisions. Thanks for the helpers.

public class Hits
{
   private static boolean isPolygonCollidingWithAnotherPolygon(Polygon p1, Polygon p2) {
      for (int i = 0; i < p1.npoints; i++) {
         Point p = new Point(p1.xpoints[i], p1.ypoints[i]);
         if (p2.contains(p))
            return true;
      }

      for (int i = 0; i < p2.npoints; i++) {
         Point p = new Point(p2.xpoints[i], p2.ypoints[i]);
         if (p1.contains(p))
            return true;
      }

      return false;
   }

   // ball with spaceship
   public static boolean isBallHittingSpaceship(Ball b,Spaceship s)
   {
      return b.isFromShooter && s.getPolygon().contains(b.getX(),b.getY());
   }

   // ball with asteroid
   public static boolean isBallHittingAsteroid(Ball b,Asteroid a)
   {
      return a.getPolygon().contains(b.getX(),b.getY());
   }

   // ball with player
   public static boolean isShooterHittingBall(Ball b, Player player)
   {
      return !b.isFromShooter && player.getPolygon().contains(b.getX(), b.getY());
   }

   // spaceship with asteroid
   public static boolean isSpaceshipHittingAsteroid(Spaceship spaceship ,Asteroid asteroid)
   {
            return isPolygonCollidingWithAnotherPolygon(spaceship.getPolygon(),  asteroid.getPolygon());
   }

   // asteroid with player
   public static boolean isShooterHittingAsteroid(Player player , Asteroid asteroid)
   {
        return isPolygonCollidingWithAnotherPolygon(player.getPolygon(), asteroid.getPolygon());
   }

   // spaceship with player
   public static boolean isSpaceshipHittingShooter(Spaceship spaceship, Player player)
   {
        return isPolygonCollidingWithAnotherPolygon(spaceship.getPolygon(), player.getPolygon());
   }
}

As seen in the code, I tried to check every possible point in one polygon, if it's in the other polygon, but still it doesn't work properly.


问:
How to Copy file ONLY NEW FILES from Google Cloud Bucket Storage using GSUTIL
I have some automate project would like to sending files from my google cloud bucket to sftp server. But to do that, everyday i must maintain the name files generated by some cloud function that i want to send.

I'm using gsutil to copy the files from bucket to my server using jenkins automation.

Is that possible to copy only NEW FILES using gsutil?

or is that any prefix or sort by date or time on gsutil to that?

Copy only new files from google cloud bucket with gsutil using sorting like date or prefix


问:
Store problematic string in a variable and then correctly reference the variable?
I use the amazing command line tool FZF

It offers the means to set its interface colours inline (Linux users get a config file, windows inline only):

```<code>Fzf --color=fg+:#00b4eb,bg+:#3d3c3c,hl:#0069fc,hl+:#0069fc --color=info:#80807e,prompt:#0069fc,pointer:#008ffc --color=marker:#008ffc,spinner:#454445,header:#353636
</code>```

As you can  see its a long line. besides I would like to build different configurations for different contexts via variables/functions , much like splatting parameters.

So I tried:

```<code>$Style = "--color=fg+:#00b4eb,bg+:#3d3c3c,hl:#0069fc,hl+:#0069fc --color=info:#80807e,prompt:#0069fc,pointer:#008ffc --color=marker:#008ffc,spinner:#454445,header:#353636"

FZF $Style
</code>```

I get this error:

```<code>invalid color specification: hl+:#0069fc --color=info:#80807e
NativeCommandExitException: Program "FZFCommandLine.exe" ended with non-zero exit code: 2.
</code>```

Even when I use a non expandable here string I get the same error:

```<code>$Conf = @'
--color=fg+:#00b4eb,bg+:#3d3c3c,hl:#0069fc,hl+:#0069fc --color=info:#80807e,prompt:#0069fc,pointer:#008ffc --color=marker:#008ffc,spinner:#454445,header:#353636
'@
</code>```

I am trying to replicate the typical literal behaviour:

```<code>FZF --color=fg+:#00b4eb,bg+:#3d3c3c,hl:#0069fc,hl+:#0069fc --color=info:#80807e,prompt:#0069fc,pointer:#008ffc --color=marker:#008ffc,spinner:#454445,header:#353636
</code>```

The part after Fzf is the part  giving me trouble.

Body:
I use the amazing command line tool FZF

It offers the means to set its interface colours inline (Linux users get a config file, windows inline only):

Fzf --color=fg+:#00b4eb,bg+:#3d3c3c,hl:#0069fc,hl+:#0069fc --color=info:#80807e,prompt:#0069fc,pointer:#008ffc --color=marker:#008ffc,spinner:#454445,header:#353636

As you can  see its a long line. besides I would like to build different configurations for different contexts via variables/functions , much like splatting parameters.

So I tried:

$Style = "--color=fg+:#00b4eb,bg+:#3d3c3c,hl:#0069fc,hl+:#0069fc --color=info:#80807e,prompt:#0069fc,pointer:#008ffc --color=marker:#008ffc,spinner:#454445,header:#353636"

FZF $Style

I get this error:

invalid color specification: hl+:#0069fc --color=info:#80807e
NativeCommandExitException: Program "FZFCommandLine.exe" ended with non-zero exit code: 2.

Even when I use a non expandable here string I get the same error:

$Conf = @'
--color=fg+:#00b4eb,bg+:#3d3c3c,hl:#0069fc,hl+:#0069fc --color=info:#80807e,prompt:#0069fc,pointer:#008ffc --color=marker:#008ffc,spinner:#454445,header:#353636
'@

I am trying to replicate the typical literal behaviour:

FZF --color=fg+:#00b4eb,bg+:#3d3c3c,hl:#0069fc,hl+:#0069fc --color=info:#80807e,prompt:#0069fc,pointer:#008ffc --color=marker:#008ffc,spinner:#454445,header:#353636

The part after Fzf is the part  giving me trouble.


问:
dropdown list options are not rendering properly for agGridReact
Grid for reference

I was trying to add dynamic dropdown for 'beneficiaryBankAccount' column based on the value of 'ReceivedFrom' column i.e. in every row for same column 'beneficiaryBankAccount' the dropdown list will be different.

sometimes after selecting the 'ReceivedFrom' column data values for 'beneficiaryBankAccount' column are not rendering properly.

this is how I am setting columnDef:

this is how I am rendering option List for 'beneficiaryBankAccount' after selecting value of 'ReceivedFrom' column.

```<code>result =[{ accountNumber: "NA", bankName: "NA", bankLocation:"NA", swiftCode:"NA"}];
          const {costcenter,cdoptions, subEntry,bankoptions, bankDetails }=this.state;
this.setState({
    bankDetails:result,
    columnDefs: ColumnDef.map((data) => {
                  if (data.field === "bankDetails")
                {
                return {
                    ...data,
                    cellRendererParams: {
                    entryoptions: result
                    .map((option) => `${option.accountNumber}-${option.bankName}`),
                    width: data.width,
                    },};
                }
                return data;
                })
                })
</code>```

based on values of 'ReceivedFrom' column data of last column is getting called.

usually dropdown list is getting rendered but sometimes list is not coming!
don't know where things are going wrong.

Body:
Grid for reference

I was trying to add dynamic dropdown for 'beneficiaryBankAccount' column based on the value of 'ReceivedFrom' column i.e. in every row for same column 'beneficiaryBankAccount' the dropdown list will be different.

sometimes after selecting the 'ReceivedFrom' column data values for 'beneficiaryBankAccount' column are not rendering properly.

this is how I am setting columnDef:

this is how I am rendering option List for 'beneficiaryBankAccount' after selecting value of 'ReceivedFrom' column.

result =[{ accountNumber: "NA", bankName: "NA", bankLocation:"NA", swiftCode:"NA"}];
          const {costcenter,cdoptions, subEntry,bankoptions, bankDetails }=this.state;
this.setState({
    bankDetails:result,
    columnDefs: ColumnDef.map((data) => {
                  if (data.field === "bankDetails")
                {
                return {
                    ...data,
                    cellRendererParams: {
                    entryoptions: result
                    .map((option) => `${option.accountNumber}-${option.bankName}`),
                    width: data.width,
                    },};
                }
                return data;
                })
                })

based on values of 'ReceivedFrom' column data of last column is getting called.

usually dropdown list is getting rendered but sometimes list is not coming!
don't know where things are going wrong.


问:
How do I change the dock name in macOS programmatically?
This Is Not A Duplicate, As Previous Questions On Stackoverflow Are Extremely Outdated And They Don't Work

I want to change the name of the application in the dock to make it feel more like macos.
I was reading this post and I couldn't get it to work. instead, it just appeared with the name "java"

I would like to do this within the java program itself so that whenever the user double-clicks on the jar file, it should launch with the dock name and icon. I have successfully changed the icon with java.awt.TaskBar and also the menu bar, but I couldn't do it dock name. How do I do this?

Java Details:

```<code>$ java --version
openjdk 19.0.1 2022-10-18
OpenJDK Runtime Environment (build 19.0.1+10-21)
OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)
$ javac --version
javac 19.0.1
</code>```

Body:
This Is Not A Duplicate, As Previous Questions On Stackoverflow Are Extremely Outdated And They Don't Work

I want to change the name of the application in the dock to make it feel more like macos.
I was reading this post and I couldn't get it to work. instead, it just appeared with the name "java"

I would like to do this within the java program itself so that whenever the user double-clicks on the jar file, it should launch with the dock name and icon. I have successfully changed the icon with java.awt.TaskBar and also the menu bar, but I couldn't do it dock name. How do I do this?

Java Details:

$ java --version
openjdk 19.0.1 2022-10-18
OpenJDK Runtime Environment (build 19.0.1+10-21)
OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)
$ javac --version
javac 19.0.1


问:
Termination of the current state of the function with any other user actions outside of the running function (FSM) Aiogram
The problem occurs when another function is called from the button. When a certain state is triggered in which the bot reproduces the menu, if the user presses any other button on the playback keyboard, the state ends, but does not issue a new action requested by the user. In order for this action to work, the user must once again click on the button that he wants to activate. I hope the problem is clear. (At the moment of the running state, in order for the user to open another menu, it must be called twice. the first time - completes the state, the second time - starts a new function. Need an idea how to solve this problem)

poster = ['any url', 'any url', 'any url']
name = ['test1', 'test2', 'test3']

storage = MemoryStorage()
bot = Bot(TOKEN)
dp = Dispatcher(bot=bot,
                storage=storage)

class Test(StatesGroup):
    Q1 = State()

next_button = InlineKeyboardButton(text='next', callback_data='next')
back_button = InlineKeyboardButton(text='back', callback_data='back')

nbtn_callback = [next_button.callback_data, back_button.callback_data]

nbtn = InlineKeyboardMarkup(row_width=True)
nbtn_next = InlineKeyboardMarkup(row_width=True)
nbtn_next.add(next_button)
nbtn.row(back_button, next_button)

a = KeyboardButton('cancel')
b = KeyboardButton('Photo')

menu = ReplyKeyboardMarkup(resize_keyboard=True)
menu.row(a, b)

@dp.message_handler(commands=['start'])
async def start_bot(message: types.Message):
    txt = "Hello!\n"
    await message.answer(txt, reply_markup=menu)
    await message.delete()

@dp.message_handler(text='Photo', state=None)
async def photo(message: types.Message):
    reply_markup = nbtn_next
    await Test.Q1.set()
    await bot.send_photo(
        message.chat.id,
        photo=poster[0],
        reply_markup=reply_markup,
        caption=name[0],
    )

@dp.message_handler(text='cancel', state=None)
async def cancel(message: types.Message):
    ph = "any url photo"
    await bot.send_photo(chat_id=message.chat.id,
                         photo=ph)

@dp.callback_query_handler(state=Test.Q1)
async def photo_update(callback: types.CallbackQuery, state: FSMContext):
    if callback.data == "next":
        i = await state.get_data()
        i = i.get("answer")

        if i is None:
            i = 1
        else:
            i += 1
        file_path = poster[i]
        await state.update_data(
            {"answer": poster.index(file_path)}
        )
        file = InputMedia(media=file_path, caption=name[i])
        await callback.message.edit_media(file, reply_markup=nbtn)

@dp.message_handler(content_types=types.ContentType.TEXT, state=Test.Q1)
async def stop_state(message: types.Message, state: FSMContext):
    await state.finish()
```
<p>As you can see this part of the code is for the completion of the state, but due to this design, a new action is required for it to work</p>
<pre class="lang-py prettyprint-override"><code>@dp.message_handler(content_types=types.ContentType.TEXT, state=Test.Q1)
async def stop_state(message: types.Message, state: FSMContext):
    await state.finish()
</code>```

Body:
The problem occurs when another function is called from the button. When a certain state is triggered in which the bot reproduces the menu, if the user presses any other button on the playback keyboard, the state ends, but does not issue a new action requested by the user. In order for this action to work, the user must once again click on the button that he wants to activate. I hope the problem is clear. (At the moment of the running state, in order for the user to open another menu, it must be called twice. the first time - completes the state, the second time - starts a new function. Need an idea how to solve this problem)

poster = ['any url', 'any url', 'any url']
name = ['test1', 'test2', 'test3']

storage = MemoryStorage()
bot = Bot(TOKEN)
dp = Dispatcher(bot=bot,
                storage=storage)

class Test(StatesGroup):
    Q1 = State()

next_button = InlineKeyboardButton(text='next', callback_data='next')
back_button = InlineKeyboardButton(text='back', callback_data='back')

nbtn_callback = [next_button.callback_data, back_button.callback_data]

nbtn = InlineKeyboardMarkup(row_width=True)
nbtn_next = InlineKeyboardMarkup(row_width=True)
nbtn_next.add(next_button)
nbtn.row(back_button, next_button)

a = KeyboardButton('cancel')
b = KeyboardButton('Photo')

menu = ReplyKeyboardMarkup(resize_keyboard=True)
menu.row(a, b)

@dp.message_handler(commands=['start'])
async def start_bot(message: types.Message):
    txt = "Hello!\n"
    await message.answer(txt, reply_markup=menu)
    await message.delete()

@dp.message_handler(text='Photo', state=None)
async def photo(message: types.Message):
    reply_markup = nbtn_next
    await Test.Q1.set()
    await bot.send_photo(
        message.chat.id,
        photo=poster[0],
        reply_markup=reply_markup,
        caption=name[0],
    )

@dp.message_handler(text='cancel', state=None)
async def cancel(message: types.Message):
    ph = "any url photo"
    await bot.send_photo(chat_id=message.chat.id,
                         photo=ph)

@dp.callback_query_handler(state=Test.Q1)
async def photo_update(callback: types.CallbackQuery, state: FSMContext):
    if callback.data == "next":
        i = await state.get_data()
        i = i.get("answer")

        if i is None:
            i = 1
        else:
            i += 1
        file_path = poster[i]
        await state.update_data(
            {"answer": poster.index(file_path)}
        )
        file = InputMedia(media=file_path, caption=name[i])
        await callback.message.edit_media(file, reply_markup=nbtn)

@dp.message_handler(content_types=types.ContentType.TEXT, state=Test.Q1)
async def stop_state(message: types.Message, state: FSMContext):
    await state.finish()

As you can see this part of the code is for the completion of the state, but due to this design, a new action is required for it to work

@dp.message_handler(content_types=types.ContentType.TEXT, state=Test.Q1)
async def stop_state(message: types.Message, state: FSMContext):
    await state.finish()


问:
Conflicting arguments to generic parameter 'Self' when using opaque type
I'm playing a bit with opaque types in Swift, and I have one concern. This code:

```<code>func makeInt() -> some Equatable {
   Int.random(in: 1...10)
}

let a = makeInt()
let b = makeInt()
</code>```

works fine, while this one:

```<code>let a: some Equatable = 1
let b: some Equatable = 2

print("\(a == b)")
</code>```

causes build error: error: conflicting arguments to generic parameter 'Self' ('some Equatable' (result type of 'a') vs. 'some Equatable' (result type of 'b'))

Why it's so?

Body:
I'm playing a bit with opaque types in Swift, and I have one concern. This code:

func makeInt() -> some Equatable {
   Int.random(in: 1...10)
}

let a = makeInt()
let b = makeInt()

works fine, while this one:

let a: some Equatable = 1
let b: some Equatable = 2

print("\(a == b)")

causes build error: error: conflicting arguments to generic parameter 'Self' ('some Equatable' (result type of 'a') vs. 'some Equatable' (result type of 'b'))

Why it's so?


问:
Using the URLconf defined in wiki.urls, Django tried these URL patterns, in this order:
this question was asked before but i cant find the solution to this.

When i run server i get this:enter image description here

here is my code:
** helo\urls.py:**

```<code>from django.urls import path
    from . import views

    urlpatterns = [
      path('', views.index, name='index')
    ]
</code>```

helo\views.py:

```<code>from django.shortcuts import render
    from django.http import HttpResponse

    def index(request):
      return HttpResponse("Hello")

</code>```

** wiki\urls.py:**

```<code> from django.contrib import admin
    from django.urls import include,path

    urlpatterns = [
      path('admin/', admin.site.urls),
      path('helo/', include("helo.urls")),
    ]
</code>```

and i did put 'helo' in INSTALLED_APPS

Why do i get this error?

Body:
this question was asked before but i cant find the solution to this.

When i run server i get this:enter image description here

here is my code:
** helo\urls.py:**

from django.urls import path
    from . import views

    urlpatterns = [
      path('', views.index, name='index')
    ]

helo\views.py:

from django.shortcuts import render
    from django.http import HttpResponse

    def index(request):
      return HttpResponse("Hello")

** wiki\urls.py:**

 from django.contrib import admin
    from django.urls import include,path

    urlpatterns = [
      path('admin/', admin.site.urls),
      path('helo/', include("helo.urls")),
    ]

and i did put 'helo' in INSTALLED_APPS

Why do i get this error?


问:
getBoundingClientRect() not updating properly
I am trying to build an e commerce app using nodeJs. In the frontend, I am trying to add an image zoom functionality when hovered over product images. I have 3 different images of the same product. Everything works fine on the first image. But when I click on the second image, the values of imageRect.width and imageRect.height does not change. Hence it messes up my zoom. But when I click on it once more everything works fine. I am really puzzled.
Here is my EJS code

```<code><div class="d-flex justify-content-center p-5">
        <div class="img-cont">
          <img id="main-image" class="product-main-image" src="/<%= sku.images[0] %> " alt="">
          <div class="lens"></div>
          <div class="result"></div>
        </div>
      </div>
      <div class="d-flex px-5 justify-content-center">
        <div class="col-2 d-flex justify-content-center mx-3">
          <div class="card product-alt-card p-2" id="image1" onclick="changeImage(this.id)">
            <img class="product-alt-images" src="/<%= sku.images[0] %> " alt="">
          </div>
        </div>
        <div class="col-2 d-flex justify-content-center mx-3">
          <div class="card product-alt-card p-2" id="image2" onclick="changeImage(this.id)">
            <img class="product-alt-images" src="/<%= sku.images[1] %> " alt="">
          </div>
        </div>
        <div class="col-2 d-flex justify-content-center mx-3">
          <div class="card product-alt-card p-2" id="image3" onclick="changeImage(this.id)">
            <img class="product-alt-images" src="/<%= sku.images[2] %> " alt="">
          </div>
        </div>
      </div>
</code>```

Here is my CSS

```<code>.img-cont{
  position: relative;
}
.lens{
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background-color: rgba(31, 180, 255, 0.3);
  visibility: hidden;
}
.result{
  position: absolute;
  left: calc(100% + 10rem);
  top: 5rem;
  width: 300px;
  height: 300px;
  background-repeat: no-repeat;
  visibility: hidden;
  transition: transform 0.1s;
  z-index: 99;
}
</code>```

Here is my JS code

```<code>
let container = document.querySelector('.img-cont')
let image = document.querySelector('#main-image')
let lens = document.querySelector('.lens')
let result = document.querySelector('.result')

let containerRect = container.getBoundingClientRect()
let imageRect = image.getBoundingClientRect()
let lensRect = lens.getBoundingClientRect()
let resultRect = result.getBoundingClientRect()

result.style.backgroundImage = `url(${image.src})`

//for changing the image of the product

function changeImage(id) {
  console.log(imageRect.width)
  console.log(imageRect.height)

  const newImage = document.querySelector(`#${id} img`).src
  console.log(image)
  const mainImage = document.querySelector('#main-image')
  mainImage.src = newImage

  container = document.querySelector('.img-cont')
  image = document.querySelector('#main-image')

  containerRect = container.getBoundingClientRect()
  imageRect = image.getBoundingClientRect()

  result.style.backgroundImage = `url(${image.src})`

  console.log(imageRect.width)
  console.log(imageRect.height)
}

//code to zoom on hover

container.addEventListener('mousemove', zoomImage)

function zoomImage(e) {
  const{x,y} = getMousePos(e)

  lens.style.left = x + 'px'
  lens.style.top = y + 'px'

  let fx = resultRect.width/lensRect.width
  let fy = resultRect.height/lensRect.height

  result.style.backgroundSize = `${imageRect.width * fx}px ${imageRect.height*fy}px`
  result.style.backgroundPosition = `-${x*fx}px -${y*fy}px`
}

function getMousePos(e) {
  let x = e.clientX - containerRect.left - lensRect.width/2
  let y = e.clientY - containerRect.top - lensRect.height/2

  let minX = 0
  let minY = 0
  let maxX = containerRect.width - lensRect.width
  let maxY = containerRect.height - lensRect.height

  if(x <= minX){
    x = minX
  } else if (x >= maxX){
    x = maxX
  }
  if(y <= minY){
    y = minY
  } else if (y >= maxY){
    y = maxY
  }
  return {x, y}
}

container.addEventListener('mouseenter', showZoom)

function showZoom() {
  lens.style.visibility = 'visible'
  result.style.visibility = 'visible'
  result.style.transform = 'scale(1.5)'
}

container.addEventListener('mouseleave', hideZoom)

function hideZoom() {
  lens.style.visibility = 'hidden'
  result.style.visibility = 'hidden'
  result.style.transform = 'scale(0.5)'
}
</code>```

I rewrote the entire getBoundingClientRect() code within the changeImage function so that it updates when the image is changed. But it is only updating when I invoke the function twice

Body:
I am trying to build an e commerce app using nodeJs. In the frontend, I am trying to add an image zoom functionality when hovered over product images. I have 3 different images of the same product. Everything works fine on the first image. But when I click on the second image, the values of imageRect.width and imageRect.height does not change. Hence it messes up my zoom. But when I click on it once more everything works fine. I am really puzzled.
Here is my EJS code

          <img id="main-image" class="product-main-image" src="/<%= sku.images[0] %> " alt="">

            <img class="product-alt-images" src="/<%= sku.images[0] %> " alt="">

            <img class="product-alt-images" src="/<%= sku.images[1] %> " alt="">

            <img class="product-alt-images" src="/<%= sku.images[2] %> " alt="">

Here is my CSS

.img-cont{
  position: relative;
}
.lens{
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background-color: rgba(31, 180, 255, 0.3);
  visibility: hidden;
}
.result{
  position: absolute;
  left: calc(100% + 10rem);
  top: 5rem;
  width: 300px;
  height: 300px;
  background-repeat: no-repeat;
  visibility: hidden;
  transition: transform 0.1s;
  z-index: 99;
}

Here is my JS code

let container = document.querySelector('.img-cont')
let image = document.querySelector('#main-image')
let lens = document.querySelector('.lens')
let result = document.querySelector('.result')

let containerRect = container.getBoundingClientRect()
let imageRect = image.getBoundingClientRect()
let lensRect = lens.getBoundingClientRect()
let resultRect = result.getBoundingClientRect()

result.style.backgroundImage = `url(${image.src})`

//for changing the image of the product

function changeImage(id) {
  console.log(imageRect.width)
  console.log(imageRect.height)

  const newImage = document.querySelector(`#${id} img`).src
  console.log(image)
  const mainImage = document.querySelector('#main-image')
  mainImage.src = newImage

  container = document.querySelector('.img-cont')
  image = document.querySelector('#main-image')

  containerRect = container.getBoundingClientRect()
  imageRect = image.getBoundingClientRect()

  result.style.backgroundImage = `url(${image.src})`

  console.log(imageRect.width)
  console.log(imageRect.height)
}

//code to zoom on hover

container.addEventListener('mousemove', zoomImage)

function zoomImage(e) {
  const{x,y} = getMousePos(e)

  lens.style.left = x + 'px'
  lens.style.top = y + 'px'

  let fx = resultRect.width/lensRect.width
  let fy = resultRect.height/lensRect.height

  result.style.backgroundSize = `${imageRect.width * fx}px ${imageRect.height*fy}px`
  result.style.backgroundPosition = `-${x*fx}px -${y*fy}px`
}

function getMousePos(e) {
  let x = e.clientX - containerRect.left - lensRect.width/2
  let y = e.clientY - containerRect.top - lensRect.height/2

  let minX = 0
  let minY = 0
  let maxX = containerRect.width - lensRect.width
  let maxY = containerRect.height - lensRect.height

  if(x <= minX){
    x = minX
  } else if (x >= maxX){
    x = maxX
  }
  if(y <= minY){
    y = minY
  } else if (y >= maxY){
    y = maxY
  }
  return {x, y}
}

container.addEventListener('mouseenter', showZoom)

function showZoom() {
  lens.style.visibility = 'visible'
  result.style.visibility = 'visible'
  result.style.transform = 'scale(1.5)'
}

container.addEventListener('mouseleave', hideZoom)

function hideZoom() {
  lens.style.visibility = 'hidden'
  result.style.visibility = 'hidden'
  result.style.transform = 'scale(0.5)'
}

I rewrote the entire getBoundingClientRect() code within the changeImage function so that it updates when the image is changed. But it is only updating when I invoke the function twice


问:
Android Java code to mimic a 2 Keystroke sequence (to perform a device screenshot)
I have been trying to get a bitmap screenshot of a SurfaceView for days but the more I look into it, there doesn't seem to be a solution at present for Android OS 2.3.4 based OSs my device from HTC.

So on to Plan B, where I just found out another blog: "On my HTC Evo 3d, all I have to do is hold the power button for 1-2 sec and then hit the home button and it takes a screen shot. No app required."  Turns out this works perfectly on my tablet.

I also know from digging around there are these intents: android.intent.action.SCREEN_OFF & android.intent.category.HOME

(So I tried a bunch of code experiments to try to mimic the 2-key combo in code to get a screenshot in this brute force manor.  Unfortunately without success).

So my ? -- Does anyone have any insights into a method to invoke this 'screenshot sequence' for my HTC device from java code?  (Presume I need to fool the OS into thinking I am holding down the power key AND tap the Home key, simultaneously)...

More: Here is a snip of the code I am attempting:

Button click for test... ...

```<code>  Thread t = new Thread() {
    public void run() {
      Instrumentation inst = new Instrumentation();
      inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POWER);
      Instrumentation inst2 = new Instrumentation();
      inst2.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
    } // run
  }; // thread t
</code>```

Doesnt work as the inst.sendKeyDownUpSync is wrong as I need a sendKeyDown (& hold) behavior or its equivel

Many thanks for any advise.  If I do get this working, I will post the solution here.  Cheers GH

PS;  I presume there is some custom intent under the hood doing this?  Is there a system log somewhere to trey to peek at the call tree to find out what it is ?

EDIT (MORE)... 9/24/11

More. Still not working but I am heading down this path & think it is closer...

// Attempt to SIMULATE A Long press (DOWN) + HOME to tell the HTC to invoke the 'Screenshot' command (WARNING: HTC Tablet specific behavior!)

```<code>        Thread tt = new Thread() {
        public void run() {
          final KeyEvent dapowerkey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POWER);

          Handler onesecondhandler = new Handler();
          onesecondhandler.postDelayed(new Runnable() {
            public void run() {
              // fpr about 1 second send power down keystrokes (DOWN ONLY)
              while (true) { dispatchKeyEvent(dapowerkey); }
            }  // we are done running on the timer past time point
          }, 750);  // 3/4 second key press
          // send the HOME keystroke
          Instrumentation inst1 = new Instrumentation();
          inst1.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
        } // outer thread run tp mpt block the GUI
      }; // outer thread t
      tt.start();
      ...
</code>```

Also thought if I can send the right intent directly to the proper place on the device that I might be able to kick off a screen capture function directly (which is what I really want.  Through some log examinations (when you Long-Power + Home click on HTC) a program called 'com.htc.mysketcher' (FlashActivity) is being called...

Again, if I figure this out then I will post to the group... Cheers GH

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to get a bitmap screenshot of a SurfaceView for days but the more I look into it, there doesn't seem to be a solution at present for Android OS 2.3.4 based OSs my device from HTC.

So on to Plan B, where I just found out another blog: "On my HTC Evo 3d, all I have to do is hold the power button for 1-2 sec and then hit the home button and it takes a screen shot. No app required."  Turns out this works perfectly on my tablet.

I also know from digging around there are these intents: android.intent.action.SCREEN_OFF & android.intent.category.HOME

(So I tried a bunch of code experiments to try to mimic the 2-key combo in code to get a screenshot in this brute force manor.  Unfortunately without success).

So my ? -- Does anyone have any insights into a method to invoke this 'screenshot sequence' for my HTC device from java code?  (Presume I need to fool the OS into thinking I am holding down the power key AND tap the Home key, simultaneously)...

More: Here is a snip of the code I am attempting:

Button click for test... ...

  Thread t = new Thread() {
    public void run() {
      Instrumentation inst = new Instrumentation();
      inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POWER);
      Instrumentation inst2 = new Instrumentation();
      inst2.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
    } // run
  }; // thread t

Doesnt work as the inst.sendKeyDownUpSync is wrong as I need a sendKeyDown (& hold) behavior or its equivel

Many thanks for any advise.  If I do get this working, I will post the solution here.  Cheers GH

PS;  I presume there is some custom intent under the hood doing this?  Is there a system log somewhere to trey to peek at the call tree to find out what it is ?

EDIT (MORE)... 9/24/11

More. Still not working but I am heading down this path & think it is closer...

// Attempt to SIMULATE A Long press (DOWN) + HOME to tell the HTC to invoke the 'Screenshot' command (WARNING: HTC Tablet specific behavior!)

        Thread tt = new Thread() {
        public void run() {
          final KeyEvent dapowerkey = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_POWER);

          Handler onesecondhandler = new Handler();
          onesecondhandler.postDelayed(new Runnable() {
            public void run() {
              // fpr about 1 second send power down keystrokes (DOWN ONLY)
              while (true) { dispatchKeyEvent(dapowerkey); }
            }  // we are done running on the timer past time point
          }, 750);  // 3/4 second key press
          // send the HOME keystroke
          Instrumentation inst1 = new Instrumentation();
          inst1.sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);
        } // outer thread run tp mpt block the GUI
      }; // outer thread t
      tt.start();
      ...

Also thought if I can send the right intent directly to the proper place on the device that I might be able to kick off a screen capture function directly (which is what I really want.  Through some log examinations (when you Long-Power + Home click on HTC) a program called 'com.htc.mysketcher' (FlashActivity) is being called...

Again, if I figure this out then I will post to the group... Cheers GH


问:
javascript inside storybook
So my file extension is .mdx and I'm not sure if it allows me to include js code inside the .mdx file. I tried having it in the preview tag but it prints it as a string.

Below I have tried to write js code in a separate js file, import the function in the .mdx file, and use it, but it still won't work.

I also tried writing the inline function directly to the button onclick but had no luck.

Code:

```<code><Preview>
 <div>
  <button onclick="onClickHandler">Click</button>
 </div>
</Preview>
</code>```

Is there a way to include a small js code in mdx file.

Title: javascript inside storybook

Body:
So my file extension is .mdx and I'm not sure if it allows me to include js code inside the .mdx file. I tried having it in the preview tag but it prints it as a string.

Below I have tried to write js code in a separate js file, import the function in the .mdx file, and use it, but it still won't work.

I also tried writing the inline function directly to the button onclick but had no luck.

Code:

<Preview>

  <button onclick="onClickHandler">Click</button>

</Preview>

Is there a way to include a small js code in mdx file.


问:
Request to Cassandra with a condition on a column that is not a Primary Key works in DBeaver but doesn't work in Python
My query has a WHERE on a column that is not a primary key.

SELECT * FROM table WHERE id_order IN ('2177579','2177130','2177072')

The query works fine in DBeaver, but when using the Cassandra library in Python:

from cassandra.cluster import Cluster string = '''SELECT * FROM table WHERE id_order IN ('2177579','2177130','2177072')''' session.execute(string)

I am getting an exception:

InvalidRequest: Error from server: code=2200 [Invalid query] message="IN predicates on non-primary-key columns (id_order) is not yet supported"

Any help would be highly appreciated


问:
Chart.js: ERROR "horizontalBar" is not a registered controller
seeing the below console error

ERROR "horizontalBar" is not a registered controller.

The version of chart.js used is:
"chart.js": "^4.0.1"

can you please let me know how to get rid of this


问:
Opening a file from SafariWebExtensionHandler
I'm developing a Safari Web Extension. Among other things it has to open files on the user's disc (in their corresponding apps, like "Preview" app for png file and so on) when user clicks a browser contextual menu item.

But if I try to do something like this (for testing purposes):

```<code>class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {

   func beginRequest(with context: NSExtensionContext) {
         NSWorkspace.shared.open(URL(fileURLWithPath: "/Users/username/Downloads/banner.png"))
   }

}
</code>```

I get the following error:

The application “(null)” does not have permission to open “banner.png.”

Which is weird, because this works fine:

```<code>NSWorkspace.shared.selectFile("/Users/username/Downloads/banner.png", inFileViewerRootedAtPath: "/Users/username/Downloads")
</code>```

Will be grateful for any suggestions

I tried calling shell script to open the file, but it doesn't work either.

Body:
I'm developing a Safari Web Extension. Among other things it has to open files on the user's disc (in their corresponding apps, like "Preview" app for png file and so on) when user clicks a browser contextual menu item.

But if I try to do something like this (for testing purposes):

class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {

   func beginRequest(with context: NSExtensionContext) {
         NSWorkspace.shared.open(URL(fileURLWithPath: "/Users/username/Downloads/banner.png"))
   }

}

I get the following error:

The application “(null)” does not have permission to open “banner.png.”

Which is weird, because this works fine:

NSWorkspace.shared.selectFile("/Users/username/Downloads/banner.png", inFileViewerRootedAtPath: "/Users/username/Downloads")

Will be grateful for any suggestions

I tried calling shell script to open the file, but it doesn't work either.


问:
elastic/search-ui - How to change facet view? Filter by id but display by label
Similar question was raised on discuss.elastic.co.

Given I have some documents in my elasticsearch index with a tag field.

```<code>{
...
tag:[
    {
      "id":"1",
      "label":{
        "en":"dog",
        "ger":"Hund"
    },
    {
      "id":"2",
      "label":{
        "en":"cat",
        "de":"Katze"
      }
    }
]
...
}
</code>```

I´d like to build a frontend with elastic/search-ui and provide a facet for the tag field
so that the actual filtering is applied on basis of the id subfield.

Within the framework this can be achieved by providing a simple configuration within the configuration object.

```<code>let searchConfig: SearchDriverOptions = {
  ...
  searchQuery:{
    ...
    facets:{
      "tag.id":{type:"value",size:"5"}
    }
  }
}
</code>```

While this works like expected it is only half of the solution.

What I want to achieve in a next step is to display the content of tag.label.en within the ui instead of the values of tag.id.

In the end the filtering should be done on basis of tag.id but in the UI the corresponding value of tag.label.en should be shown.

Is there a simple way to achieve this in elastic/search-ui?

Body:
Similar question was raised on discuss.elastic.co.

Given I have some documents in my elasticsearch index with a tag field.

{
...
tag:[
    {
      "id":"1",
      "label":{
        "en":"dog",
        "ger":"Hund"
    },
    {
      "id":"2",
      "label":{
        "en":"cat",
        "de":"Katze"
      }
    }
]
...
}

I´d like to build a frontend with elastic/search-ui and provide a facet for the tag field
so that the actual filtering is applied on basis of the id subfield.

Within the framework this can be achieved by providing a simple configuration within the configuration object.

let searchConfig: SearchDriverOptions = {
  ...
  searchQuery:{
    ...
    facets:{
      "tag.id":{type:"value",size:"5"}
    }
  }
}

While this works like expected it is only half of the solution.

What I want to achieve in a next step is to display the content of tag.label.en within the ui instead of the values of tag.id.

In the end the filtering should be done on basis of tag.id but in the UI the corresponding value of tag.label.en should be shown.

Is there a simple way to achieve this in elastic/search-ui?


问:
Comparing signed integers in ARM assembly using CMP
`   MIN         RN  R1
COUNTER     RN  R2
P1          RN  R0

```<code>                AREA mycode, CODE, READONLY
                ENTRY
                EXPORT __main

__main
            LDR     P1, =RAND_DATA
            MOV     MIN, #100
            MOV     COUNTER, #6

LOOP
            LDRSB   R3, [P1]
            ;ADD    P1, P1, #1
            CMP     MIN, R3
            BLO     UPDATE_VALUES
            MOV     MIN, R3

UPDATE_VALUES
            ;UPDATE VALUES
            ADD     P1, P1, #1  ; update pointer
            SUBS    COUNTER, #1 ; update counter
            BNE     LOOP        ; loop again or end

STOP
            B       STOP

RAND_DATA       DCB     +12,-10,+24,+35,-11,-2
                ALIGN
            END`
</code>```

When CMP instruction runs with +12 and -10, my code Branches out by BLO indicating +12 < -10?
What am I doing wrong?

I'm trying to compare signed numbers to get the min value using simple loop. But,
when CMP instruction runs with +12 and -10, my code Branches out by BLO indicating +12 < -10?
What am I doing wrong?

Body:
`   MIN         RN  R1
COUNTER     RN  R2
P1          RN  R0

                AREA mycode, CODE, READONLY
                ENTRY
                EXPORT __main

__main
            LDR     P1, =RAND_DATA
            MOV     MIN, #100
            MOV     COUNTER, #6

LOOP
            LDRSB   R3, [P1]
            ;ADD    P1, P1, #1
            CMP     MIN, R3
            BLO     UPDATE_VALUES
            MOV     MIN, R3

UPDATE_VALUES
            ;UPDATE VALUES
            ADD     P1, P1, #1  ; update pointer
            SUBS    COUNTER, #1 ; update counter
            BNE     LOOP        ; loop again or end

STOP
            B       STOP

RAND_DATA       DCB     +12,-10,+24,+35,-11,-2
                ALIGN
            END`

When CMP instruction runs with +12 and -10, my code Branches out by BLO indicating +12 < -10?
What am I doing wrong?

I'm trying to compare signed numbers to get the min value using simple loop. But,
when CMP instruction runs with +12 and -10, my code Branches out by BLO indicating +12 < -10?
What am I doing wrong?


问:
Calling a API twice on same page fails second time in WordPress
Code working fine in codepen but while trying to run in WordPress page using shortcode it's not running. What could be the reason. All of the remaining content below this code are also not showing. Especially while trying to run js in page nothing showing.</p>
```<code>  <script>
    // Fetch the exchange rates from the API
    fetch(`https://api.fastforex.io/fetch-multi?from=AED&to=USD,EUR,GBP,INR,AUD,CAD,SGD,CHF,MYR,JPY&api_key=xxxxx-xxx-xxx`)// API key on purpose
      .then(response => response.json())
      .then(data => {
        // Update the exchange rates in the table
        document.getElementById("eur").innerHTML = data.results.EUR;
document.getElementById("gbp").innerHTML = data.results.GBP;
document.getElementById("chf").innerHTML = data.results.CHF;
document.getElementById("eur").innerHTML = data.results.EUR;
document.getElementById("gbp").innerHTML = data.results.GBP;
document.getElementById("chf").innerHTML = data.results.CHF;
document.getElementById("usd").innerHTML = data.results.USD;
document.getElementById("inr").innerHTML = data.results.INR;
document.getElementById("aud").innerHTML = data.results.AUD;
document.getElementById("cad").innerHTML = data.results.CAD;
document.getElementById("sgd").innerHTML = data.results.SGD;
document.getElementById("myr").innerHTML = data.results.MYR;
document.getElementById("jpy").innerHTML = data.results.JPY;

      });
  </script>
</body>
</code>```


问:
Google Cloud Composer (Airflow) - Scalability issues
I'm facing some issues on my Cloud Composer instance resulting in failed tasks.

Details of instance configuration :

Composer image : composer-2.0.29-airflow-2.3.3 / Airflow version : 2.3.3

Airflow.cfg :

parallelism = 32 / dag_concurrency = 100 / worker_concurrency = 24

In terms of resources :

I have 60 DAGs which can contains up to 55 tasks that needs to run in parallel.
They don't do any compute, only some light PythonOperator/GCSOperator/BigQueryOperator.

I often encounter this type of errors :

```<code>*** Log file is not found: gs://xxx/xxx/attempt=2.log.
*** The task might not have been executed or worker executing it might have finished abnormally (e.g. was evicted).
*** Please, refer to https://cloud.google.com/composer/docs/how-to/using/troubleshooting-dags#common_issues hints to learn what might be possible reasons for a missing log.
</code>```

All of my tasks have 3 retries but when it happens for a reason it stops at 2 retries and send a failure error. I don't understand why. Example of error in mail sent :

```<code>Try 2 out of 3
Exception:
Executor reports task instance finished (failed) although the task says its queued. (Info: None) Was the task killed externally?
</code>```

I also receives random zombie tasks Detected as zombie

My metrics are the following :

When I clear the task, it succeeds as it should.
(I don't have access to GKE but if it helps I can ask to have access)

Any advice to prevent this errors and understand what happens ?

Body:
I'm facing some issues on my Cloud Composer instance resulting in failed tasks.

Details of instance configuration :

Composer image : composer-2.0.29-airflow-2.3.3 / Airflow version : 2.3.3

Airflow.cfg :

parallelism = 32 / dag_concurrency = 100 / worker_concurrency = 24

In terms of resources :

I have 60 DAGs which can contains up to 55 tasks that needs to run in parallel.
They don't do any compute, only some light PythonOperator/GCSOperator/BigQueryOperator.

I often encounter this type of errors :

*** Log file is not found: gs://xxx/xxx/attempt=2.log.
*** The task might not have been executed or worker executing it might have finished abnormally (e.g. was evicted).
*** Please, refer to https://cloud.google.com/composer/docs/how-to/using/troubleshooting-dags#common_issues hints to learn what might be possible reasons for a missing log.

All of my tasks have 3 retries but when it happens for a reason it stops at 2 retries and send a failure error. I don't understand why. Example of error in mail sent :

Try 2 out of 3
Exception:
Executor reports task instance finished (failed) although the task says its queued. (Info: None) Was the task killed externally?

I also receives random zombie tasks Detected as zombie

My metrics are the following :

When I clear the task, it succeeds as it should.
(I don't have access to GKE but if it helps I can ask to have access)

Any advice to prevent this errors and understand what happens ?


问:
Sendkeys envia apenas 1 caracter da palavra escolhida
Estou tentando enviar um texto para um elemento html no WhatsappWeb, este elemento é o campo onde o usuário digita sua mensagem. Porém, quando eu tento adicionar um texto a este campo usando o método "send_keys" o campo só recebe o primeiro caracter da minha palavra enviada.
EX: palavra = "ola"
area_texto.send_keys(palavra)
campo de mensagem do WhatsApp recebe: "o"

Meu código:

mensagem = driver.find_element(
By.XPATH, "///html/body/div[1]/div/div/div[4]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]"
)

```<code>   area_msg = driver.find_element(
        By.XPATH, "//div[@title='Mensagem']"conversation-compose-box-input
    )
    if(mensagem.text == "1"):
        area_msg.click()
        area_msg.clear()
        area_msg.send_keys("Esse é o teste numero 1?")
        area_msg.send_keys(Keys.RETURN)
</code>```

Body:
Estou tentando enviar um texto para um elemento html no WhatsappWeb, este elemento é o campo onde o usuário digita sua mensagem. Porém, quando eu tento adicionar um texto a este campo usando o método "send_keys" o campo só recebe o primeiro caracter da minha palavra enviada.
EX: palavra = "ola"
area_texto.send_keys(palavra)
campo de mensagem do WhatsApp recebe: "o"

Meu código:

mensagem = driver.find_element(
By.XPATH, "///html/body/div[1]/div/div/div[4]/div/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]"
)

   area_msg = driver.find_element(
        By.XPATH, "//div[@title='Mensagem']"conversation-compose-box-input
    )
    if(mensagem.text == "1"):
        area_msg.click()
        area_msg.clear()
        area_msg.send_keys("Esse é o teste numero 1?")
        area_msg.send_keys(Keys.RETURN)


问:
What is an ideal place for creating GCP Private Service Connect Endpoint, Publish Service etc. in case of "Shared VPC" setup?
I understand GCP Private Service Connect (PSC) is an effective solution for enabling service-centric private network connectivity for GCP APIs and other hosted services within and across VPC projects/organizations/on-prem setup based on Producer/Consumer project model.

GCP documentation on Private Service Connect explains the purpose, PSC Endpoint and Publish Service configuration however I don't find relevant details on what should be an ideal location (or best practice) for creating and configuring PSC Endpoint, Publish Service when you have Shared VPC based network setup.

IMO, PSC Endpoint & Publish Service are network resources so the ideal place is to create in 'Host Project' of Shared VPC Network as a 'Host Project' is meant for centralized network management.

Also, having PSC Endpoint and Publish Service in 'Host Project' will help in sharing a single 'PSC endpoint' for all the 'Service Project' resources (which otherwise require multiple PSC endpoints per Service Project). However I would like to understand from you if you have come across and/or implemented such scenario.

Update: I tried a Shared VPC setup wherein PSC creation is allowed in Service-Project which means GCP doesn't restrict the creation of PSC in Service-Project.

Host Project:

Service Project:

Service Project PSC setup:


问:
MongoDB/Mongoose populate when using multiple DBs
i'm using multiple dbs with mongoose and i have schema that references another schema on same db (like on db1).

```<code>import mongoose from 'mongoose';

const { ObjectId } = mongoose.Schema.Types;
const salitaSchema = new mongoose.Schema(
  {
    idstabile: { type: ObjectId, ref: 'Stabile', required: true }, //Schema stabile is on DB1
    phonenumbers: [{ type: String, trim: true }],
    softdelete: { type: Boolean, default: false },
    authorizationids: [{ type: Number, default: null }],
  },

  { timestamps: true }
);
const db1= mongoose.connection.useDb('pluto');
export = db1.model('Salite', salitaSchema);
</code>```

Now i want to populate Stabile but it doesn't work.

I have also created Stabile schema liike this:

```<code>const db1= mongoose.connection.useDb('pluto');

export = db1.model('Stabile', stabileSchema);
</code>```

What i am getting is this :

```<code>Internal server error. Cannot populate path `\"idstabile\"` because it is not in your schema. Set the `strictPopulate` option to false to override.
</code>```

But with strictPopulate to false it doesn't work

Body:
i'm using multiple dbs with mongoose and i have schema that references another schema on same db (like on db1).

import mongoose from 'mongoose';

const { ObjectId } = mongoose.Schema.Types;
const salitaSchema = new mongoose.Schema(
  {
    idstabile: { type: ObjectId, ref: 'Stabile', required: true }, //Schema stabile is on DB1
    phonenumbers: [{ type: String, trim: true }],
    softdelete: { type: Boolean, default: false },
    authorizationids: [{ type: Number, default: null }],
  },

  { timestamps: true }
);
const db1= mongoose.connection.useDb('pluto');
export = db1.model('Salite', salitaSchema);

Now i want to populate Stabile but it doesn't work.

I have also created Stabile schema liike this:

const db1= mongoose.connection.useDb('pluto');

export = db1.model('Stabile', stabileSchema);

What i am getting is this :

Internal server error. Cannot populate path `\"idstabile\"` because it is not in your schema. Set the `strictPopulate` option to false to override.

But with strictPopulate to false it doesn't work


问:
loading reference package.json ( connect ECONNERFUSED )
when I installed tailwind, at first thre were 3 problem (unknown @tailwind rule) I fixed these problem by installing  postcss extention but after that . one problem created that is (Problems loading reference 'https://json.schemastore.org/package': Unable to load schema from 'https://json.schemastore.org/package': connect ECONNREFUSED 127.0.0.1:58221.) . how can fix this problem ?

I try to fix this problem untill start my tailwind project without any problem


问:
Using pytest and requests.request in dependency-injector
I have

file1.py

```<code>def _request_token(self):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    data = {
        'id': self.id,
    }
    response = requests.request(
        method="POST",
        url=self.url,
        headers=headers,
        data=data
    )
    self.token_json = response.json()
</code>```

test_token.py

```<code>def test_request_token(test_token):
    with patch('mod1.file1.requests.request') as mock_request:
        mock_request.return_value = json.loads('{"response": "returned_data"}')
        res = test_token._request_token()

    assert res.token_json == {"response": "returned_data"}
</code>```

conftest.py

```<code>@pytest.fixture(scope="session")
def test_token(test_container):
    return test_container.token_mgr(id="abc")

@pytest.fixture(scope="session")
def test_container():
    test_container = initialize(test_yaml_dir)
    return test_container
</code>```

I'm using dependency-injectors, and the traceback I currently see:

```<code>AttributeError: 'dict' object has no attribute 'json'
</code>```

Do I need to fully mock a response, using a different method?

Body:
I have

file1.py

def _request_token(self):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    data = {
        'id': self.id,
    }
    response = requests.request(
        method="POST",
        url=self.url,
        headers=headers,
        data=data
    )
    self.token_json = response.json()

test_token.py

def test_request_token(test_token):
    with patch('mod1.file1.requests.request') as mock_request:
        mock_request.return_value = json.loads('{"response": "returned_data"}')
        res = test_token._request_token()

    assert res.token_json == {"response": "returned_data"}

conftest.py

@pytest.fixture(scope="session")
def test_token(test_container):
    return test_container.token_mgr(id="abc")

@pytest.fixture(scope="session")
def test_container():
    test_container = initialize(test_yaml_dir)
    return test_container

I'm using dependency-injectors, and the traceback I currently see:

AttributeError: 'dict' object has no attribute 'json'

Do I need to fully mock a response, using a different method?


问:
How do I get the contents of a Selenium Webelement in Javascript?
I've got a Selenium Webdriver on node.js and Firefox. I want to find and retrieve the outerHTML contents of a set of elements, but I'm failing at it.

Here's my code:

```<code>    let Elements = await driver.findElements(By.xpath('//img'));

    Elements.forEach(function(Element){
        console.log(Element);
    });
</code>```

This produces a set of objects like:

WebElement {
driver_: Driver {
session_: Promise { [Session] },
executor_: Executor { customCommands_: [Map], log_: [Logger], w3c: true },
fileDetector_: null,
onQuit_: [Function: onQuit]
},
id_: Promise { 'b4519d34-d176-47e2-acf0-07d868e89a4e' }
}

I've also tried:

```<code>    for(let Element of Elements) {
        text = await Element.innerHTML;
        console.log("Element: " + Element + " - Text:" + text);
    }
</code>```

This gives me the results:

Element: [object Object] - Text:undefined

And I've tried:

```<code>    Elements = promise.fullyResolved(Elements);

    console.log("Fullyresolved: " + Elements);

    Elements.forEach(function(Element){
        let text = Element.getAttribute("innerHTML");
        console.log("Fullyresolved: " + text);
    });
</code>```

Which gives me:

Fullyresolved: [object Promise]

and a crash that Elements.forEach is not a function.

Any help appreciated!

TIA!

Body:
I've got a Selenium Webdriver on node.js and Firefox. I want to find and retrieve the outerHTML contents of a set of elements, but I'm failing at it.

Here's my code:

    let Elements = await driver.findElements(By.xpath('//img'));

    Elements.forEach(function(Element){
        console.log(Element);
    });

This produces a set of objects like:

WebElement {
driver_: Driver {
session_: Promise { [Session] },
executor_: Executor { customCommands_: [Map], log_: [Logger], w3c: true },
fileDetector_: null,
onQuit_: [Function: onQuit]
},
id_: Promise { 'b4519d34-d176-47e2-acf0-07d868e89a4e' }
}

I've also tried:

    for(let Element of Elements) {
        text = await Element.innerHTML;
        console.log("Element: " + Element + " - Text:" + text);
    }

This gives me the results:

Element: [object Object] - Text:undefined

And I've tried:

    Elements = promise.fullyResolved(Elements);

    console.log("Fullyresolved: " + Elements);

    Elements.forEach(function(Element){
        let text = Element.getAttribute("innerHTML");
        console.log("Fullyresolved: " + text);
    });

Which gives me:

Fullyresolved: [object Promise]

and a crash that Elements.forEach is not a function.

Any help appreciated!

TIA!


问:
Send Client Certificate and Private Key to Server with SSL
I have been working on Windows application in C#, which will act as TCP client and communicate with server. Tool has to send Certificate and Private key to Server, once the server authentication is successful there will a handshake at TLS level.

I used SSL stream class to send certificate, but on server end it does shows that the certificate.
But once I make connection, server log the client connection.

I am so new to this, Can someone help through the process and examples.

Thanks in advance.


问:
How can receive an ADFS bearer token in C# without user log in
This is sorta driving me crazy. We got a Web API that takes a JWT bearer token received via ADFS. Now I have to write a Windows Service that communicates with the API but to do that, I need that JWT token.

I tried looking on the internet but none of the solutions work. Lots of examples use the WSTrustChannelFactory but none of them show how to specify a Client ID for the ADFS application or other relevant information.

Another example is MSAL.NET which supposedly supports ADFS. But all the examples and documentation are about Azure AD, but we have an on-premise AD. Some examples also point to example code that no longer exists on GitHub.

I managed to get a token with the ConfidentialClientApplication from MSAL.NET but it‘s not working, the API says it‘s invalid. And it seems it uses response_type code, rather than id_token which I need, and there apparently is no way to change that.

Other than these two, I can‘t find anything at all about this subject.

So: How can I receive an ADFS JWT bearer token with C# from a Windows Service application using the current user context, rather than requiring a manual username and password entry?

Any pointers would be greatly appreciated.


问:
the difference of const initializer for global and local variable in C
I'm not sure why the error happened. However, in the following line the code is OK when compiling.

Does someone have any explanation?

```<code>#include <stdio.h>
int g_value = 10;
const int* p1 = &g_value;
const int* p2 = p1; // error: initializer element is not constant
int main()
{
    const int* p3 = &g_value;
    const int* p4 = p3; // Compile normally without any error!

    return 0;
}
</code>```

Body:
I'm not sure why the error happened. However, in the following line the code is OK when compiling.

Does someone have any explanation?

#include <stdio.h>
int g_value = 10;
const int* p1 = &g_value;
const int* p2 = p1; // error: initializer element is not constant
int main()
{
    const int* p3 = &g_value;
    const int* p4 = p3; // Compile normally without any error!

    return 0;
}


问:
How to calculate AIC from a maxnet model in R
I would like to perform an AIC on a maxnet model.

I run a model using maxnet package in R and I want to perform an AIC on this model.

I tried to use the SDMtune package in R but the class of the maxnet output does not correspond to the class requested by the SDMtune package.

I am not very familiar with the output so it would be great also if AIC can be calculated manually from the maxnet model output.

Example:

```<code>library(maxnet)
data("bradypus")

mod <- maxnet(p=bradypus$presence, data = bradypus[-1],
              regmult =1:3,  # to adjust regularization
              classes = "q")
mod

# apply here AIC or BIC
....
</code>```

Body:
I would like to perform an AIC on a maxnet model.

I run a model using maxnet package in R and I want to perform an AIC on this model.

I tried to use the SDMtune package in R but the class of the maxnet output does not correspond to the class requested by the SDMtune package.

I am not very familiar with the output so it would be great also if AIC can be calculated manually from the maxnet model output.

Example:

library(maxnet)
data("bradypus")

mod <- maxnet(p=bradypus$presence, data = bradypus[-1],
              regmult =1:3,  # to adjust regularization
              classes = "q")
mod

# apply here AIC or BIC
....


问:
file-saver library does not get mocked by jest
I'm testing with jest a custom hook that downloads n files and creates a zip. On promise resolution, I call FileSaver.saveAs() method to open the file explorer so the user can choose where to save it.
This is the test in question:

```<code>test(
  'should return zip with selected files',
  async () => {
    jest.mock('file-saver')
    const mockStorageGet = () => {
      return fetch('http://localhost/download')
        .then((res) => res.blob())
        .then((data) => {
          return {Body: data}
        })
    }
    Storage.get = jest.fn().mockImplementation(mockStorageGet)
    toast.done = jest.fn()
    const storageSpy = jest.spyOn(Storage, 'get')
    const toastDoneSpy = jest.spyOn(toast, 'done')
    const {result} = renderHook(() => useFileTable(dummyData.mockSelectedFiles), {wrapper: Wrapper})
    await act(async () => result.current.onDownload())
    expect(storageSpy).toHaveBeenCalledTimes(2)
    expect(toastDoneSpy).toHaveBeenCalled()
  }
)
</code>```

My last attempt was to follow jest's documentation about manually mocking a node module https://jestjs.io/docs/27.x/manual-mocks but it is still executing the actual code

Things I tried:

1.

```<code>jest.mock('file-saver', () => ({
  FileSaver: {
    saveAs: jest.fn()
  }
}))
</code>```

```<code>import FileSaver from 'file-saver'
test('', () => {
  FileSaver.saveAs = jest.fn().mockImplementation(() => {})
})

//throws error: saveAs is readOnly
</code>```

follow jest's documentation about manually mocking a node module https://jestjs.io/docs/27.x/manual-mocks

Body:
I'm testing with jest a custom hook that downloads n files and creates a zip. On promise resolution, I call FileSaver.saveAs() method to open the file explorer so the user can choose where to save it.
This is the test in question:

test(
  'should return zip with selected files',
  async () => {
    jest.mock('file-saver')
    const mockStorageGet = () => {
      return fetch('http://localhost/download')
        .then((res) => res.blob())
        .then((data) => {
          return {Body: data}
        })
    }
    Storage.get = jest.fn().mockImplementation(mockStorageGet)
    toast.done = jest.fn()
    const storageSpy = jest.spyOn(Storage, 'get')
    const toastDoneSpy = jest.spyOn(toast, 'done')
    const {result} = renderHook(() => useFileTable(dummyData.mockSelectedFiles), {wrapper: Wrapper})
    await act(async () => result.current.onDownload())
    expect(storageSpy).toHaveBeenCalledTimes(2)
    expect(toastDoneSpy).toHaveBeenCalled()
  }
)

My last attempt was to follow jest's documentation about manually mocking a node module https://jestjs.io/docs/27.x/manual-mocks but it is still executing the actual code

Things I tried:

1.

jest.mock('file-saver', () => ({
  FileSaver: {
    saveAs: jest.fn()
  }
}))

import FileSaver from 'file-saver'
test('', () => {
  FileSaver.saveAs = jest.fn().mockImplementation(() => {})
})

//throws error: saveAs is readOnly

follow jest's documentation about manually mocking a node module https://jestjs.io/docs/27.x/manual-mocks


问:
Praat TextGrid reviewer script cannot be run repeatedly
I am relatively new to Praat and am currently using a Praat script to open all sound files and related textgrids in a directory, make changes on each textgrid and then saving the textgrid in the end.
This worked fine when I ran the script for the first time but I could not run it another time, neither on the same directory (containing files that had been reviewed before + files that had not been reviewed), nor on a different directory (containing files that had not been reviewed with this script previously at any point in time).

I am not getting any error. When I try to run the script now, the Praat information window opens and informs me that all files in the respective directory have been reviewed.

It might be important to note that I interrupted the script in the first run (thinking that I could simply take a note on where I stopped and work on the rest of the files later on).
I would be glad about some help here! Any ideas?

Here is the script I am using:

```<code>## text grid reviewer.praat
## Originally created by the excellent Katherine Crosswhite
## Script modified by Mark Antoniou
## MARCS Auditory Laboratories C 2010

##  This script opens all the sound files in a given directory, plus
##  their associated textgrids so that you can review/change the
##  boundaries or labels.

form Enter directory and search string
# Be sure not to forget the slash (Windows: backslash, OSX: forward
# slash)  at the end of the directory name.
    sentence Directory C:/Users/Hansen/Desktop/annotate_latency/03_1_cond/
#  Leaving the "Word" field blank will open all sound files in a
#  directory. By specifying a Word, you can open only those files
#  that begin with a particular sequence of characters. For example,
#  you may wish to only open tokens produced by speaker 02 in context C01
#  then you enter 02_C01.

    sentence Word
    sentence Filetype WAV
endform

Create Strings as file list... list 'directory$'*'filetype$'
number_of_files = Get number of strings
for x from 1 to number_of_files
     select Strings list
     current_file$ = Get string... x
     Read from file... 'directory$''current_file$'
     object_name$ = selected$ ("Sound")
     Read from file... 'directory$''object_name$'.TextGrid
     plus Sound 'object_name$'
     Edit
     pause  Make any changes on file 'object_name$' then click Continue.
     minus Sound 'object_name$'
     Write to text file... 'directory$''object_name$'.TextGrid
     select all
     minus Strings list
     Remove
endfor

select Strings list
Remove
clearinfo
printline TextGrids have been reviewed for 'word$'.'filetype$' files in
printline 'directory$'.

## written by Katherine Crosswhite
## crosswhi@ling.rochester.edu

</code>```

I first thought that Praat simply cannot re-review files that have been reviewed previously and tried to re-run the script on only those files I had not reviewed before. The issue kept occurring.
Then I tried running the script on an entirely different directory, with the same result.

I tried clearing up the Praat history (assuming that this might be any kind of traceback error).
I also tried including the clearinfo command in the beginning of the script.
Nothing of that made any difference.

To sum up, I played around a bit but could not find out why Praat thinks that all files have been reviewed already.

Body:
I am relatively new to Praat and am currently using a Praat script to open all sound files and related textgrids in a directory, make changes on each textgrid and then saving the textgrid in the end.
This worked fine when I ran the script for the first time but I could not run it another time, neither on the same directory (containing files that had been reviewed before + files that had not been reviewed), nor on a different directory (containing files that had not been reviewed with this script previously at any point in time).

I am not getting any error. When I try to run the script now, the Praat information window opens and informs me that all files in the respective directory have been reviewed.

It might be important to note that I interrupted the script in the first run (thinking that I could simply take a note on where I stopped and work on the rest of the files later on).
I would be glad about some help here! Any ideas?

Here is the script I am using:

## text grid reviewer.praat
## Originally created by the excellent Katherine Crosswhite
## Script modified by Mark Antoniou
## MARCS Auditory Laboratories C 2010

##  This script opens all the sound files in a given directory, plus
##  their associated textgrids so that you can review/change the
##  boundaries or labels.

form Enter directory and search string
# Be sure not to forget the slash (Windows: backslash, OSX: forward
# slash)  at the end of the directory name.
    sentence Directory C:/Users/Hansen/Desktop/annotate_latency/03_1_cond/
#  Leaving the "Word" field blank will open all sound files in a
#  directory. By specifying a Word, you can open only those files
#  that begin with a particular sequence of characters. For example,
#  you may wish to only open tokens produced by speaker 02 in context C01
#  then you enter 02_C01.

    sentence Word
    sentence Filetype WAV
endform

Create Strings as file list... list 'directory$'*'filetype$'
number_of_files = Get number of strings
for x from 1 to number_of_files
     select Strings list
     current_file$ = Get string... x
     Read from file... 'directory$''current_file$'
     object_name$ = selected$ ("Sound")
     Read from file... 'directory$''object_name$'.TextGrid
     plus Sound 'object_name$'
     Edit
     pause  Make any changes on file 'object_name$' then click Continue.
     minus Sound 'object_name$'
     Write to text file... 'directory$''object_name$'.TextGrid
     select all
     minus Strings list
     Remove
endfor

select Strings list
Remove
clearinfo
printline TextGrids have been reviewed for 'word$'.'filetype$' files in
printline 'directory$'.

## written by Katherine Crosswhite
## crosswhi@ling.rochester.edu

I first thought that Praat simply cannot re-review files that have been reviewed previously and tried to re-run the script on only those files I had not reviewed before. The issue kept occurring.
Then I tried running the script on an entirely different directory, with the same result.

I tried clearing up the Praat history (assuming that this might be any kind of traceback error).
I also tried including the clearinfo command in the beginning of the script.
Nothing of that made any difference.

To sum up, I played around a bit but could not find out why Praat thinks that all files have been reviewed already.