问:
Have anybody taken screenshot of BlueStacks running in background successfully like fraps?
I am writing an assist tool for a game running in BlueStacks. I want to take screenshot when BlueStacks running in background(not minimized). Normal GDI ways will get black image. I find it loads ddraw.dll and opengl32.dll, and I successfully hooked these two libraries, but the main entrance functions like glBegin or DirectDrawCreate, DirectDrawCreateEx are not called. So I can not take its back buffer.
But fraps works fine. Does anybody know why? </p>

答: Try using ADB to grab a screenshot. Using a windows screenshot tool does not consider the size of the bluestacks window. Using ADB gives a native resolution screenshot regardless of the size of the bluestacks window. It will even work with the bluestacks window minimized.</p>


来源: stackexchange

问:
Binary tree in Java implementation
My task is to implement a Binary Tree in Java and do some operations on the tree e.g adding elements or showing the minimum or maximum element of the tree. I am having trouble solving this so if anyone could help I'd appreciate it. All the methods and variables we can use are already in the class so we have to use only those. My code so far is the following:

/**
 * A binary tree with int values.
 */
class Tree {

    /**
     * The value of this node in the tree.
     */
    private int node;

    /**
     * The left subtree.
     */
    private Tree lhs;

    /**
     * The right subtree.
     */
    private Tree rhs;

    /**
     * Creates a new tree with the value node.
     * @param node The value of this node in the tree.
     */
    public Tree(int node) {
        this.node = node;
        this.lhs = null;
        this.rhs = null;

    }

    /**
     * Method to add a node to the tree. Duplicates will be refused.
     *
     * @param insert the new number
    */
    public void add(int insert) {

    }

    /**
     * Method to calculate the depth of a tree. It is defined by the maximal
     * number of edges to a leaf.
     *
     * @return the depth of the tree
    */
    public int depth(Tree tree) {
    // Root being null means tree doesn't exist.
    if (tree == null) {
        return 0;
    }

    // Get the depth of the left and right subtree
    // using recursion.
    int leftDepth = depth(tree.lhs);
    int rightDepth = depth(tree.rhs);

    // Choose the larger one and add the root to it.
    if (leftDepth > rightDepth) {
        return (leftDepth + 1);
    }
    else {
        return (rightDepth + 1);
}

    }

    /**
     * Method to find a number in the tree.
     *
     * @param wanted the wanted number
     * @return true, if the wanted number exists in the try, else false
    */
    public boolean exists(int wanted) {

    }

    /**
     * Method to find the smallest number in the tree.
     *
     * @return the smallest number in the tree
    */
    public int smallest( int min) {
        while (Tree.lhs != null) {
            Tree.lhs + 1;
        }
            minimum = Tree.lhs
            return min;

    }

    /**
     * Method to find the biggest number in the tree.
     *
     * @return the biggest number in the tree
    */
    public int biggest(int max) {
    while(Tree.rhs != nil) {
        Tree.rhs++;
    }
    return max;

    }

    /**
     * Method to check whether a tree is degenerate.
     *
     * @return true if every node has either no or one child node, else false
    */
    public boolean isDegenerate() {

    }

    /**
     * Method that formats the tree into a readable string.
     *
     * @return the formatted string
    */
    public String toString() {

    }
}
```
<p>And this is the main class its suppose the work with:</p>
<pre class="lang-java prettyprint-override"><code>class Main {

    public static void main(String[] args) {

        Tree tree = new Tree(15);

        int[] set1 = {15, 21, 8, 41, 8, 5, 41, 33};
        int[] set2 = {18, 45, 36, 19, 3, 24, 19, 10};

        for (int i = 0; i < set1.length; i++) {
            tree.add(set1[i]);
        }

        System.out.println(tree.toString());
        System.out.println("The depth of the tree is " + tree.depth() + ".");
        System.out.println("Does the number 8 exist in the tree? " + tree.exists(8));
        System.out.println("Does the number 24 exist in the tree? " + tree.exists(24));
        System.out.println(tree.smallest() + " is the smallest number in the tree. ");
        System.out.println(tree.biggest() + " is the biggest number in the tree. ");
        System.out.println("Is the tree degenerate? " + tree.isDegenerate());

        for (int i = 0; i < set2.length; i++) {
            tree.add(set2[i]);
        }

        System.out.println(tree.toString());
        System.out.println("The depth of the tree is " + tree.depth() + ".");
        System.out.println("Does the number 8 exist in the tree? " + tree.exists(8));
        System.out.println("Does the number 24 exist in the tree? " + tree.exists(24));
        System.out.println(tree.smallest() + " is the smallest number in the tree. ");
        System.out.println(tree.biggest() + " is the biggest number in the tree. ");
        System.out.println("Is the tree degenerate? " + tree.isDegenerate());

    }
}

</code>```

答:
I assume this is a binary tree (not a binary search tree).  First, you need to define your Tree class and Node class correctly.  I'm giving to give you the code for the Tree and the Node class plus the add method. The add method add level by level. From there, you can work on completing the rest of the methods.</p>
```<code>import java.util.*;
class Tree {
   private static class Node{
      int data;
      Node left, right;
      Node(int data){
         this.data=data;
      }
   }
   private Node root;
   public void add(int data){
      Node n = new Node(data);
      if (root == null){
        root = n; return;
      }
      Queue<Node> queue = new LinkedList<>();
      queue.add(root);
      while(!queue.isEmpty()){
         Node t = queue.remove();
         if (t.left == null) {
            t.left = n; break;
         }
         else if (t.right == null) {
            t.right = n; break;
         }
         else {
            queue.add(t.left); queue.add(t.right);
         }
      }
   }
}

</code>```

ContentLicense: CC BY-SA 4.0

Title: Binary tree in Java implementation

Body:
My task is to implement a Binary Tree in Java and do some operations on the tree e.g adding elements or showing the minimum or maximum element of the tree. I am having trouble solving this so if anyone could help I'd appreciate it. All the methods and variables we can use are already in the class so we have to use only those. My code so far is the following:

/**
 * A binary tree with int values.
 */
class Tree {

    /**
     * The value of this node in the tree.
     */
    private int node;

    /**
     * The left subtree.
     */
    private Tree lhs;

    /**
     * The right subtree.
     */
    private Tree rhs;

    /**
     * Creates a new tree with the value node.
     * @param node The value of this node in the tree.
     */
    public Tree(int node) {
        this.node = node;
        this.lhs = null;
        this.rhs = null;

    }

    /**
     * Method to add a node to the tree. Duplicates will be refused.
     *
     * @param insert the new number
    */
    public void add(int insert) {

    }

    /**
     * Method to calculate the depth of a tree. It is defined by the maximal
     * number of edges to a leaf.
     *
     * @return the depth of the tree
    */
    public int depth(Tree tree) {
    // Root being null means tree doesn't exist.
    if (tree == null) {
        return 0;
    }

    // Get the depth of the left and right subtree
    // using recursion.
    int leftDepth = depth(tree.lhs);
    int rightDepth = depth(tree.rhs);

    // Choose the larger one and add the root to it.
    if (leftDepth > rightDepth) {
        return (leftDepth + 1);
    }
    else {
        return (rightDepth + 1);
}

    }

    /**
     * Method to find a number in the tree.
     *
     * @param wanted the wanted number
     * @return true, if the wanted number exists in the try, else false
    */
    public boolean exists(int wanted) {

    }

    /**
     * Method to find the smallest number in the tree.
     *
     * @return the smallest number in the tree
    */
    public int smallest( int min) {
        while (Tree.lhs != null) {
            Tree.lhs + 1;
        }
            minimum = Tree.lhs
            return min;

    }

    /**
     * Method to find the biggest number in the tree.
     *
     * @return the biggest number in the tree
    */
    public int biggest(int max) {
    while(Tree.rhs != nil) {
        Tree.rhs++;
    }
    return max;

    }

    /**
     * Method to check whether a tree is degenerate.
     *
     * @return true if every node has either no or one child node, else false
    */
    public boolean isDegenerate() {

    }

    /**
     * Method that formats the tree into a readable string.
     *
     * @return the formatted string
    */
    public String toString() {

    }
}

And this is the main class its suppose the work with:

class Main {

    public static void main(String[] args) {

        Tree tree = new Tree(15);

        int[] set1 = {15, 21, 8, 41, 8, 5, 41, 33};
        int[] set2 = {18, 45, 36, 19, 3, 24, 19, 10};

        for (int i = 0; i < set1.length; i++) {
            tree.add(set1[i]);
        }

        System.out.println(tree.toString());
        System.out.println("The depth of the tree is " + tree.depth() + ".");
        System.out.println("Does the number 8 exist in the tree? " + tree.exists(8));
        System.out.println("Does the number 24 exist in the tree? " + tree.exists(24));
        System.out.println(tree.smallest() + " is the smallest number in the tree. ");
        System.out.println(tree.biggest() + " is the biggest number in the tree. ");
        System.out.println("Is the tree degenerate? " + tree.isDegenerate());

        for (int i = 0; i < set2.length; i++) {
            tree.add(set2[i]);
        }

        System.out.println(tree.toString());
        System.out.println("The depth of the tree is " + tree.depth() + ".");
        System.out.println("Does the number 8 exist in the tree? " + tree.exists(8));
        System.out.println("Does the number 24 exist in the tree? " + tree.exists(24));
        System.out.println(tree.smallest() + " is the smallest number in the tree. ");
        System.out.println(tree.biggest() + " is the biggest number in the tree. ");
        System.out.println("Is the tree degenerate? " + tree.isDegenerate());

    }
}

Body:
I assume this is a binary tree (not a binary search tree).  First, you need to define your Tree class and Node class correctly.  I'm giving to give you the code for the Tree and the Node class plus the add method. The add method add level by level. From there, you can work on completing the rest of the methods.

import java.util.*;
class Tree {
   private static class Node{
      int data;
      Node left, right;
      Node(int data){
         this.data=data;
      }
   }
   private Node root;
   public void add(int data){
      Node n = new Node(data);
      if (root == null){
        root = n; return;
      }
      Queue<Node> queue = new LinkedList<>();
      queue.add(root);
      while(!queue.isEmpty()){
         Node t = queue.remove();
         if (t.left == null) {
            t.left = n; break;
         }
         else if (t.right == null) {
            t.right = n; break;
         }
         else {
            queue.add(t.left); queue.add(t.right);
         }
      }
   }
}


问:
git clone error: unable to map '/mnt/v/.git/config': Operation not permitted
I'm trying to clone a git repo on a Windows mapped network drive under WSL (Windows Subsystem for Linux).
The drive is a Samba share.

Windows version: 10.0.19044
WSL: Ubuntu 20.04LTS

```<code>fstab: V: /mnt/v drvfs rw,relatime,user,umask=000 0 0

$ sudo git clone https://github.com/google/googletest.git ./xxx
Cloning into './xxx'...
error: unable to mmap '/mnt/v/xxx/.git/config': Operation not permitted
fatal: could not set 'core.filemode' to 'false'
</code>```

Permissions of /mnt/v/:

```<code>$ ls -la /mnt/v/
total 38912
drwxrwxrwx 1 root root      512 Feb  7 12:06  .
</code>```

I have also tried:

```<code>sudo mount -t drvfs '\\samba\my-drive' /mnt/Vtest/

$ git clone https://github.com/google/googletest.git ./xxx
Cloning into './xxx'...
error: chmod on /mnt/Vtest/xxx/.git/config.lock failed: Operation not permitted
fatal: could not set 'core.filemode' to 'false'
</code>```

Permissions of /mnt/Vtest:

```<code>$ ls -la .
total 38912
drwxrwxrwx 1 root root      512 Feb  7 12:06  .
</code>```

And also tried:

```<code>sudo mount -t drvfs V: /mnt/Vtest/ -o metadata

$ git clone https://github.com/google/googletest.git .
Cloning into '.'...
error: chmod on /mnt/Vtest/delete/.git/config.lock failed: Operation not permitted
fatal: could not set 'core.filemode' to 'false'
</code>```

Using sudo goes a bit further, but still fail:

```<code>$ sudo git clone https://github.com/google/googletest.git .
Cloning into '.'...
remote: Enumerating objects: 23828, done.
remote: Counting objects: 100% (286/286), done.
remote: Compressing objects: 100% (168/168), done.
fatal: Unable to create temporary file '/mnt/Vtest/delete/.git/objects/pack/tmp_pack_XXXXXX': Permission denied
fatal: index-pack failed
</code>```

I have seen:
Git init: fatal: could not set 'core.filemode' to 'false' and checked that no AV is scanning this directory.

答:
The solution I found was to upgrade to WSL2 and mount using cifs instead of drvfs:

```<code>sudo mount -t cifs -overs=3.0,mfsymlinks,username=xxxxx,uid=1000 '\\samba\xxxxx' /mnt/v
</code>```

As an aside, I am building a CMake project targetting WSL-GCC. I had issues with the CMake tools failing due to permissions errors and trying to delete apps that were still running (resource busy). I solved this by moving the CMake build files to the C: drive of the local machine under WSL, by setting 'Build root to C:....'. This also has the benefit of speeding up the build.

Body:
I'm trying to clone a git repo on a Windows mapped network drive under WSL (Windows Subsystem for Linux).
The drive is a Samba share.

Windows version: 10.0.19044
WSL: Ubuntu 20.04LTS

fstab: V: /mnt/v drvfs rw,relatime,user,umask=000 0 0

$ sudo git clone https://github.com/google/googletest.git ./xxx
Cloning into './xxx'...
error: unable to mmap '/mnt/v/xxx/.git/config': Operation not permitted
fatal: could not set 'core.filemode' to 'false'

Permissions of /mnt/v/:

$ ls -la /mnt/v/
total 38912
drwxrwxrwx 1 root root      512 Feb  7 12:06  .

I have also tried:

sudo mount -t drvfs '\\samba\my-drive' /mnt/Vtest/

$ git clone https://github.com/google/googletest.git ./xxx
Cloning into './xxx'...
error: chmod on /mnt/Vtest/xxx/.git/config.lock failed: Operation not permitted
fatal: could not set 'core.filemode' to 'false'

Permissions of /mnt/Vtest:

$ ls -la .
total 38912
drwxrwxrwx 1 root root      512 Feb  7 12:06  .

And also tried:

sudo mount -t drvfs V: /mnt/Vtest/ -o metadata

$ git clone https://github.com/google/googletest.git .
Cloning into '.'...
error: chmod on /mnt/Vtest/delete/.git/config.lock failed: Operation not permitted
fatal: could not set 'core.filemode' to 'false'

Using sudo goes a bit further, but still fail:

$ sudo git clone https://github.com/google/googletest.git .
Cloning into '.'...
remote: Enumerating objects: 23828, done.
remote: Counting objects: 100% (286/286), done.
remote: Compressing objects: 100% (168/168), done.
fatal: Unable to create temporary file '/mnt/Vtest/delete/.git/objects/pack/tmp_pack_XXXXXX': Permission denied
fatal: index-pack failed

I have seen:
Git init: fatal: could not set 'core.filemode' to 'false' and checked that no AV is scanning this directory.

Body:
The solution I found was to upgrade to WSL2 and mount using cifs instead of drvfs:

sudo mount -t cifs -overs=3.0,mfsymlinks,username=xxxxx,uid=1000 '\\samba\xxxxx' /mnt/v

As an aside, I am building a CMake project targetting WSL-GCC. I had issues with the CMake tools failing due to permissions errors and trying to delete apps that were still running (resource busy). I solved this by moving the CMake build files to the C: drive of the local machine under WSL, by setting 'Build root to C:....'. This also has the benefit of speeding up the build.


问:
Code signing Thawte problems (Netbeans or Samsung Jet S8003)
I recently bought a code signing certificate and have had successfully signed standalone java applet jar files with it.

I also have partial success signing java midlets.

But I can not get the Netbeans emulator (tried 6.9 and 7.0) or a samsung jet S8003 to recognize the certificate.

Netbeans Error

```<code>Reason: The content provider certificate issuer C=ZA;ST=Western Cape;L=Cape Town;O=Thawte Consulting cc;OU=Certification Services Division;CN=Thawte Premium Server CA;EmailAddress=premium-server@thawte.com is unknown
</code>```

Samsung jet Error

```<code>Certificate error
</code>```

Is there maybe a root certificate that i should install on these systems?
(BTW, successful on Samsung Chat 335 and numerous other Nokia phones)

Thanks

答:
The Samsung SDK 1.2.2 came to my rescue to a very limited extent.
because I managed to find the exact root certificate my Thawte certificate chains to:
Namely

Owner: C=ZA;ST=Western Cape;L=Cape Town;O=Thawte Consulting cc;OU=Certification Services Division;CN=Thawte Premium Server CA;EmailAddress=premium-server@thawte.com
  Valid from Thu Aug 01 03:00:00 EEST 1996 to Fri Jan 01 01:59:59 EET 2021
  Security Domain: identified_third_party
  State: enabled

The other certificates in  Samsung SDK 1.2.2 does not matter at all.

The neat thing about the Samsung SDK is that has a much broader range of root certificates.
Something that Netbeans does not have.

As for the Samsung jet issue, I am still battling that one, been active on the samsung development forum has brought no resolution yet.
Interestingly the Samsung s8003 has 2 root Thawte certs installed one very similar to the above.

ContentLicense: CC BY-SA 3.0

Body:
I recently bought a code signing certificate and have had successfully signed standalone java applet jar files with it.

I also have partial success signing java midlets.

But I can not get the Netbeans emulator (tried 6.9 and 7.0) or a samsung jet S8003 to recognize the certificate.

Netbeans Error

Reason: The content provider certificate issuer C=ZA;ST=Western Cape;L=Cape Town;O=Thawte Consulting cc;OU=Certification Services Division;CN=Thawte Premium Server CA;EmailAddress=premium-server@thawte.com is unknown

Samsung jet Error

Certificate error

Is there maybe a root certificate that i should install on these systems?
(BTW, successful on Samsung Chat 335 and numerous other Nokia phones)

Thanks


问:
Check interval in icinga2?
I am trying to change the check_interval time for a single domain to 5 minutes but icinga2 doesn't override it. The checks are done every 1 minute. Here is my conf.
The main domain examplemanager.com Icinga checks for 5 minutes but I want test.examplemanager.com to be checked every 7 minutes and examplemanager.com/test/admin to check every 5 minutes. how can I do that?

configuration file

lastchek details in icinga2 dashboard

答:
check_interval doesn't inherit from vars.

THis way it's vars.check_interval and not check_interval.

I always have an generic service include that does

```<code>if (service.vars.check_interval) {
  check_interval = service.vars.check_interval
}
</code>```

Title: Check interval in icinga2?

Body:
check_interval doesn't inherit from vars.

THis way it's vars.check_interval and not check_interval.

I always have an generic service include that does

if (service.vars.check_interval) {
  check_interval = service.vars.check_interval
}


问:
OpenShift pod certificate installation
I have an OpenShift PHP pod running an application and I need to authenticate a user account against an Active Directory server. The LDAP bind is failing with a certificate error

```<code>LDAP Error (authenticateUser), Cannot bind to LDAP : error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed (unable to get local issuer certificate) - ldap_bind failed
</code>```

It was suggested I need to install the AD servers certificate into the pod. The certificate has now been copied into the Git repository. I thought I may be able to use a Life Cycle Hook to install the certificate into /etc/openldap/certs/

```<code>rollingParams:
  post:
    execNewPod:
      command:
        - /bin/sh
        - '-c'
        - >-
          /usr/bin/cp
          /opt/app-root/src/certificates/certificate.pem
          /etc/openldap/certs/
      containerName: application
    failurePolicy: Ignore
</code>```

However there is a permissions error - I assume that the deployment is not running as root so the directory is not accessible.

```<code>/usr/bin/cp: cannot create regular file '/etc/openldap/certs/certificate.pem': Permission denied
</code>```

Is it possible to copy this certificate using the DeploymentConfig or is there a better way to do this?

答:
I managed to resolve this. You need to add the ldap.conf and the certificate to ConfigMaps.

```<code> oc create configmap configmap_name --from-file=filenam=path and filename
</code>```

Then you need to mount the ConfigMaps:

```<code>  volumeMounts:
        - mountPath: /etc/openldap/ldap.conf
          name: openldap-ad-config-volume
          subPath: ldap.conf
        - mountPath: /etc/openldap/certs/certificate.pem
          name: ad-certificate-volume
          subPath: certificate.pem

  volumes:
    - configMap:
        defaultMode: 292
        name: openldap-ad-config
      name: openldap-ad-config-volume
    - configMap:
        defaultMode: 292
        name: ad-certificate
      name: ad-certificate-volume
</code>```

Property subPath is used so that the rest of the contents of the directory are not excluded as mounting normally mounts the whole of the directory. Property defaultMode is used otherwise the files will be world read/write.

Title: OpenShift pod certificate installation

Body:
I have an OpenShift PHP pod running an application and I need to authenticate a user account against an Active Directory server. The LDAP bind is failing with a certificate error

LDAP Error (authenticateUser), Cannot bind to LDAP : error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed (unable to get local issuer certificate) - ldap_bind failed

It was suggested I need to install the AD servers certificate into the pod. The certificate has now been copied into the Git repository. I thought I may be able to use a Life Cycle Hook to install the certificate into /etc/openldap/certs/

rollingParams:
  post:
    execNewPod:
      command:
        - /bin/sh
        - '-c'
        - >-
          /usr/bin/cp
          /opt/app-root/src/certificates/certificate.pem
          /etc/openldap/certs/
      containerName: application
    failurePolicy: Ignore

However there is a permissions error - I assume that the deployment is not running as root so the directory is not accessible.

/usr/bin/cp: cannot create regular file '/etc/openldap/certs/certificate.pem': Permission denied

Is it possible to copy this certificate using the DeploymentConfig or is there a better way to do this?

Body:
I managed to resolve this. You need to add the ldap.conf and the certificate to ConfigMaps.

 oc create configmap configmap_name --from-file=filenam=path and filename

Then you need to mount the ConfigMaps:

  volumeMounts:
        - mountPath: /etc/openldap/ldap.conf
          name: openldap-ad-config-volume
          subPath: ldap.conf
        - mountPath: /etc/openldap/certs/certificate.pem
          name: ad-certificate-volume
          subPath: certificate.pem

  volumes:
    - configMap:
        defaultMode: 292
        name: openldap-ad-config
      name: openldap-ad-config-volume
    - configMap:
        defaultMode: 292
        name: ad-certificate
      name: ad-certificate-volume

Property subPath is used so that the rest of the contents of the directory are not excluded as mounting normally mounts the whole of the directory. Property defaultMode is used otherwise the files will be world read/write.


问:
Is there a way to create an array of an element that contains a specific CSS style?
I'm trying to capture the elements that do not contain a display type of none.

```<code>let pfCard = document.getElementsByClassName("PortfolioCard").style.display = 'block';
</code>```

This doesn't seem to be working as I believe it is attempting to modify the style type instead of retrieve it.

答:
You'd probably have to querySelectorAll(".PortfolioCard") to get an array of them, then .filter() the array looking for style.display != 'none'.

A nicer solution would be if you separate your display: none property into a small utility class like: .hide-portfolio { display: none; }, and hide them that way. Then you can search for them with querySelectorAll(".PortfolioCard:not(.hide-portfolio)");

Body:
I'm trying to capture the elements that do not contain a display type of none.

let pfCard = document.getElementsByClassName("PortfolioCard").style.display = 'block';

This doesn't seem to be working as I believe it is attempting to modify the style type instead of retrieve it.


问:
Why it is showing error ''Error: Expected a value of type Future but got one of type '-Dynamic'''
Error: Expected a value of type Future but got one of type '-Dynamic'
I don't know why it is showing this error I am new to flutter and

.plz any one here help me in solving it.. gskjbggchegegvfyuetvbyegflebgeicgbui;;ncbrgbgruibeurnuteehjkfkjfggfkjfgfjgj ff hco fco g fj gefgcefgecfgub

```<code>         This is my model page:

           // To parse this JSON data, do
          //
          //     final welcome = welcomeFromJson(jsonString);

       import 'dart:convert';

    Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));

    String welcomeToJson(Welcome data) => json.encode(data.toJson());

   class Welcome {
     Welcome({
    this.page,
    this.perPage,
    this.total,
    this.totalPages,
    this.data,
    this.support,
});

int? page;
int? perPage;
int? total;
int? totalPages;
List<Datum>? data;
Support? support;

factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
    page: json["page"],
    perPage: json["per_page"],
    total: json["total"],
    totalPages: json["total_pages"],
    data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    support: Support.fromJson(json["support"]),
);

Map<String, dynamic> toJson() => {
    "page": page,
    "per_page": perPage,
    "total": total,
    "total_pages": totalPages,
    "data": List<dynamic>.from(data!.map((x) => x.toJson())),
    "support": support!.toJson(),
};
}

 class Datum {
   Datum({
    this.id,
    this.email,
    this.firstName,
    this.lastName,
    this.avatar,
});

int? id;
String? email;
String? firstName;
String? lastName;
String? avatar;

factory Datum.fromJson(Map<String, dynamic> json) => Datum(
    id: json["id"],
    email: json["email"],
    firstName: json["first_name"],
    lastName: json["last_name"],
    avatar: json["avatar"],
);

Map<String, dynamic> toJson() => {
    "id": id,
    "email": email,
    "first_name": firstName,
    "last_name": lastName,
    "avatar": avatar,
  };
  }

  class Support {
  Support({
    this.url,
    this.text,
  });

String? url;
String? text;

factory Support.fromJson(Map<String, dynamic> json) => Support(
    url: json["url"],
    text: json["text"],
);

Map<String, dynamic> toJson() => {
    "url": url,
    "text": text,
   };
 }
</code>```

And this is my This is Profile controller page

```<code>      import 'package:api/model/profile.dart';
       import 'package:api/services/remoteservics.dart';
         import 'package:flutter/material.dart';
        import 'package:get/get.dart';

       class profilecontroller extends GetxController{

       late Future<Welcome> jsonModel;

    @override
  onInit() {
  jsonModel = profilecontroller().FechProfile();
  super.onInit();
  }

 FechProfile() async {
var profiles = await RemoteServics.FechProfile();
if(profiles!=null){
  // productList.value = profiles ;
  jsonModel= profilecontroller().FechProfile();

    }
   }
 }
</code>```

And this is my services page :

```<code> class RemoteServics{
  static var client =HttpClient();

 static Future <Map<String,dynamic>>  FechProfile() async{
 var jsonModel = null;
 var url = Uri.parse("https://reqres.in/api/users?page=2");
 http.Response response = await http.get(url);
 var jsonstring = response.body;
// print(jsonstring);
// return Welcome.fromJson(jsonDecode(response.body)[0]);
var jsonmap = json.decode(jsonstring);
// return [jsonstring].cast<Welcome>();
jsonModel = Welcome.fromJson(jsonmap);
return jsonModel;

 }
}
</code>```

答:
You had not set the return type of your function:

```<code>Future<Welcome> FechProfile() async {

</code>```

You may want to crank up your linter and compiler, this should be a compile time problem, it should never go to runtime.

That said... why isn't your compiler/linter throwing a fit here? I can see many more of those problems in your code. Make sure your compiler is up to speed, your flutter is updated and you listen to all warnings you get.

Body:
Error: Expected a value of type Future but got one of type '-Dynamic'
I don't know why it is showing this error I am new to flutter and

.plz any one here help me in solving it.. gskjbggchegegvfyuetvbyegflebgeicgbui;;ncbrgbgruibeurnuteehjkfkjfggfkjfgfjgj ff hco fco g fj gefgcefgecfgub

         This is my model page:

           // To parse this JSON data, do
          //
          //     final welcome = welcomeFromJson(jsonString);

       import 'dart:convert';

    Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));

    String welcomeToJson(Welcome data) => json.encode(data.toJson());

   class Welcome {
     Welcome({
    this.page,
    this.perPage,
    this.total,
    this.totalPages,
    this.data,
    this.support,
});

int? page;
int? perPage;
int? total;
int? totalPages;
List<Datum>? data;
Support? support;

factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
    page: json["page"],
    perPage: json["per_page"],
    total: json["total"],
    totalPages: json["total_pages"],
    data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    support: Support.fromJson(json["support"]),
);

Map<String, dynamic> toJson() => {
    "page": page,
    "per_page": perPage,
    "total": total,
    "total_pages": totalPages,
    "data": List<dynamic>.from(data!.map((x) => x.toJson())),
    "support": support!.toJson(),
};
}

 class Datum {
   Datum({
    this.id,
    this.email,
    this.firstName,
    this.lastName,
    this.avatar,
});

int? id;
String? email;
String? firstName;
String? lastName;
String? avatar;

factory Datum.fromJson(Map<String, dynamic> json) => Datum(
    id: json["id"],
    email: json["email"],
    firstName: json["first_name"],
    lastName: json["last_name"],
    avatar: json["avatar"],
);

Map<String, dynamic> toJson() => {
    "id": id,
    "email": email,
    "first_name": firstName,
    "last_name": lastName,
    "avatar": avatar,
  };
  }

  class Support {
  Support({
    this.url,
    this.text,
  });

String? url;
String? text;

factory Support.fromJson(Map<String, dynamic> json) => Support(
    url: json["url"],
    text: json["text"],
);

Map<String, dynamic> toJson() => {
    "url": url,
    "text": text,
   };
 }

And this is my This is Profile controller page

      import 'package:api/model/profile.dart';
       import 'package:api/services/remoteservics.dart';
         import 'package:flutter/material.dart';
        import 'package:get/get.dart';

       class profilecontroller extends GetxController{

       late Future<Welcome> jsonModel;

    @override
  onInit() {
  jsonModel = profilecontroller().FechProfile();
  super.onInit();
  }

 FechProfile() async {
var profiles = await RemoteServics.FechProfile();
if(profiles!=null){
  // productList.value = profiles ;
  jsonModel= profilecontroller().FechProfile();

    }
   }
 }

And this is my services page :

 class RemoteServics{
  static var client =HttpClient();

 static Future <Map<String,dynamic>>  FechProfile() async{
 var jsonModel = null;
 var url = Uri.parse("https://reqres.in/api/users?page=2");
 http.Response response = await http.get(url);
 var jsonstring = response.body;
// print(jsonstring);
// return Welcome.fromJson(jsonDecode(response.body)[0]);
var jsonmap = json.decode(jsonstring);
// return [jsonstring].cast<Welcome>();
jsonModel = Welcome.fromJson(jsonmap);
return jsonModel;

 }
}

Body:
You had not set the return type of your function:

Future<Welcome> FechProfile() async {

You may want to crank up your linter and compiler, this should be a compile time problem, it should never go to runtime.

That said... why isn't your compiler/linter throwing a fit here? I can see many more of those problems in your code. Make sure your compiler is up to speed, your flutter is updated and you listen to all warnings you get.


问:
How to cancel valueChanges in Angular and set the old value again?
I subscribed to valueChanges of a mat-selection-list to be notified when the user selects a new list item. In some cases I ask the user if he/she really wants to select the new item via a confirmation dialog. If the user clicks "No" in this dialog, I need to cancel the selection of the new item. This is how I attempted to do this:

```<code>this.createForm.controls.selectionList.valueChanges.subscribe((value: number[]) => {
  const prevValue = this.createForm.controls.selectionList.value;

  if (<condition>) {
    const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: "Do you really want to do this?",
    });

    confirmDialogRef.afterClosed().subscribe((confirmResult) => {
      if (confirmResult === true) {
        // User clicked yes, continue...
      } else {
        // User clicked no, set the previous value again...
        this.createForm.controls.selectionList.setValue(prevValue, { emitEvent: false });
      }
    });
  } else {
    // No user confirmation required, just continue...
  }
});
</code>```

Unfortunately, this does not seem to work because prevValue seems to already be the new value when I try to set it as current value. What can I do instead to set the previous value again and basically just pretend that the user never even selected a new list item to begin with? Do I really have to cache the previous value manually, or is there a better way to do this?

答:
 I think you can use the (openedChange) output event of mat-select to save the previous value when the user opens the mat-select dropdown and then use that value to restore to your previous value when the user does not confirm the change.

 <mat-select formControlName="selectionList" (openedChange)="savePreviousValue()">
```
</strike>
<p>In your <code>.ts</code> component, create a variable that stores the previous value, if by default there is any value, set it to that value, or if be default it is empty then it is <code>undefined</code></p>
<pre class="lang-js prettyprint-override"><code>//Can be set to default value wherever you fetch the data.
prevValue: any = undefined;
</code>```

Then you can use this prevValue in your valueChanges subscription.

For the first time if the user does not confirm in the dialog, the prevValue will be used to set the value back to undefined, if the user confirms the dialog, then update the prevValue with the latest value so that it can be used the next time user does not confirm the change and so on.

Body:
I subscribed to valueChanges of a mat-selection-list to be notified when the user selects a new list item. In some cases I ask the user if he/she really wants to select the new item via a confirmation dialog. If the user clicks "No" in this dialog, I need to cancel the selection of the new item. This is how I attempted to do this:

this.createForm.controls.selectionList.valueChanges.subscribe((value: number[]) => {
  const prevValue = this.createForm.controls.selectionList.value;

  if (<condition>) {
    const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: "Do you really want to do this?",
    });

    confirmDialogRef.afterClosed().subscribe((confirmResult) => {
      if (confirmResult === true) {
        // User clicked yes, continue...
      } else {
        // User clicked no, set the previous value again...
        this.createForm.controls.selectionList.setValue(prevValue, { emitEvent: false });
      }
    });
  } else {
    // No user confirmation required, just continue...
  }
});

Unfortunately, this does not seem to work because prevValue seems to already be the new value when I try to set it as current value. What can I do instead to set the previous value again and basically just pretend that the user never even selected a new list item to begin with? Do I really have to cache the previous value manually, or is there a better way to do this?

Body:
 I think you can use the (openedChange) output event of mat-select to save the previous value when the user opens the mat-select dropdown and then use that value to restore to your previous value when the user does not confirm the change.

 <mat-select formControlName="selectionList" (openedChange)="savePreviousValue()">

In your .ts component, create a variable that stores the previous value, if by default there is any value, set it to that value, or if be default it is empty then it is undefined

//Can be set to default value wherever you fetch the data.
prevValue: any = undefined;

Then you can use this prevValue in your valueChanges subscription.

For the first time if the user does not confirm in the dialog, the prevValue will be used to set the value back to undefined, if the user confirms the dialog, then update the prevValue with the latest value so that it can be used the next time user does not confirm the change and so on.


问:
Will the results of Fast CRC using PCLMULQDQ be the same as for the naive implementation without further parameters?
As far as I understand, there's multiple ways to compute CRC depending on the polynomial of course but also on whether the data is bit-reflected, the initial value, or the final xor value. Let's say the "naive" implementation doesn't work on bit-reflected data and sets these values to 0.

Now, the algorithm to compute CRC for generic polynomials using PCLMULQDQ as described in https://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf doesn't do all that as well, so I was wondering, will the results be the same as for the naive implementation?
And if not, is there a way to check the correctness of my implementation for Fast CRC? I don't seem to find any online CRC calculators or any implementations for this specific algorithm.

答:
I converted Intel code from a github site to work with Visual Studio, added comments to the constants used for "folding" and Barrett reduction (comments are missing for some constants in the Intel source, with no explanation of how they were generated), and added a program to generate the constants. There are 6 sets of code: for 16, 32, and 64 bit non-reflected and reflected. For each of the 6 combinations, crcxxxa.asm is assembly code that uses PCLMULQDQ for folding data and to calculate the CRC for "Barrett reduction", crcxxxc.cpp is the test code and uses a table driven C++ CRC to verify the fast CRC, and crcxxxg.cpp is the code used to generate the constants used in crcxxxa.asm.

I'm using XMM registers and PCLMULQDQ, which takes two 64 bit operands and produces a 127 bit (not 128) product, since there are no carries to go into bit 127. Since it's a carryless multiply the only consequence of using it for reflected operands is the reflected product is effectively multiplied by 2, since bit 127, which is logical bit 0 for a reflected product is 0. This is taken care of by adjusting the constants.

For CRC64, the CRC polynomial and it's inverse are 65 bits. The constants in the code don't include the x^64 bit. To handle product = (A * B), where B is a 65 bit operand (stored in memory without the x^64 bit), product = (A << 64) XOR (A * (B & 0xFFFFFFFFFFFFFFFF)).

The assembly code takes an initial CRC as an input parameter, but does not include an xorout parameter. The post xor operation can be done after calling the assembly code, or the assembly code could be updated to take an xorout parameter (which would be in R9).

https://github.com/jeffareid/crc


问:
How to use `remotes::install_gitlab` to install from a branch?
I wanted to install the interp package from the "spline" branch in the Gitlab repository at https://gitlab.aau.at/agebhard/interp .  When I select that branch on the web page, the URL changes to https://gitlab.aau.at/agebhard/interp/-/tree/spline .  However, using that URL in the obvious way gives an error:

remotes::install_gitlab("agebhard/interp",
                        subdir = "-/tree/spline",
                        host = "https://gitlab.aau.at")
#> Error: Failed to install 'unknown package' from GitLab:
#>   cannot open URL 'https://gitlab.aau.at/api/v4/projects/agebhard%2Finterp/repository/files/-%2Ftree%2Fspline%2FDESCRIPTION/raw?ref=HEAD'
```

Created on 2022-02-09 by the reprex package (v2.0.1.9000)

I ended up cloning the whole repository and then using git branch to select the branch, and installing locally.  But surely remotes::install_gitlab() would offer a way to install directly from a branch?  The install_github() function has ref to select a branch or tag, but I don't see an equivalent of that argument in install_gitlab().

答:
You can use just install_git

```<code>remotes::install_git(
  url = "https://gitlab.aau.at/agebhard/interp.git",
  ref = "spline"
)
</code>```

Body:
I wanted to install the interp package from the "spline" branch in the Gitlab repository at https://gitlab.aau.at/agebhard/interp .  When I select that branch on the web page, the URL changes to https://gitlab.aau.at/agebhard/interp/-/tree/spline .  However, using that URL in the obvious way gives an error:

remotes::install_gitlab("agebhard/interp",
                        subdir = "-/tree/spline",
                        host = "https://gitlab.aau.at")
#> Error: Failed to install 'unknown package' from GitLab:
#>   cannot open URL 'https://gitlab.aau.at/api/v4/projects/agebhard%2Finterp/repository/files/-%2Ftree%2Fspline%2FDESCRIPTION/raw?ref=HEAD'

Created on 2022-02-09 by the reprex package (v2.0.1.9000)

I ended up cloning the whole repository and then using git branch to select the branch, and installing locally.  But surely remotes::install_gitlab() would offer a way to install directly from a branch?  The install_github() function has ref to select a branch or tag, but I don't see an equivalent of that argument in install_gitlab().

Body:
You can use just install_git

remotes::install_git(
  url = "https://gitlab.aau.at/agebhard/interp.git",
  ref = "spline"
)


问:
How to create translation to "timesince" value ? (template tag)
I review docs but I am lost... some problem with it:

```<code>{% load i18n %}
{% blocktrans %}
{{ wpis.entry.lastChangeDate|timesince }}
{% endblocktrans %}
</code>```

Raise:

```<code>`KeyError: u'wpis.entry.lastChangeDate | timesince'`
</code>```

Of course, without blocktrans all works fine.

So, what is simples way to translate few words? (I am interesting polish lang, minutes -> minut, hours -> godzin, etc)
I will be thankful for clear example.

EDIT:
in my .po file i have now:

```<code>#: templates/part.html:37
#, python-format
msgid ""
"\n"
"%(lastChangeDate)s\n"
msgstr ""
</code>```

and i don't see anything about var in docs... now i would do:

```<code>msgid "hours"
msgstr "godzin"
</code>```

etc and bind it to my var (above example don't work...)

答:
Simply use {{ var|timesince }} and make sure that in settings.py, LANGUAGE_CODE is set to your locale and that USE_I18N is True.

You don't need to use blocktrans or have custom translations in a .po file for this, it's already included.

ContentLicense: CC BY-SA 2.5

Body:
I review docs but I am lost... some problem with it:

{% load i18n %}
{% blocktrans %}
{{ wpis.entry.lastChangeDate|timesince }}
{% endblocktrans %}

Raise:

`KeyError: u'wpis.entry.lastChangeDate | timesince'`

Of course, without blocktrans all works fine.

So, what is simples way to translate few words? (I am interesting polish lang, minutes -> minut, hours -> godzin, etc)
I will be thankful for clear example.

EDIT:
in my .po file i have now:

#: templates/part.html:37
#, python-format
msgid ""
"\n"
"%(lastChangeDate)s\n"
msgstr ""

and i don't see anything about var in docs... now i would do:

msgid "hours"
msgstr "godzin"

etc and bind it to my var (above example don't work...)


问:
Unable to access inputfield in modal generated by TinyMCE react in Next.JS
I am using Next.JS in my project. I want to add the TinyMCE editor to my page. I have used the below code.

```<code><TinyMceEditor
    selector='textarea'
    initialValue={ props.value }
    apiKey=<API_KEY>
    init={{
        height: 500,
        menubar: false,
        plugins: [
            'advlist autolink lists link image',
            'charmap print preview anchor help',
            'searchreplace visualblocks code',
            'insertdatetime media table paste wordcount'
        ],
        toolbar:
            'undo redo | formatselect | bold italic underline | \
            alignleft aligncenter alignright | \
            bullist numlist outdent indent | \
            anchor link table image media video | \
            searchreplace visualblocks code'
    }}
    onChange={(...args) => console.log(args)}
/>
</code>```

I am getting two different behavior of this code for the two different pages.

On the homepage, i.e. localhost:3000/, the editor is working correctly. I can add Images through a popup modal, attach a link, etc.

But when I go localhost:3000/admin/teams the input fields of the popup modal are not focusable. It does not gain focus when I click on it. But at the same time, I can interact with the buttons/checkboxes. It is just not focusing on the input field.

I am not getting what is causing this problem. The same problem is also happening in Jodit editor also. I am not getting whether it is related to the Next.JS environment issue or path-related issue. From the last few days after experimenting with these two editors, I am thinking the issue is related to the modal elements used in them (maybe).

Any advice or help would be appreciated. Thank you.

答: It was an issue with the dialog box of Material UI. After passing disableEnforceFocus={true} to <Dialog /> component, it got resolved.

Body:
I am using Next.JS in my project. I want to add the TinyMCE editor to my page. I have used the below code.

<TinyMceEditor
    selector='textarea'
    initialValue={ props.value }
    apiKey=<API_KEY>
    init={{
        height: 500,
        menubar: false,
        plugins: [
            'advlist autolink lists link image',
            'charmap print preview anchor help',
            'searchreplace visualblocks code',
            'insertdatetime media table paste wordcount'
        ],
        toolbar:
            'undo redo | formatselect | bold italic underline | \
            alignleft aligncenter alignright | \
            bullist numlist outdent indent | \
            anchor link table image media video | \
            searchreplace visualblocks code'
    }}
    onChange={(...args) => console.log(args)}
/>

I am getting two different behavior of this code for the two different pages.

On the homepage, i.e. localhost:3000/, the editor is working correctly. I can add Images through a popup modal, attach a link, etc.

But when I go localhost:3000/admin/teams the input fields of the popup modal are not focusable. It does not gain focus when I click on it. But at the same time, I can interact with the buttons/checkboxes. It is just not focusing on the input field.

I am not getting what is causing this problem. The same problem is also happening in Jodit editor also. I am not getting whether it is related to the Next.JS environment issue or path-related issue. From the last few days after experimenting with these two editors, I am thinking the issue is related to the modal elements used in them (maybe).

Any advice or help would be appreciated. Thank you.


问:
Capacitor / Ionic / Vue Local Notification eventlistener
I'm trying to get Local Notifications working in an Ionic Vue app (using capacitor).

I did get scheduling notifications working, but now i want to listen to clicks on the notification.

in main.js I bind LocalNotifications to this.$LocalNotifications:

```<code>import { Plugins } from '@capacitor/core';
const { LocalNotifications } = Plugins;

Vue.prototype.$LocalNotifications = LocalNotifications;
</code>```

in my Root component App I have this:

```<code>created() {
console.log('Created!')
document.addEventListener('deviceready', () => {
      console.log('ready');
       this.$LocalNotifications.addListener('localNotificationReceived', (notification) => {
          console.log('Notification action received', notification);
        });
    }, false);
}
</code>```

When I build and run on the ios-emulator, i get the following output in my log:

```<code>APP ACTIVE
To Native Cordova ->  Badge load Badge1248600129 ["options": []]
⚡  [log] - onscript loading complete
To Native Cordova ->  Device getDeviceInfo Device1248600130 ["options": []]
⚡  To Native ->  Storage get 90127150
⚡  TO JS {"value":null}
⚡  [log] - Created!
To Native Cordova ->  LocalNotification launch LocalNotification1248600131 ["options": []]
To Native Cordova ->  LocalNotification ready INVALID ["options": []]
⚡  To Native ->  LocalNotifications addListener ⚡  [log] - ready
90127151
⚡  WebView loaded
⚡  To Native ->  App addListener 90127152
</code>```

When I schedule a Notification, the notification does show up, but I think something doesn't go quite well when i'm adding the listener:

```<code>INVALID ["options":[]]
</code>```

Does anyone have any idea how to solve this?
Or does anyone have a code example of working notifications in an Ionic Vue app?

Kind regards,

Bram

答:
To sum up:

You should use localNotificationActionPerformed instead of localNotificationReceived. The latter is called when notifications are displayed, while the other is listening to actions performed on a notification (as it's stated in the docs), that of course includes clicking / tapping on it.
So your code would look like this:

```<code>this.$LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
  console.log('Notification action received', notification.actionId);
});
</code>```

...which would output "tap". Since you did write 'Notification action received', I assume you wanted to get the action, so I added .actionId after 'notification', which only by itself would be logged as [object Object] or as the object tree.

You also asked for code example, so here it comes:

```<code>// 1.
import { LocalNotifications } from '@capacitor/local-notifications';

// 2.
await LocalNotifications.requestPermissions();

// 3.
await LocalNotifications.registerActionTypes({
  types: [
    {
      id: 'your_choice',
      actions: [
        {
          id: 'dismiss',
          title: 'Dismiss',
          destructive: true
        },
        {
          id: 'open',
          title: 'Open app'
        },
        {
          id: 'respond',
          title: 'Respond',
          input: true
        }
      ]
    }
  ]
});

// 4.
LocalNotifications.schedule({
  notifications: [
    {
      id: 1,
      title: 'Sample title',
      body: 'Sample body',
      actionTypeId: 'your_choice'
    }
  ]
});

// 5.
LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
  console.log(`Notification ${notification.notification.title} was ${notification.actionId}ed.`);
});
</code>```

1: Since your question, plugins have been placed into their own npm packages, so one needs to install @capacitor/local-notifications and import from there.

2: You should make sure that notifications are allowed, ask for permissions if needed.

3: Tapping was your question's topic, but you can define a lot more than that.

4: This is how you actually create & send a notification at once.

5: Logs "Notification Sample title was taped / opened / dismissed / responded.", according to the given action (but not always according to grammar).

Finally, if someone's just getting into local notifications, check out the really nice documentation on what else (a whole lot more!) can be done and also watching this video might give one a head start. At least that's what I did.

Body:
I'm trying to get Local Notifications working in an Ionic Vue app (using capacitor).

I did get scheduling notifications working, but now i want to listen to clicks on the notification.

in main.js I bind LocalNotifications to this.$LocalNotifications:

import { Plugins } from '@capacitor/core';
const { LocalNotifications } = Plugins;

Vue.prototype.$LocalNotifications = LocalNotifications;

in my Root component App I have this:

created() {
console.log('Created!')
document.addEventListener('deviceready', () => {
      console.log('ready');
       this.$LocalNotifications.addListener('localNotificationReceived', (notification) => {
          console.log('Notification action received', notification);
        });
    }, false);
}

When I build and run on the ios-emulator, i get the following output in my log:

APP ACTIVE
To Native Cordova ->  Badge load Badge1248600129 ["options": []]
⚡  [log] - onscript loading complete
To Native Cordova ->  Device getDeviceInfo Device1248600130 ["options": []]
⚡  To Native ->  Storage get 90127150
⚡  TO JS {"value":null}
⚡  [log] - Created!
To Native Cordova ->  LocalNotification launch LocalNotification1248600131 ["options": []]
To Native Cordova ->  LocalNotification ready INVALID ["options": []]
⚡  To Native ->  LocalNotifications addListener ⚡  [log] - ready
90127151
⚡  WebView loaded
⚡  To Native ->  App addListener 90127152

When I schedule a Notification, the notification does show up, but I think something doesn't go quite well when i'm adding the listener:

INVALID ["options":[]]

Does anyone have any idea how to solve this?
Or does anyone have a code example of working notifications in an Ionic Vue app?

Kind regards,

Bram

Body:
To sum up:

You should use localNotificationActionPerformed instead of localNotificationReceived. The latter is called when notifications are displayed, while the other is listening to actions performed on a notification (as it's stated in the docs), that of course includes clicking / tapping on it.
So your code would look like this:

this.$LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
  console.log('Notification action received', notification.actionId);
});

...which would output "tap". Since you did write 'Notification action received', I assume you wanted to get the action, so I added .actionId after 'notification', which only by itself would be logged as [object Object] or as the object tree.

You also asked for code example, so here it comes:

// 1.
import { LocalNotifications } from '@capacitor/local-notifications';

// 2.
await LocalNotifications.requestPermissions();

// 3.
await LocalNotifications.registerActionTypes({
  types: [
    {
      id: 'your_choice',
      actions: [
        {
          id: 'dismiss',
          title: 'Dismiss',
          destructive: true
        },
        {
          id: 'open',
          title: 'Open app'
        },
        {
          id: 'respond',
          title: 'Respond',
          input: true
        }
      ]
    }
  ]
});

// 4.
LocalNotifications.schedule({
  notifications: [
    {
      id: 1,
      title: 'Sample title',
      body: 'Sample body',
      actionTypeId: 'your_choice'
    }
  ]
});

// 5.
LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
  console.log(`Notification ${notification.notification.title} was ${notification.actionId}ed.`);
});

1: Since your question, plugins have been placed into their own npm packages, so one needs to install @capacitor/local-notifications and import from there.

2: You should make sure that notifications are allowed, ask for permissions if needed.

3: Tapping was your question's topic, but you can define a lot more than that.

4: This is how you actually create & send a notification at once.

5: Logs "Notification Sample title was taped / opened / dismissed / responded.", according to the given action (but not always according to grammar).

Finally, if someone's just getting into local notifications, check out the really nice documentation on what else (a whole lot more!) can be done and also watching this video might give one a head start. At least that's what I did.


问:
rc-tree not showing navigation arrows(+,-) on react
I have tried implementing simple rc-tree component in react, but it doesnt show "+" button which i can expand, it just shows the root parent names.

here is a sandbox link i have created  https://codesandbox.io/s/flamboyant-stonebraker-ythlr?file=/src/App.js

sample code

```<code><Tree
    defaultExpandAll={false}
    style={{ border: "1px solid #000" }}
    treeData={[
        {
            key: "0",
            title: "node 0",
            children: [
                {
                    key: "0-2",
                    title: "node 0-2",
                    children: [
                        { key: "0-2-0", title: "node 0-2-0" },
                        { key: "0-2-1", title: "node 0-2-1" }
                    ]
                },

                { key: "0-4", title: "node 0-4" }
            ]
        },
        {
            key: "1",
            title: "node 1",

            children: [
                {
                    key: "1-0",
                    title: "node 1-0",
                    children: []
                }
            ]
        }
    ]}
/>
</code>```

答:
You need to import the default css styles. Add this to your App.js file

```<code>import "rc-tree/assets/index.css";
</code>```

Body:
I have tried implementing simple rc-tree component in react, but it doesnt show "+" button which i can expand, it just shows the root parent names.

here is a sandbox link i have created  https://codesandbox.io/s/flamboyant-stonebraker-ythlr?file=/src/App.js

sample code

<Tree
    defaultExpandAll={false}
    style={{ border: "1px solid #000" }}
    treeData={[
        {
            key: "0",
            title: "node 0",
            children: [
                {
                    key: "0-2",
                    title: "node 0-2",
                    children: [
                        { key: "0-2-0", title: "node 0-2-0" },
                        { key: "0-2-1", title: "node 0-2-1" }
                    ]
                },

                { key: "0-4", title: "node 0-4" }
            ]
        },
        {
            key: "1",
            title: "node 1",

            children: [
                {
                    key: "1-0",
                    title: "node 1-0",
                    children: []
                }
            ]
        }
    ]}
/>

Body:
You need to import the default css styles. Add this to your App.js file

import "rc-tree/assets/index.css";


问:
Cannot get a circle on the Leaflet Map when user clicks on the button - Blazor
I'm trying to get a circle of certain radius when the user click on the button. My application is in Blazor. I've started with initialise function which works well. However, the GetCircle() function doesn't work and it gives me an exception error 'map.addLayer is not a function' I.

When I also tried to declare the map and circle variable to the top of the code, the error turns to 'Cannot read properties of undefined (reading '_leaflet_id''

Here is my js:

```<code>window.myMap = {
    initialise : function(){
var map = L.map('map').setView([51.75164151931502, -1.2382256195107832], 15);

L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
    attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    maxZoom: 18,
    id: 'mapbox/streets-v11',
    tileSize: 512,
    zoomOffset: -1,
    accessToken: '----'

}).addTo(map);

  var marker = L.marker([51.75262676993951, -1.2533975397416488]).addTo(map);

  map.on('click',function(e) {
    if (marker !== null ) {
        map.removeLayer(marker);
    }

    marker = new L.Marker(e.latlng);
    map.addLayer(marker);

});
},
GetCircle: function()
{
  //here is the issue

    var circle = L.circle([51.75262676993951,-1.2533975397416488],{radius:300});

    map.addLayer(circle);

}

};

</code>```

this is my Blazor Component:

```<code>@page "/testt"
@inject IJSRuntime JSRuntime
@using Microsoft.JSInterop

<style>
    #map {
    height: 600px;
}

</style>
<br>
 <div class="col-9" id="map"  ></div>
<button @onclick="GetCircle">
Get Area
</button>

 @code{

     protected override async Task OnAfterRenderAsync(bool firstRender)
{

if (firstRender)
    {
        await JSRuntime.InvokeVoidAsync("myMap.initialise");

        StateHasChanged();
    }
}
      public async Task GetCircle()

    {
        await JSRuntime.InvokeVoidAsync("myMap.GetCircle");

    }
}

</code>```

I'm getting  'map.addLayer is not a function'
I've tried to put 'addTo(map)' instead of addLayer and the same error came out.

Any hint?

答:
Your map variable is not accessible gloabl.
You can do following:

```<code>var map = L.map('map').setView([51.75164151931502, -1.2382256195107832], 15);
window.map = map;
</code>```
```<code>GetCircle: function()
{
    var circle = L.circle([51.75262676993951,-1.2533975397416488],{radius:300});
    window.map.addLayer(circle);
}
</code>```

Body:
I'm trying to get a circle of certain radius when the user click on the button. My application is in Blazor. I've started with initialise function which works well. However, the GetCircle() function doesn't work and it gives me an exception error 'map.addLayer is not a function' I.

When I also tried to declare the map and circle variable to the top of the code, the error turns to 'Cannot read properties of undefined (reading '_leaflet_id''

Here is my js:

window.myMap = {
    initialise : function(){
var map = L.map('map').setView([51.75164151931502, -1.2382256195107832], 15);

L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
    attribution: 'Map data © OpenStreetMap contributors',
    maxZoom: 18,
    id: 'mapbox/streets-v11',
    tileSize: 512,
    zoomOffset: -1,
    accessToken: '----'

}).addTo(map);

  var marker = L.marker([51.75262676993951, -1.2533975397416488]).addTo(map);

  map.on('click',function(e) {
    if (marker !== null ) {
        map.removeLayer(marker);
    }

    marker = new L.Marker(e.latlng);
    map.addLayer(marker);

});
},
GetCircle: function()
{
  //here is the issue

    var circle = L.circle([51.75262676993951,-1.2533975397416488],{radius:300});

    map.addLayer(circle);

}

};

this is my Blazor Component:

@page "/testt"
@inject IJSRuntime JSRuntime
@using Microsoft.JSInterop

<button @onclick="GetCircle">
Get Area
</button>

 @code{

     protected override async Task OnAfterRenderAsync(bool firstRender)
{

if (firstRender)
    {
        await JSRuntime.InvokeVoidAsync("myMap.initialise");

        StateHasChanged();
    }
}
      public async Task GetCircle()

    {
        await JSRuntime.InvokeVoidAsync("myMap.GetCircle");

    }
}

I'm getting  'map.addLayer is not a function'
I've tried to put 'addTo(map)' instead of addLayer and the same error came out.

Any hint?

Body:
Your map variable is not accessible gloabl.
You can do following:

var map = L.map('map').setView([51.75164151931502, -1.2382256195107832], 15);
window.map = map;

GetCircle: function()
{
    var circle = L.circle([51.75262676993951,-1.2533975397416488],{radius:300});
    window.map.addLayer(circle);
}


问:
warning: Kotlin runtime JAR files in the classpath should have the same version
I get the following warning, but I'm not sure where v1.0.6 resides.

Is it possible this error comes from a Kotlin library somehow including an old Kotlin version?

Any ideas how to fix it or at least how can I follow the suggestion to make kotlin-reflect explicit (1.1) ?

答: The Kotlin version in build.gradle and the one bundled with your IDE are of different versions. Check the kotlin version in build.gradle (app) and in Tools -> Kotlin -> Configure Kotlin Plugin Updates.</p>


问:
Use array_filter() or array_intersect() to filter 2-dimensional array by one column using a 1-dimensional array
I'm trying to filter my first array by my second array.  I want to filter every person whose age is 22,25,35, or 40.  I have these whitelisted values store in an $a2

```<code>$a1 = [
    ['name' => 'mike',  'age' => 18],
    ['name' => 'james', 'age' => 22],
    ['name' => 'sarah', 'age' => 35],
    ['name' => 'ken',   'age' => 29],
];

$a2 = [22, 25, 35, 40];
</code>```

I tried array_intersect() like:

```<code>$results = array_intersect($a2, $a1['age']);
var_dump($results);
</code>```

And array_filter() but without success.

My desired output is:

```<code>[
    ['name' => 'james', 'age' => 22],
    ['name' => 'sarah', 'age' => 35]
]
</code>```

答:
array_uintersect() is the first thing that comes to mind -- it allows you to compare the intersecting values between two arrays.  The fact that you have arrays of different depths means that you will need a custom callback.  Within that callback, you cannot be sure that $a1 values will be represented in temporary variable $a, nor sure that $a2 values will be represented in $b.  To properly handle each iteration, check for an age key else fall back to the base variable).

Code: (Demo)

```<code>$a1 = [
    ['name' => 'mike',  'age' => 18],
    ['name' => 'james', 'age' => 22],
    ['name' => 'sarah', 'age' => 35],
    ['name' => 'ken',   'age' => 29],
];

$a2 = [22, 25, 35, 40];

var_export(
    array_uintersect(
        $a1,
        $a2,
        fn($a, $b) => ($a['age'] ?? $a) <=> ($b['age'] ?? $b)
    )
);
</code>```

Alternatively, a more concise approach involves making iterated calls of in_array() inside of an array_filter() call.  Generally, I strongly advise against making iterated calls of in_array() because in_array() is one of the slowest ways to make checks on array values.  Depending on the actual size of the two input arrays, the following snippet may perform better or worse than array_uintersect() -- I did not do any benchmarks.

Code: (Demo)

```<code>var_export(
    array_filter($a1, fn($row) => in_array($row['age'], $a2))
);
</code>```

Body:
I'm trying to filter my first array by my second array.  I want to filter every person whose age is 22,25,35, or 40.  I have these whitelisted values store in an $a2

$a1 = [
    ['name' => 'mike',  'age' => 18],
    ['name' => 'james', 'age' => 22],
    ['name' => 'sarah', 'age' => 35],
    ['name' => 'ken',   'age' => 29],
];

$a2 = [22, 25, 35, 40];

I tried array_intersect() like:

$results = array_intersect($a2, $a1['age']);
var_dump($results);

And array_filter() but without success.

My desired output is:

[
    ['name' => 'james', 'age' => 22],
    ['name' => 'sarah', 'age' => 35]
]

Body:
array_uintersect() is the first thing that comes to mind -- it allows you to compare the intersecting values between two arrays.  The fact that you have arrays of different depths means that you will need a custom callback.  Within that callback, you cannot be sure that $a1 values will be represented in temporary variable $a, nor sure that $a2 values will be represented in $b.  To properly handle each iteration, check for an age key else fall back to the base variable).

Code: (Demo)

$a1 = [
    ['name' => 'mike',  'age' => 18],
    ['name' => 'james', 'age' => 22],
    ['name' => 'sarah', 'age' => 35],
    ['name' => 'ken',   'age' => 29],
];

$a2 = [22, 25, 35, 40];

var_export(
    array_uintersect(
        $a1,
        $a2,
        fn($a, $b) => ($a['age'] ?? $a) <=> ($b['age'] ?? $b)
    )
);

Alternatively, a more concise approach involves making iterated calls of in_array() inside of an array_filter() call.  Generally, I strongly advise against making iterated calls of in_array() because in_array() is one of the slowest ways to make checks on array values.  Depending on the actual size of the two input arrays, the following snippet may perform better or worse than array_uintersect() -- I did not do any benchmarks.

Code: (Demo)

var_export(
    array_filter($a1, fn($row) => in_array($row['age'], $a2))
);


问:
How to make the RealmSwift RealmOptional compatible with Swift Codable?
Im facing an issue where I can't make the RealmOptional compatible with swift new Codable feature with json decoder.

Cosider the following Realm object.

```<code>class School: Object, Codable {

    @objc dynamic var id: Int64 = 0

    @objc dynamic var name: String?
    var numberOfStudents = RealmOptional<Int64>()
    var classes = List<Class>()

    enum CodingKeys: String, CodingKey {
       case id
       case name
       case numberOfStudents
       case classes
    }
}

class Class: Object, Codable {
    var name: String?
    var numberOfStudents = RealmOptional<Int64>()
}
</code>```

Here we can declare the class as Codable because I wrote an extension for RealmOptinal with the help of this gist. But the problem is when the decoder decodes the json.

Consider this json

```<code>let jsonData = """
[
    "id": 1234,
    "name": "Shreesha",
    "numberOfStudents": nil,
    "classes": {
       "name": "Class V",
       "numberOfStudents": 12
    }
]
""".data(using: .utf8)!
</code>```

In this json all the data are passed and this decodes perfectly with the code.

```<code>let decoder = JSONDecoder()

let decoded = try! decoder.decode(School.self, from: jsonData)
</code>```

But if I remove the numberOfStudents key from the json data which supposed to be a RealmOptional object it will throw an error and it will not decode because RealmOptional is not a swift optional so the decoder thinks that there should be a key in the json data. In JSONDecoder it doesn't try to decode if the key is not there in the json and the property is declared as optional. It simply skips to other keys.

Until now I didn't override the initialiser because we had all the supporting extensions for RealmOptional Realm Lists etc. But now I have to override the init(from decoder: Decoder) to decode it manually and the Realm model has more than 50 properties in it (You know what I mean).

If we override the initialiser I feel there is not point in using JSONDecoder because there is more manual work than using JSONDecoder.

```<code>required convenience init(from decoder: Decoder) throws {
    self.init()
    let container = try decoder.container(keyedBy: CodingKeys.self)

    id = try container.decodeIfPresent(Int64.self, forKey: .id) ?? 0
    name = try container.decodeIfPresent(String?.self, forKey: .name) ?? ""
    numberOfStudents = try container.decodeIfPresent(RealmOptional<Int64>.self, forKey: .numberOfStudents) ?? RealmOptional<Int64>()

    let classesArray = try container.decode([Class].self, forKey: .classes)
    classes.append(objectsIn: classesArray)
}
</code>```

So can someone suggest me the alternate solution to make the RealmOptional compatible with JSONDecoder so that we don't have to override the initialisers.

答:
Since last year, Realm added a new and more easier way for optionals, using @Persisted - docs

How to use it:

```<code>class Order: Object, Codable {

   @Persisted(primaryKey: true) var productOrderId: Int?

   @Persisted var name: String?
   @Persisted var standardPrice: Double?
   @Persisted var paid: Bool?

}
</code>```

Body:
Im facing an issue where I can't make the RealmOptional compatible with swift new Codable feature with json decoder.

Cosider the following Realm object.

class School: Object, Codable {

    @objc dynamic var id: Int64 = 0

    @objc dynamic var name: String?
    var numberOfStudents = RealmOptional<Int64>()
    var classes = List<Class>()

    enum CodingKeys: String, CodingKey {
       case id
       case name
       case numberOfStudents
       case classes
    }
}

class Class: Object, Codable {
    var name: String?
    var numberOfStudents = RealmOptional<Int64>()
}

Here we can declare the class as Codable because I wrote an extension for RealmOptinal with the help of this gist. But the problem is when the decoder decodes the json.

Consider this json

let jsonData = """
[
    "id": 1234,
    "name": "Shreesha",
    "numberOfStudents": nil,
    "classes": {
       "name": "Class V",
       "numberOfStudents": 12
    }
]
""".data(using: .utf8)!

In this json all the data are passed and this decodes perfectly with the code.

let decoder = JSONDecoder()

let decoded = try! decoder.decode(School.self, from: jsonData)

But if I remove the numberOfStudents key from the json data which supposed to be a RealmOptional object it will throw an error and it will not decode because RealmOptional is not a swift optional so the decoder thinks that there should be a key in the json data. In JSONDecoder it doesn't try to decode if the key is not there in the json and the property is declared as optional. It simply skips to other keys.

Until now I didn't override the initialiser because we had all the supporting extensions for RealmOptional Realm Lists etc. But now I have to override the init(from decoder: Decoder) to decode it manually and the Realm model has more than 50 properties in it (You know what I mean).

If we override the initialiser I feel there is not point in using JSONDecoder because there is more manual work than using JSONDecoder.

required convenience init(from decoder: Decoder) throws {
    self.init()
    let container = try decoder.container(keyedBy: CodingKeys.self)

    id = try container.decodeIfPresent(Int64.self, forKey: .id) ?? 0
    name = try container.decodeIfPresent(String?.self, forKey: .name) ?? ""
    numberOfStudents = try container.decodeIfPresent(RealmOptional<Int64>.self, forKey: .numberOfStudents) ?? RealmOptional<Int64>()

    let classesArray = try container.decode([Class].self, forKey: .classes)
    classes.append(objectsIn: classesArray)
}

So can someone suggest me the alternate solution to make the RealmOptional compatible with JSONDecoder so that we don't have to override the initialisers.

Body:
Since last year, Realm added a new and more easier way for optionals, using @Persisted - docs

How to use it:

class Order: Object, Codable {

   @Persisted(primaryKey: true) var productOrderId: Int?

   @Persisted var name: String?
   @Persisted var standardPrice: Double?
   @Persisted var paid: Bool?

}


问:
How to represent regex number ranges (e.g. 1 to 12)?
I'm currently using ([1-9]|1[0-2]) to represent inputs from 1 to 12. (Leading zeros not allowed.)

However it seems rather hacky, and on some days it looks outright dirty.

☞ Is there a proper in-built way to do it?

☞ What are some other ways to represent number ranges?

Body:
You can use:

[1-9]|1[012]


问:
Importing existing terraform resources using a tag or pattern
Due to some accident my .tfstate got deleted and current situation is I have all the resources up and live and also have all the terraform code for those resources. However, whats not there is the state.

I am aware of terraform import but reading documentation what I understood that you have to individually specify resource names to import it. This will be too tedious or impractical since the number of resources are high.The backend being used it azurerm.

My questions is, is there a way I can import existing resource using a filter such as  tags or name pattern?

I am aware of third party tools such as terraformer but I am looking for a more standard and fool proof way to do it, since the infrastructure is of critical nature.

答: Terraformer is a tool that supports large scale import jobs by pattern. It explicitly supports most major and minor cloud providers, including azure.</p>


问:
How to run Python files in example folder?
I am creating a Python package and want to make the example files in the example folder runnable with something like python example_file.py. How do I do it? My example_file.py and __init__.py look like below:

# example_file.py
from demandforecast import DemandForecast # module coded in demandforecast.py

if __name__ == '__main__':
    # Example code here
```
<pre class="lang-py prettyprint-override"><code># __init__.py
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
</code>```

When I navigate to the examples directory and run python example_file.py I get the following error:

```<code>Exception has occurred: ModuleNotFoundError
No module named 'demandforecast'
</code>```

This can be solved by adding using the old sys.path.insert() trick mentioned in Importing files from different folder, but I would rather not include the absolute path because this will vary from user to user.

Here is my directory structure:

```<code>├───demandforecast
│       demandforecast.py
│       __init__.py
│
└───examples
        example_file.py
</code>```

I have tried a few posts here, such as Relative imports in Python 3, but without luck. Adding sys.path.append('../') to the example file before the demandforecast import also did not work.

答:
```<code>from src.pro.demandforecast.demandforecast import foo

if __name__ == '__main__':
    foo()
</code>```

output:

```<code>foo
</code>```

create a folder src and inside of it create a package pro and now inside pro create two packages demandforecast and examples.

Directory structure:

```<code>/src$ tree
.
└── pro
    ├── demandforecast
    │   ├── demandforecast.py
    │   ├── __init__.py
    │   └── __pycache__
    │       ├── demandforecast.cpython-38.pyc
    │       └── __init__.cpython-38.pyc
    ├── examples
    │   ├── example_file.py
    │   └── __init__.py
    ├── __init__.py
    └── __pycache__
        └── __init__.cpython-38.pyc
</code>```

IDE:

Body:
I am creating a Python package and want to make the example files in the example folder runnable with something like python example_file.py. How do I do it? My example_file.py and __init__.py look like below:

# example_file.py
from demandforecast import DemandForecast # module coded in demandforecast.py

if __name__ == '__main__':
    # Example code here

# __init__.py
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))

When I navigate to the examples directory and run python example_file.py I get the following error:

Exception has occurred: ModuleNotFoundError
No module named 'demandforecast'

This can be solved by adding using the old sys.path.insert() trick mentioned in Importing files from different folder, but I would rather not include the absolute path because this will vary from user to user.

Here is my directory structure:

├───demandforecast
│       demandforecast.py
│       __init__.py
│
└───examples
        example_file.py

I have tried a few posts here, such as Relative imports in Python 3, but without luck. Adding sys.path.append('../') to the example file before the demandforecast import also did not work.

Body:
from src.pro.demandforecast.demandforecast import foo

if __name__ == '__main__':
    foo()

output:

foo

create a folder src and inside of it create a package pro and now inside pro create two packages demandforecast and examples.

Directory structure:

/src$ tree
.
└── pro
    ├── demandforecast
    │   ├── demandforecast.py
    │   ├── __init__.py
    │   └── __pycache__
    │       ├── demandforecast.cpython-38.pyc
    │       └── __init__.cpython-38.pyc
    ├── examples
    │   ├── example_file.py
    │   └── __init__.py
    ├── __init__.py
    └── __pycache__
        └── __init__.cpython-38.pyc

IDE:


问:
Clarification on overloading
When the parent class have an add method with 2 parameters, If we add new add method with 3 parameters in child class, shall we call this as over loading?

Thanks in advance.

答:
Overloading is when methods have the SAME NAME but DIFFERENT SIGNATURE.
Overriding - when methods have IDENTICAL NAMES and IDENTICAL SIGNATURE.</p>

Title: Clarification on overloading


问:
What is the impact of `pos_weight` argument in `BCEWithLogitsLoss`?
According to the pytorch doc of nn.BCEWithLogitsLoss, pos_weight is an optional argument  a that takes the weight of positive examples. I don't fully understand the statement "pos_weight > 1 increases recall and pos_weight < 1 increases precision" in that page. How do you guys understand this statement?

答:
The binary cross-entropy with logits loss (nn.BCEWithLogitsLoss, equivalent to F.binary_cross_entropy_with_logits) is a sigmoid layer (nn.Sigmoid) followed with a binary cross-entropy loss (nn.BCELoss). The general case assumes you are in a multi-label classification task i.e. a single input can be labeled with multiple classes. One common sub-case is to have a single class: the binary classification task. If you define q as your tensor of predicted classes and p the ground-truth [0,1] corresponding to the true probabilities for each class.

The explicit formulation for the binary cross-entropy would be:

```<code>z = torch.sigmoid(q)
loss = -(w_p*p*torch.log(z) + (1-p)*torch.log(1-z))
</code>```

introducing the w_p, the weight associated with the true label for each class. Read this post for more details on the weighting scheme used by the BCELoss.

For a given class:

```<code>precision =  TP / (TP + FP)
recall = TP / (TP + FN)
</code>```

Then if w_p > 1, it increases the weight on the positive classification (classifying as true). This will tend to increase false positives (FP), thus decreasing the precision. Similarly if if w_p < 1, we are decreasing the weight on the true class which means it will tend to increase false negatives (FN), which decreases recall.

Body:
The binary cross-entropy with logits loss (nn.BCEWithLogitsLoss, equivalent to F.binary_cross_entropy_with_logits) is a sigmoid layer (nn.Sigmoid) followed with a binary cross-entropy loss (nn.BCELoss). The general case assumes you are in a multi-label classification task i.e. a single input can be labeled with multiple classes. One common sub-case is to have a single class: the binary classification task. If you define q as your tensor of predicted classes and p the ground-truth [0,1] corresponding to the true probabilities for each class.

The explicit formulation for the binary cross-entropy would be:

z = torch.sigmoid(q)
loss = -(w_p*p*torch.log(z) + (1-p)*torch.log(1-z))

introducing the w_p, the weight associated with the true label for each class. Read this post for more details on the weighting scheme used by the BCELoss.

For a given class:

precision =  TP / (TP + FP)
recall = TP / (TP + FN)

Then if w_p > 1, it increases the weight on the positive classification (classifying as true). This will tend to increase false positives (FP), thus decreasing the precision. Similarly if if w_p < 1, we are decreasing the weight on the true class which means it will tend to increase false negatives (FN), which decreases recall.