问:
Google Translation API id blocking ip address for too many requests
I'm setting up a Django Views that requests products data from an API, parse them with BeautifulSoup, apply the googletrans module and save the response into my Postgresql database.

Everything was working fine yesterday until suddenly, Google blocked access on my IP address for too many requests at once..

I just turned on my LTE to change my IP address and it worked.

But now, to make sure that it doesn't happen with this IP address again I need to find a way to call the googletrans API in batches or any other solution that would prevent me from getting blocked again.

This is my Views:

```<code>from bs4 import BeautifulSoup
from googletrans import Translator
import requests
import json

def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.headout.com/api/public/v1/product/get/"

        translator = Translator()

        for item in resp_1_data['items']:
            print('translating item {}'.format(item['id']))
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
                })
            resp_2_data = resp_2.json()

            descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'

            #Parsing work
            soup = BeautifulSoup(descriptiontxt, 'lxml')
            parsed = soup.find('p').text

            #Translation doesn't work
            translation = translator.translate(parsed, dest='fr')

            titlename = item['name']
            titlefr = translator.translate(titlename, dest='fr')

            destinationname = item['city']['name']
            destinationfr = translator.translate(destinationname, dest='fr')

            Product.objects.get_or_create(
                title=titlefr.text,
                destination=destinationfr.text,
                description=translation.text,
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")
</code>```

How can I call the Google translation API in Batch? Or is there any other solution for that?

Please help.

EDIT

Based on @ddor254 where should I put the: time.sleep(2)?

This is what I came out with, is this okay?

```<code>  Product.objects.get_or_create(
      title=titlefr.text,
      destination=destinationfr.text,
      description=translation.text,
      link=item['canonicalUrl'],
      image=item['image']['url']
  )time.sleep(2) #here
</code>```

or like this:

```<code>resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            }, time.sleep(2)) #here
</code>```

Just want to make sure that its the right way to do it before risking of getting this new IP also blocked.

答:
I suggest you read this article from MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429

if this is the response you get so try and look at the header Retry-After in the response object.

so adding a sleep or other delay method, with the value of that header might fix your problem.

Body:
I'm setting up a Django Views that requests products data from an API, parse them with BeautifulSoup, apply the googletrans module and save the response into my Postgresql database.

Everything was working fine yesterday until suddenly, Google blocked access on my IP address for too many requests at once..

I just turned on my LTE to change my IP address and it worked.

But now, to make sure that it doesn't happen with this IP address again I need to find a way to call the googletrans API in batches or any other solution that would prevent me from getting blocked again.

This is my Views:

from bs4 import BeautifulSoup
from googletrans import Translator
import requests
import json

def api_data(request):
    if request.GET.get('mybtn'):  # to improve, == 'something':
        resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            })
        resp_1_data = resp_1.json()
        base_url_2 = "https://www.headout.com/api/public/v1/product/get/"

        translator = Translator()

        for item in resp_1_data['items']:
            print('translating item {}'.format(item['id']))
            # concat ID to the URL string
            url = '{}{}'.format(base_url_2, item['id'] + '?language=fr')

            # make the HTTP request
            resp_2 = requests.get(
                url,
                headers={
                    "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
                })
            resp_2_data = resp_2.json()

            descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...'

            #Parsing work
            soup = BeautifulSoup(descriptiontxt, 'lxml')
            parsed = soup.find('p').text

            #Translation doesn't work
            translation = translator.translate(parsed, dest='fr')

            titlename = item['name']
            titlefr = translator.translate(titlename, dest='fr')

            destinationname = item['city']['name']
            destinationfr = translator.translate(destinationname, dest='fr')

            Product.objects.get_or_create(
                title=titlefr.text,
                destination=destinationfr.text,
                description=translation.text,
                link=item['canonicalUrl'],
                image=item['image']['url']
            )

    return render(request, "form.html")

How can I call the Google translation API in Batch? Or is there any other solution for that?

Please help.

EDIT

Based on @ddor254 where should I put the: time.sleep(2)?

This is what I came out with, is this okay?

  Product.objects.get_or_create(
      title=titlefr.text,
      destination=destinationfr.text,
      description=translation.text,
      link=item['canonicalUrl'],
      image=item['image']['url']
  )time.sleep(2) #here

or like this:

resp_1 = requests.get(
            "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD",
            headers={
                "Headout-Auth": HEADOUT_PRODUCTION_API_KEY
            }, time.sleep(2)) #here

Just want to make sure that its the right way to do it before risking of getting this new IP also blocked.


来源: stackexchange

问:
Which JRE am I really using?
I try to set environment variables JAVA_HOME and JRE_HOME.

JAVA_HOME worked through typing -java version in cmd but I have trouble to
find a solution for JRE_HOME.

```<code>javac version
</code>```

doesn't work

```<code>java-XshowSettings:properties -version
</code>```

doesn't work either

答:
You need to set JAVA_HOME=jre in jdk folder

then do not close the command promt,

then do startup.bat

ContentLicense: CC BY-SA 4.0

Title: Which JRE am I really using?

Body:
I try to set environment variables JAVA_HOME and JRE_HOME.

JAVA_HOME worked through typing -java version in cmd but I have trouble to
find a solution for JRE_HOME.

javac version

doesn't work

java-XshowSettings:properties -version

doesn't work either


问:
Object modified in the function is not being modified outside the function
I'm building a code to parse some JSON details received from the server into a javascript object. The object has many objects inside it.

Then I have another function to create HTML element and apply that object's values (using for - in loop) into HTML tags' "innerHTML".

I have included the code i use below,

```<code>// This one is executed on the 'onLoad' event.

function requestDriverListings() {

**//This object stores the received object from server.**

var drivers = {};

// ***This function requests details from the server and the function in the arguments is executed once the details are received.***

sendUserData ({}, "request driver.php", function (request) {
listDrivers(request,drivers); console.log(drivers); displayDrivers(drivers);});

}

</code>```

This one is the function to create a HTML Element and stores the received data in it and the use JSON.parse() to parse them into a Object.

The driver parameter is the Object passed in the above code.
request parameter has no effect on this problem. (It is the XHR responseText.)

```<code>
function listDrivers (request,driver) {
    var response = document.createElement("html");
    response.innerHTML = request;
    driver = response.querySelector("#drivers").innerHTML;
    var stripComma = driver.lastIndexOf(",");
    driver = JSON.parse(driver.substring(0,stripComma) +"}");

}
</code>```

Here is the displayDrivers function.

drivers Object is passed into driveParsed  in the first function.

requestAPage() is a function to request the displaying element from the server. the function in it's arguments is the function to apply the Objects details into the HTML innerHTML.

```<code>
function displayDrivers (driveParsed) {
    var driverElement = document.createElement("div");
    driverElement.id = "driverElement";
    driverElement.style.display = "none";
    document.getElementById("driverContainer").appendChild(driverElement);

    requestAPage("Drivers.html", "drivers", "driverElement", function() {  selectDrivers();});

    var selectDrivers = function () {

    for (var x=0; x<=Object.keys(driveParsed).length; x++) {
         var driverParsed = driveParsed[x];
         setDriversDetails(driveParsed,x);
         var element = createAElement( "div", {"margin-top": "10px;"});
         element.id = driveParsed.name;
         element.className  = "container border";
         element.innerHTML = driverElement.innerHTML;
         document.getElementById("driverContainer").appendChild(element);

    }

    };

}
</code>```

================================================================

My problem is this displayDrivers() is not getting the modified drivers Object.

Please help me to solve this problem. Sorry for the long description.

答:
@trincot beat me to it and his answer is better. I'll leave this up anyway though.

Try doing this in requestDriverListings:

```<code>function requestDriverListings() {

  var drivers = {};

  sendUserData ({}, "request driver.php", function (request) {
    var updatedDrivers = listDrivers(request,drivers);
    console.log(drivers);
    displayDrivers(updatedDrivers);});
}
</code>```

And this in listDrivers:

```<code>function listDrivers (request,driver) {
  var response = document.createElement("html");
  response.innerHTML = request;
  driver = response.querySelector("#drivers").innerHTML;
  var stripComma = driver.lastIndexOf(",");
  driver = JSON.parse(driver.substring(0,stripComma) +"}");
  return driver;
}
</code>```

Body:
I'm building a code to parse some JSON details received from the server into a javascript object. The object has many objects inside it.

Then I have another function to create HTML element and apply that object's values (using for - in loop) into HTML tags' "innerHTML".

I have included the code i use below,

// This one is executed on the 'onLoad' event.

function requestDriverListings() {

**//This object stores the received object from server.**

var drivers = {};

// ***This function requests details from the server and the function in the arguments is executed once the details are received.***

sendUserData ({}, "request driver.php", function (request) {
listDrivers(request,drivers); console.log(drivers); displayDrivers(drivers);});

}

This one is the function to create a HTML Element and stores the received data in it and the use JSON.parse() to parse them into a Object.

The driver parameter is the Object passed in the above code.
request parameter has no effect on this problem. (It is the XHR responseText.)

function listDrivers (request,driver) {
    var response = document.createElement("html");
    response.innerHTML = request;
    driver = response.querySelector("#drivers").innerHTML;
    var stripComma = driver.lastIndexOf(",");
    driver = JSON.parse(driver.substring(0,stripComma) +"}");

}

Here is the displayDrivers function.

drivers Object is passed into driveParsed  in the first function.

requestAPage() is a function to request the displaying element from the server. the function in it's arguments is the function to apply the Objects details into the HTML innerHTML.

function displayDrivers (driveParsed) {
    var driverElement = document.createElement("div");
    driverElement.id = "driverElement";
    driverElement.style.display = "none";
    document.getElementById("driverContainer").appendChild(driverElement);

    requestAPage("Drivers.html", "drivers", "driverElement", function() {  selectDrivers();});

    var selectDrivers = function () {

    for (var x=0; x<=Object.keys(driveParsed).length; x++) {
         var driverParsed = driveParsed[x];
         setDriversDetails(driveParsed,x);
         var element = createAElement( "div", {"margin-top": "10px;"});
         element.id = driveParsed.name;
         element.className  = "container border";
         element.innerHTML = driverElement.innerHTML;
         document.getElementById("driverContainer").appendChild(element);

    }

    };

}

================================================================

My problem is this displayDrivers() is not getting the modified drivers Object.

Please help me to solve this problem. Sorry for the long description.

Body:
@trincot beat me to it and his answer is better. I'll leave this up anyway though.

Try doing this in requestDriverListings:

function requestDriverListings() {

  var drivers = {};

  sendUserData ({}, "request driver.php", function (request) {
    var updatedDrivers = listDrivers(request,drivers);
    console.log(drivers);
    displayDrivers(updatedDrivers);});
}

And this in listDrivers:

function listDrivers (request,driver) {
  var response = document.createElement("html");
  response.innerHTML = request;
  driver = response.querySelector("#drivers").innerHTML;
  var stripComma = driver.lastIndexOf(",");
  driver = JSON.parse(driver.substring(0,stripComma) +"}");
  return driver;
}


问:
To print the boundary of Binary Tree
I have been asked in an interviews to print the boundary of the Binary Tree. For example.

```<code>      1
   /    \
  2      3
 /  \   /  \
4    5 6    7
    /   \     \
   8     9     10
</code>```

Answer will be : 1, 2, 4, 8, 9, 10, 7, 3

I have given the following answer.

First Method :

I have used a  Bool  variable to solve the above problem.

```<code>void printLeftEdges(BinaryTree *p, bool print) {
   if (!p) return;
   if (print || (!p->left && !p->right))
       cout << p->data << " ";
   printLeftEdges(p->left, print);
   printLeftEdges(p->right, false);
}

void printRightEdges(BinaryTree *p, bool print) {
   if (!p) return;
   printRightEdges(p->left, false);
   printRightEdges(p->right, print);
   if (print || (!p->left && !p->right))
   cout << p->data << " ";
}

void printOuterEdges(BinaryTree *root) {
   if (!root) return;
   cout << root->data << " ";
   printLeftEdges(root->left, true);
   printRightEdges(root->right, true);
}
</code>```

His Response : You have used  Bool  variable so many times. Can you solve this without using that.

Second Method :

I simply used tree traversal to solve this problem.

```<code>1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
     2.1 Print all leaf nodes of left sub-tree from left to right.
     2.2 Print all leaf nodes of right subtree from left to right.
3. Print the right boundary in bottom-up manner.
</code>```

His Response : He was not happy with this method too. He told that you are traversing the tree 3 times. That is too much. Give another solution if you have any.

Third Method :
This time i have went for Level Order traversal (BFS).

```<code> 1: Print starting and ending node of each level
 2: For each other node check if its both the children are <b>NULL</b> then print that node too.
</code>```

His Response : He was not seems happy with this method too because this method takes extra memory of order O(n).

My question is that Tell me a method which traverse tree single times, do not use any Bool variable and do not use any extra memory. Is it possible?

答:
Below is a Java O(n) time complexity solution that solves the problem of counting duplicates (ex: left node that is also leaf node)

```<code>class Node {
    Node left;
    Node right;
    int data;
    Node(int d) {
       data = d;
       left = right = null;
    }
}

class BinaryTree {
    Node root;
    public void getBoundary() {
       preorderLeft(root);
       inorderLeaves(root);
       postorderRight(root);
    }
    public boolean isLeaf(Node node) {
       if (node != null && node.left == null && node.right == null) return true;
       return false;
    }
    public void preorderLeft(Node start) {
       if (start != null && isLeaf(start) == false) System.out.print(start.data + " ");
       if (start.left != null) preorderLeftSide(start.left);
    }
    public void inorderLeaves(Node start) {
       if(start == null) return;
       if(start.left != null) inorderLeaves(start.left);
       if(start.left == null && start.right == null) System.out.print(start.data + " ");
       if(start.right != null) inorderLeaves(start.right);
    }
    public void postorderRight(Node start) {
       if(start.right != null) postorderRightSide(start.right);
       if(start != null && isLeaf(start) == false) System.out.print(start.data + " ");
    }
}
</code>```

This YouTube video was very helpful. The author write comments explaining each method and shows how to skip duplicates. https://youtu.be/7GzuxmZ34cI

ContentLicense: CC BY-SA 3.0

Title: To print the boundary of Binary Tree

Body:
I have been asked in an interviews to print the boundary of the Binary Tree. For example.

      1
   /    \
  2      3
 /  \   /  \
4    5 6    7
    /   \     \
   8     9     10

Answer will be : 1, 2, 4, 8, 9, 10, 7, 3

I have given the following answer.

First Method :

I have used a  Bool  variable to solve the above problem.

void printLeftEdges(BinaryTree *p, bool print) {
   if (!p) return;
   if (print || (!p->left && !p->right))
       cout <
data << " ";
   printLeftEdges(p->left, print);
   printLeftEdges(p->right, false);
}

void printRightEdges(BinaryTree *p, bool print) {
   if (!p) return;
   printRightEdges(p->left, false);
   printRightEdges(p->right, print);
   if (print || (!p->left && !p->right))
   cout <
data << " ";
}

void printOuterEdges(BinaryTree *root) {
   if (!root) return;
   cout << root->data << " ";
   printLeftEdges(root->left, true);
   printRightEdges(root->right, true);
}

His Response : You have used  Bool  variable so many times. Can you solve this without using that.

Second Method :

I simply used tree traversal to solve this problem.

1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
     2.1 Print all leaf nodes of left sub-tree from left to right.
     2.2 Print all leaf nodes of right subtree from left to right.
3. Print the right boundary in bottom-up manner.

His Response : He was not happy with this method too. He told that you are traversing the tree 3 times. That is too much. Give another solution if you have any.

Third Method :
This time i have went for Level Order traversal (BFS).

 1: Print starting and ending node of each level
 2: For each other node check if its both the children are NULL then print that node too.

His Response : He was not seems happy with this method too because this method takes extra memory of order O(n).

My question is that Tell me a method which traverse tree single times, do not use any Bool variable and do not use any extra memory. Is it possible?

Body:
Below is a Java O(n) time complexity solution that solves the problem of counting duplicates (ex: left node that is also leaf node)

class Node {
    Node left;
    Node right;
    int data;
    Node(int d) {
       data = d;
       left = right = null;
    }
}

class BinaryTree {
    Node root;
    public void getBoundary() {
       preorderLeft(root);
       inorderLeaves(root);
       postorderRight(root);
    }
    public boolean isLeaf(Node node) {
       if (node != null && node.left == null && node.right == null) return true;
       return false;
    }
    public void preorderLeft(Node start) {
       if (start != null && isLeaf(start) == false) System.out.print(start.data + " ");
       if (start.left != null) preorderLeftSide(start.left);
    }
    public void inorderLeaves(Node start) {
       if(start == null) return;
       if(start.left != null) inorderLeaves(start.left);
       if(start.left == null && start.right == null) System.out.print(start.data + " ");
       if(start.right != null) inorderLeaves(start.right);
    }
    public void postorderRight(Node start) {
       if(start.right != null) postorderRightSide(start.right);
       if(start != null && isLeaf(start) == false) System.out.print(start.data + " ");
    }
}

This YouTube video was very helpful. The author write comments explaining each method and shows how to skip duplicates. https://youtu.be/7GzuxmZ34cI


问:
How to remove error when pathprovider search an empty file in flutter?
Hello I use pathprovider to search a video I saved. I use a bottom app bar and pageview to slide between page, and when I change page and build the widget , my inistat() search in a folder a file, but if there isn't file I have graphic error, and it's uggly when I change page, I have a quick error screen. How can remove this error screen ?

here is where I think is the problem:

```<code>  Future<String> startVideoRecording() async {
    RegExp regExp = new RegExp(            //Here is the regex fonction to extract long, lat
      r"(^\S*)",
    );

    var match = regExp.firstMatch("$_currentDate");
    _currentDate_modify = match.group(1);

    final Directory extDir = await getApplicationDocumentsDirectory();
    print('file:${extDir.path}/Movies/$_currentDate_modify.mp4');
    _controller = VideoPlayerController.network(

        'file:${extDir.path}/Movies/$_currentDate_modify.mp4'
    )

      ..initialize().then((_) {
        setState(() {

        });
      });

  }
</code>```

答:
You can set a default value or default widget to show while the async function completes..

```<code>String variable;
</code>```

To set default value

```<code>variable??'default value'
</code>```

To set a default widget, I just used an empty container

```<code>variable!=null?Your_Widget():Container()
</code>```

Body:
Hello I use pathprovider to search a video I saved. I use a bottom app bar and pageview to slide between page, and when I change page and build the widget , my inistat() search in a folder a file, but if there isn't file I have graphic error, and it's uggly when I change page, I have a quick error screen. How can remove this error screen ?

here is where I think is the problem:

  Future<String> startVideoRecording() async {
    RegExp regExp = new RegExp(            //Here is the regex fonction to extract long, lat
      r"(^\S*)",
    );

    var match = regExp.firstMatch("$_currentDate");
    _currentDate_modify = match.group(1);

    final Directory extDir = await getApplicationDocumentsDirectory();
    print('file:${extDir.path}/Movies/$_currentDate_modify.mp4');
    _controller = VideoPlayerController.network(

        'file:${extDir.path}/Movies/$_currentDate_modify.mp4'
    )

      ..initialize().then((_) {
        setState(() {

        });
      });

  }

Body:
You can set a default value or default widget to show while the async function completes..

String variable;

To set default value

variable??'default value'

To set a default widget, I just used an empty container

variable!=null?Your_Widget():Container()


问:
Ignore overflow error when multiplication result is bigger than what a double can hold
During some iterative optimization, the following VBA code for the computation of the bivariate normal CDF sometimes throws an Overflow error on the line with z = hx * hy * c inside the while loop of the upper function.

I debugged the code and the overflow occurs when the numbers being multiplied result in a number bigger than what a double can hold.

Can you show me how to handle the problem by ignoring the iterations of the loop with such high values - I guess that's the only feasible solution (?). I tried myself with a On Error Goto nextiteration line before the multiplication and placing the nextiteration jump point before the Wend, but the error persists.

```<code>Function tetrachoric(x As Double, y As Double, rho As Double) As Double
    Const FACCURACY As Double = 0.0000000000001
    Const MinStopK As Integer = 20
    Dim k As Integer
    Dim c As Double
    Dim z As Double
    Dim s As Double
    Dim hx As Double
    Dim hx1 As Double
    Dim hx2 As Double
    Dim hy As Double
    Dim hy1 As Double
    Dim hy2 As Double
    Dim CheckPass As Integer

    hx = 1
    hy = 1
    hx1 = 0
    hy1 = 0
    k = 0

    c = rho
    z = c
    s = z
    CheckPass = 0

    While CheckPass < MinStopK
        k = k + 1
        hx2 = hx1
        hy2 = hy1
        hx1 = hx
        hy1 = hy
        hx = x * hx1 - (k - 1) * hx2
        hy = y * hy1 - (k - 1) * hy2
        c = c * rho / (k + 1)
        z = hx * hy * c
        s = s + z
        If Abs(z / s) < FACCURACY Then
            CheckPass = CheckPass + 1
        Else
            CheckPass = 0
        End If
    Wend
    tetrachoric = s
End Function

Public Function bivnor(x As Double, y As Double, rho As Double) As Double
'
' bivnor function
' Calculates bivariat normal CDF F(x,y,rho) for a pair of standard normal
' random variables with correlation RHO
'
If rho = 0 Then
    bivnor = Application.WorksheetFunction.NormSDist(x) * _
         Application.WorksheetFunction.NormSDist(y)
Else
    bivnor = Application.WorksheetFunction.NormSDist(x) * _
         Application.WorksheetFunction.NormSDist(y) + _
         Application.WorksheetFunction.NormDist(x, 0, 1, False) * _
         Application.WorksheetFunction.NormDist(y, 0, 1, False) * _
         tetrachoric(x, y, rho)
End If
End Function
</code>```

Source: Available for download at http://michael.marginalq.com/

答:
Updated code using On Error Resume Next instead of On Error Goto:

```<code>While CheckPass < MinStopK
    k = k + 1
    hx2 = hx1
    hy2 = hy1
    hx1 = hx
    hy1 = hy
    hx = x * hx1 - (k - 1) * hx2
    hy = y * hy1 - (k - 1) * hy2
    c = c * rho / (k + 1)
    On Error Resume Next
    z = hx * hy * c
    If Err.Number = 0 Then
        s = s + z
        If Abs(z / s) < FACCURACY Then
            CheckPass = CheckPass + 1
        Else
            CheckPass = 0
        End If
    Else
        Err.Clear
    End If
Wend
</code>```

Body:
During some iterative optimization, the following VBA code for the computation of the bivariate normal CDF sometimes throws an Overflow error on the line with z = hx * hy * c inside the while loop of the upper function.

I debugged the code and the overflow occurs when the numbers being multiplied result in a number bigger than what a double can hold.

Can you show me how to handle the problem by ignoring the iterations of the loop with such high values - I guess that's the only feasible solution (?). I tried myself with a On Error Goto nextiteration line before the multiplication and placing the nextiteration jump point before the Wend, but the error persists.

Function tetrachoric(x As Double, y As Double, rho As Double) As Double
    Const FACCURACY As Double = 0.0000000000001
    Const MinStopK As Integer = 20
    Dim k As Integer
    Dim c As Double
    Dim z As Double
    Dim s As Double
    Dim hx As Double
    Dim hx1 As Double
    Dim hx2 As Double
    Dim hy As Double
    Dim hy1 As Double
    Dim hy2 As Double
    Dim CheckPass As Integer

    hx = 1
    hy = 1
    hx1 = 0
    hy1 = 0
    k = 0

    c = rho
    z = c
    s = z
    CheckPass = 0

    While CheckPass < MinStopK
        k = k + 1
        hx2 = hx1
        hy2 = hy1
        hx1 = hx
        hy1 = hy
        hx = x * hx1 - (k - 1) * hx2
        hy = y * hy1 - (k - 1) * hy2
        c = c * rho / (k + 1)
        z = hx * hy * c
        s = s + z
        If Abs(z / s) < FACCURACY Then
            CheckPass = CheckPass + 1
        Else
            CheckPass = 0
        End If
    Wend
    tetrachoric = s
End Function

Public Function bivnor(x As Double, y As Double, rho As Double) As Double
'
' bivnor function
' Calculates bivariat normal CDF F(x,y,rho) for a pair of standard normal
' random variables with correlation RHO
'
If rho = 0 Then
    bivnor = Application.WorksheetFunction.NormSDist(x) * _
         Application.WorksheetFunction.NormSDist(y)
Else
    bivnor = Application.WorksheetFunction.NormSDist(x) * _
         Application.WorksheetFunction.NormSDist(y) + _
         Application.WorksheetFunction.NormDist(x, 0, 1, False) * _
         Application.WorksheetFunction.NormDist(y, 0, 1, False) * _
         tetrachoric(x, y, rho)
End If
End Function

Source: Available for download at http://michael.marginalq.com/

Body:
Updated code using On Error Resume Next instead of On Error Goto:

While CheckPass < MinStopK
    k = k + 1
    hx2 = hx1
    hy2 = hy1
    hx1 = hx
    hy1 = hy
    hx = x * hx1 - (k - 1) * hx2
    hy = y * hy1 - (k - 1) * hy2
    c = c * rho / (k + 1)
    On Error Resume Next
    z = hx * hy * c
    If Err.Number = 0 Then
        s = s + z
        If Abs(z / s) < FACCURACY Then
            CheckPass = CheckPass + 1
        Else
            CheckPass = 0
        End If
    Else
        Err.Clear
    End If
Wend


问:
How to change names of error queues and exchanges in MassTransit for RabbitMQ?
I tried to throw some exceptions in a simple configuration and noticed the creation of a few exchanges and one queue related to errors:

Exchanges:

MassTransit:Fault

MassTransit:Fault--ConsoleApp1:Program-YourMessage--

Queues:

ReceiveEndPointQueue_error

How can I change or customize the naming of those above?

Program.cs:

```<code>public static class Program
{
    public class YourMessage
    {
        public string Text { get; set; }
    }

    public class MyMessage
    {
        public int Number { get; set; }
    }

    public static async Task Main(params string[] args)
    {
        var bus = Bus.Factory.CreateUsingRabbitMq(configuration =>
        {
            configuration.OverrideDefaultBusEndpointQueueName("DefaultBusEndpointQueue");
            configuration.Message<YourMessage>(x =>
            {
                x.SetEntityName("YourMessageEntity");
            });
            configuration.Message<MyMessage>(x =>
            {
                x.SetEntityName("MyMessageEntity");
            });

            var host = configuration.Host(new Uri("rabbitmq://localhost"), h =>
            {
            });
            configuration.ReceiveEndpoint(host, "ReceiveEndPointQueue", ep =>
            {
                ep.Handler<YourMessage>(async context => throw new Exception("YourMessage"));
                ep.Handler<MyMessage>(async context => await Console.Out.WriteLineAsync($"Received MyMessage: {context.Message.Number}"));
            });
        });

        await bus.StartAsync();
        await bus.Publish(new YourMessage{Text = "Hi"});
        await bus.Publish(new MyMessage {Number= 42});
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        await bus.StopAsync();
    }
}
</code>```

答:
Directly quoted https://gitter.im/MassTransit/MassTransit

```<code>Ehouarn Perret
@ehouarn-perret
May 30 20:14
"I am still looking for a way to change the default names of Error Exchanges / Queues when using MassTransit with RabbitMQ, can't find anything in the documentation"

Chris Patterson
@phatboyg
May 30 20:31
"There isnt' a way to change them, it's always queue_error"
</code>```

Body:
I tried to throw some exceptions in a simple configuration and noticed the creation of a few exchanges and one queue related to errors:

Exchanges:

MassTransit:Fault

MassTransit:Fault--ConsoleApp1:Program-YourMessage--

Queues:

ReceiveEndPointQueue_error

How can I change or customize the naming of those above?

Program.cs:

public static class Program
{
    public class YourMessage
    {
        public string Text { get; set; }
    }

    public class MyMessage
    {
        public int Number { get; set; }
    }

    public static async Task Main(params string[] args)
    {
        var bus = Bus.Factory.CreateUsingRabbitMq(configuration =>
        {
            configuration.OverrideDefaultBusEndpointQueueName("DefaultBusEndpointQueue");
            configuration.Message<YourMessage>(x =>
            {
                x.SetEntityName("YourMessageEntity");
            });
            configuration.Message<MyMessage>(x =>
            {
                x.SetEntityName("MyMessageEntity");
            });

            var host = configuration.Host(new Uri("rabbitmq://localhost"), h =>
            {
            });
            configuration.ReceiveEndpoint(host, "ReceiveEndPointQueue", ep =>
            {
                ep.Handler<YourMessage>(async context => throw new Exception("YourMessage"));
                ep.Handler<MyMessage>(async context => await Console.Out.WriteLineAsync($"Received MyMessage: {context.Message.Number}"));
            });
        });

        await bus.StartAsync();
        await bus.Publish(new YourMessage{Text = "Hi"});
        await bus.Publish(new MyMessage {Number= 42});
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        await bus.StopAsync();
    }
}

Body:
Directly quoted https://gitter.im/MassTransit/MassTransit

Ehouarn Perret
@ehouarn-perret
May 30 20:14
"I am still looking for a way to change the default names of Error Exchanges / Queues when using MassTransit with RabbitMQ, can't find anything in the documentation"

Chris Patterson
@phatboyg
May 30 20:31
"There isnt' a way to change them, it's always queue_error"


问:
services.AddSingleton, service's constructor is never called
tl;dr

```<code>services.AddSingleton<ISomeService, SomeService>();
// SomeService not instantiated nor initialized?
</code>```

In a variation on the classic SignalR Chat app, I'm monitoring changes to a SQL Server table and reporting them in real-time through SignalR. Watch this video for 10 seconds to get the idea. My code is adapted from this project. The chat part works fine.

Changes to the SQL Server table are supposed to be monitored by class SqlDependencyService. However, its constructor is never called, and that's where it should get a reference to the SignalR hub.

Here's my Startup.ConfigureServices:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddSignalR();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // No instantiation ?!?
    services.AddSingleton<IDatabaseChangeNotificationService, SqlDependencyService>();

    // My lame attempt at forcing instantiation:
    SqlDependencyService sqlDS = serviceProvider.GetService<SqlDependencyService>();
    //sqlDS.Config(); // Fails, sqlDS is null.
}
</code>```

And here's part of my SqlDependencyService class:

```<code>public class SqlDependencyService : IDatabaseChangeNotificationService
    {
        private readonly IConfiguration configuration;
        private readonly IHubContext<ChatHub> chatHub;

        // Never gets called!
        public SqlDependencyService(IConfiguration configuration, IHubContext<ChatHub> chatHub)
        {
            this.configuration = configuration;
            this.chatHub = chatHub;
        }

        // Never gets called!
        public void Config()
        {
            SubscribeToPersonTableChanges();
        }

        private void SubscribeToPersonTableChanges()
        {
            // ...
        }

        // ...
    }
</code>```

Here's the service's interface:

```<code>public interface IDatabaseChangeNotificationService
{
    void Config();
}
</code>```

As stated, the constructor is never called. Additionally, I don't see how the Config method could possibly be invoked - some ASP.NET Core convention magic?

I don't have this issue with the HomeController, whose constructor is called and passed an IHubContext<ChatHub>:

```<code>public class HomeController : Controller
{
    private readonly IHubContext<ChatHub> chatHub;

    public HomeController(IHubContext<ChatHub> chatHub)
    {
        this.chatHub = chatHub;
    }

    // ...
}
</code>```

答:
Just adding a service won't cause it to be instantiated, you actually need to inject it into something for the container to call it's constructor. It looks like you want the service to be available at startup, so I would recommend using the Configure method in startup:

```<code>public void Configure(IApplicationBuilder app, IDatabaseChangeNotificationService dbService)
{
    dbService.Config();

    //snip
}
</code>```

Body:
tl;dr

services.AddSingleton<ISomeService, SomeService>();
// SomeService not instantiated nor initialized?

In a variation on the classic SignalR Chat app, I'm monitoring changes to a SQL Server table and reporting them in real-time through SignalR. Watch this video for 10 seconds to get the idea. My code is adapted from this project. The chat part works fine.

Changes to the SQL Server table are supposed to be monitored by class SqlDependencyService. However, its constructor is never called, and that's where it should get a reference to the SignalR hub.

Here's my Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddSignalR();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // No instantiation ?!?
    services.AddSingleton<IDatabaseChangeNotificationService, SqlDependencyService>();

    // My lame attempt at forcing instantiation:
    SqlDependencyService sqlDS = serviceProvider.GetService<SqlDependencyService>();
    //sqlDS.Config(); // Fails, sqlDS is null.
}

And here's part of my SqlDependencyService class:

public class SqlDependencyService : IDatabaseChangeNotificationService
    {
        private readonly IConfiguration configuration;
        private readonly IHubContext<ChatHub> chatHub;

        // Never gets called!
        public SqlDependencyService(IConfiguration configuration, IHubContext<ChatHub> chatHub)
        {
            this.configuration = configuration;
            this.chatHub = chatHub;
        }

        // Never gets called!
        public void Config()
        {
            SubscribeToPersonTableChanges();
        }

        private void SubscribeToPersonTableChanges()
        {
            // ...
        }

        // ...
    }

Here's the service's interface:

public interface IDatabaseChangeNotificationService
{
    void Config();
}

As stated, the constructor is never called. Additionally, I don't see how the Config method could possibly be invoked - some ASP.NET Core convention magic?

I don't have this issue with the HomeController, whose constructor is called and passed an IHubContext<ChatHub>:

public class HomeController : Controller
{
    private readonly IHubContext<ChatHub> chatHub;

    public HomeController(IHubContext<ChatHub> chatHub)
    {
        this.chatHub = chatHub;
    }

    // ...
}

Body:
Just adding a service won't cause it to be instantiated, you actually need to inject it into something for the container to call it's constructor. It looks like you want the service to be available at startup, so I would recommend using the Configure method in startup:

public void Configure(IApplicationBuilder app, IDatabaseChangeNotificationService dbService)
{
    dbService.Config();

    //snip
}


问:
How do I add elements of a set and print their sum?
how do i add elements of the set and print their sum

i have done it by converting the set into list is their any other way without converting the set into a list

```<code>a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x = 0
sum = 0
while x != 10:
    z = list(a1)[x]
    sum += z
    x += 1
    print(sum)

a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x = 0
sum = 0
while x != 10:
    z = a1[x]
    sum += z
    x += 1
    print(sum)
</code>```

Traceback (most recent call last):   File
  "C:/Users/Usman/AppData/Local/Programs/Python/Python37/ddd.py", line
  5, in
      z=(a1[x]) TypeError: 'set' object is not subscriptable

I expect the result to be 55

答:
The usage of sum is great for this as per the other answers. Without using sumhowever, OP was probably trying to use a constructiom like these, that might be useful in contexts that require other actions, not only sum. so I am also posting it here:

```<code>>>> sum = 0
>>> for item in a1:
...     sum += item
...
>>> print(sum)
55
>>>
</code>```

Body:
how do i add elements of the set and print their sum

i have done it by converting the set into list is their any other way without converting the set into a list

a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x = 0
sum = 0
while x != 10:
    z = list(a1)[x]
    sum += z
    x += 1
    print(sum)

a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x = 0
sum = 0
while x != 10:
    z = a1[x]
    sum += z
    x += 1
    print(sum)

Traceback (most recent call last):   File
  "C:/Users/Usman/AppData/Local/Programs/Python/Python37/ddd.py", line
  5, in
      z=(a1[x]) TypeError: 'set' object is not subscriptable

I expect the result to be 55

Body:
The usage of sum is great for this as per the other answers. Without using sumhowever, OP was probably trying to use a constructiom like these, that might be useful in contexts that require other actions, not only sum. so I am also posting it here:

>>> sum = 0
>>> for item in a1:
...     sum += item
...
>>> print(sum)
55
>>>


问:
How to combine two middleware and export as one?
I have a utility file which basically has two functions (one to detect user location and another to get user device details) acting as middlewares. Now I would like to know whether it is possible to combine both the middlewares together as one so that it could be used with other middlewares on the route. I would also like to have the freedom of using the functions in the utility file individually when required.

Utility file

```<code>const axios             = require("axios");
const requestIp         = require("request-ip");

const getDeviceLocation = async (req, res, next) => {
    try {
        // ToDO: Check if it works on production
        const clientIp  = requestIp.getClientIp(req);
        const ipToCheck = clientIp === "::1" || "127.0.0.1" ? "" : clientIp;

        const details = await axios.get("https://geoip-db.com/json/" + ipToCheck);

        // Attach returned results to the request body
        req.body.country    = details.data.country_name;
        req.body.state      = details.data.state;
        req.body.city       = details.data.city;

        // Run next middleware
        next();
    }
    catch(error) {
        return res.status(500).json({ message: "ERROR_OCCURRED" });
    }
};

const getDeviceClient = async (req, res, next) => {
    const userAgent = req.headers["user-agent"];

    console.log("Device UA: " + userAgent);
    next();
};

module.exports = { getDeviceLocation, getDeviceClient };
</code>```

Example Routes

```<code>app.post("/v1/register", [getDeviceLocation, getDeviceClient, Otp.verify], User.create);

app.post("/v1/auth/google", [getDeviceLocation, getDeviceClient, Auth.verifyGoogleIdToken], Auth.useGoogle);
</code>```

I would like to have getDeviceLocation and getDeviceClient combined into one say getDeviceInfo yet have the freedom to use getDeviceLocation and getDeviceClient individually when required on any route.

答: Using connect nodemodule you can do combine the middle ware and expose a new end point for it. Ref here a sample code https://blog.budiharso.info/2015/07/28/Combine-multiple-express-middleware/</p>

Body:
I have a utility file which basically has two functions (one to detect user location and another to get user device details) acting as middlewares. Now I would like to know whether it is possible to combine both the middlewares together as one so that it could be used with other middlewares on the route. I would also like to have the freedom of using the functions in the utility file individually when required.

Utility file

const axios             = require("axios");
const requestIp         = require("request-ip");

const getDeviceLocation = async (req, res, next) => {
    try {
        // ToDO: Check if it works on production
        const clientIp  = requestIp.getClientIp(req);
        const ipToCheck = clientIp === "::1" || "127.0.0.1" ? "" : clientIp;

        const details = await axios.get("https://geoip-db.com/json/" + ipToCheck);

        // Attach returned results to the request body
        req.body.country    = details.data.country_name;
        req.body.state      = details.data.state;
        req.body.city       = details.data.city;

        // Run next middleware
        next();
    }
    catch(error) {
        return res.status(500).json({ message: "ERROR_OCCURRED" });
    }
};

const getDeviceClient = async (req, res, next) => {
    const userAgent = req.headers["user-agent"];

    console.log("Device UA: " + userAgent);
    next();
};

module.exports = { getDeviceLocation, getDeviceClient };

Example Routes

app.post("/v1/register", [getDeviceLocation, getDeviceClient, Otp.verify], User.create);

app.post("/v1/auth/google", [getDeviceLocation, getDeviceClient, Auth.verifyGoogleIdToken], Auth.useGoogle);

I would like to have getDeviceLocation and getDeviceClient combined into one say getDeviceInfo yet have the freedom to use getDeviceLocation and getDeviceClient individually when required on any route.


问:
JQuery select a variable by passing a text string of its name
I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

```<code>var test = "xxx";
</code>```

I'm thinking I could do something like this, but it won't work:

```<code>  alert($("#test"));
</code>```

Edit:  People are getting confused.  Think of it as a reflective way to get the contents of var test.  Preferrably with a JQuery selector, but I'll take any way one can come up with it..

答:
This should work for you.  You have to use the variable outside the string quotes like this.  You could replace the # with a . if you want to use a style selector vs an ID selector.

```<code>var test = "xxx";
alert($("#" + test));
</code>```

If the field is something like <input name="xxx" .../>, you would have to use something like the following:

```<code>var test = "xxx";
alert($("[name=" + test + "]"));
</code>```

Body:
I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

var test = "xxx";

I'm thinking I could do something like this, but it won't work:

  alert($("#test"));

Edit:  People are getting confused.  Think of it as a reflective way to get the contents of var test.  Preferrably with a JQuery selector, but I'll take any way one can come up with it..

Body:
This should work for you.  You have to use the variable outside the string quotes like this.  You could replace the # with a . if you want to use a style selector vs an ID selector.

var test = "xxx";
alert($("#" + test));

If the field is something like <input name="xxx" .../>, you would have to use something like the following:

var test = "xxx";
alert($("[name=" + test + "]"));


问:
How to upload a python file with Kivy to iPhone for free?
I am creating a simple Kivy app in python, but I can't figure out how to upload the .py as app to my iPhone for free.

Can someone help me with this?

答:
according to kivy documentation:

In order to submit any application to the iTunes store, you will need an iOS Developer License. For testing, you can use a physical device or the XCode iOS emulator.

I suggest using a cheap android phone to test out your application. You will need to package your application for Android. In order to do this, you will need to use Linux.


问:
How to find a mathematical method to solve this big value recursion problem?
A python code with a recursion function. To calculate this is to slow by PC. So do there have a easy way to find the answer of this python code?

def rec(n):
    if n<1:
      return 1
    return rec(n//4)+rec(n//2)
print(rec(12345678987654321))
```

答:
You can use lru_cache which is in  functools module.

https://docs.python.org/3/library/functools.html

As the docs state

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments

If maxsize is set to None the cache grows without bound.

```<code>from functools import lru_cache

@lru_cache(maxsize = None)
def rec(n):
    if n < 1:
        return  1
    return rec(n // 4) + rec(n // 2)
print(rec(12345678987654321))
</code>```

Time metrics:

```<code>times = timeit.timeit(setup = 'from __main__ import rec',
stmt = 'print(rec(12345678987654321))', number = 1)
</code>```

With lru_cache

```<code>225851433717
0.00023956200311658904
</code>```

Without lru_cache

```<code>More than 2 minutes
</code>```

Body:
You can use lru_cache which is in  functools module.

https://docs.python.org/3/library/functools.html

As the docs state

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments

If maxsize is set to None the cache grows without bound.

from functools import lru_cache

@lru_cache(maxsize = None)
def rec(n):
    if n < 1:
        return  1
    return rec(n // 4) + rec(n // 2)
print(rec(12345678987654321))

Time metrics:

times = timeit.timeit(setup = 'from __main__ import rec',
stmt = 'print(rec(12345678987654321))', number = 1)

With lru_cache

225851433717
0.00023956200311658904

Without lru_cache

More than 2 minutes


问:
How to re-use a React library with hooks
I'm writing my own library to help building forms with React.

The goal is to be able to re-use it in any React application (made from scratch, with create-react-app, nextjs, other ?)

My problem is that I can't firgure out how to re-use it.

Here is the first issue I encountered when I tried to reuse my library in another project :

Invalid Hook Call Warning

React says that the reason could be one of the following :

You might have mismatching versions of React and React DOM.

You might be breaking the Rules of Hooks.

You might have more than one copy of React in the same app.

After investigation, I've excluded points 1. and 2.

I was using Parcel in the first place to build my library but I needed to exclude React from the bundle to solve 3.

That's why I switched to Webpack and moved the React dependency to the peerDependencies + devDependencies.

I've tried different webpack configurations :

const config: webpack.Configuration = {
  ...
  externals: {
    react: 'React'
  }
}

```

<p>--> which leads to the following error in the consuming application :</p>

<blockquote>
  <p>React is not defined</p>
</blockquote>

<pre class="lang-js prettyprint-override"><code>const config: webpack.Configuration = {
  ...
  externals: {
    react: {
      root: 'React',
      amd: 'react',
      commonjs: 'react',
      commonjs2: 'react',
      umd: 'react',
    }
  }
}
</code>```

--> which leads to the following error :

Cannot read property 'createContext' of undefined

I've tried to use my library with npm link and also by publishing it on npm but the result is the same.

Step to reproduce :

Install @mlaopane/formhook in your react application (npm i @mlaopane/formhook or yarn add @mlaopane/formhook)

Try to use a component, for example

```<code>import { Form } from '@mlaopane/formhook'

export default function App() {
  return <Form />
}
</code>```

You should see the error in the console

Thank you for helping me with this :)

NB: This is my first issue, please tell if more information is needed.

答:
I've finally found a solution, inspired by create-react-library.

It looks like Rollup is a better candidate for bundling React libraries.

Even if I still can't link my library locally, it can be used when published.

Body:
I'm writing my own library to help building forms with React.

The goal is to be able to re-use it in any React application (made from scratch, with create-react-app, nextjs, other ?)

My problem is that I can't firgure out how to re-use it.

Here is the first issue I encountered when I tried to reuse my library in another project :

Invalid Hook Call Warning

React says that the reason could be one of the following :

You might have mismatching versions of React and React DOM.

You might be breaking the Rules of Hooks.

You might have more than one copy of React in the same app.

After investigation, I've excluded points 1. and 2.

I was using Parcel in the first place to build my library but I needed to exclude React from the bundle to solve 3.

That's why I switched to Webpack and moved the React dependency to the peerDependencies + devDependencies.

I've tried different webpack configurations :

const config: webpack.Configuration = {
  ...
  externals: {
    react: 'React'
  }
}

--> which leads to the following error in the consuming application :

React is not defined

const config: webpack.Configuration = {
  ...
  externals: {
    react: {
      root: 'React',
      amd: 'react',
      commonjs: 'react',
      commonjs2: 'react',
      umd: 'react',
    }
  }
}

--> which leads to the following error :

Cannot read property 'createContext' of undefined

I've tried to use my library with npm link and also by publishing it on npm but the result is the same.

Step to reproduce :

Install @mlaopane/formhook in your react application (npm i @mlaopane/formhook or yarn add @mlaopane/formhook)

Try to use a component, for example

import { Form } from '@mlaopane/formhook'

export default function App() {
  return <Form />
}

You should see the error in the console

Thank you for helping me with this :)

NB: This is my first issue, please tell if more information is needed.


问:
Prevent Lazy<T> caching exceptions when invoking Async delegate
I have a need for a simple AsyncLazy<T> which behaves exactly like Lazy<T> but correctly supports handling exceptions and avoids caching them.

Specifically the issue I am running into is as follows:

I can write a piece of code as such:

```<code>public class TestClass
{
    private int i = 0;

    public TestClass()
    {
        this.LazyProperty = new Lazy<string>(() =>
        {
            if (i == 0)
                throw new Exception("My exception");

            return "Hello World";

        }, LazyThreadSafetyMode.PublicationOnly);
    }

    public void DoSomething()
    {
        try
        {
            var res = this.LazyProperty.Value;
            Console.WriteLine(res);
            //Never gets here
        }
        catch { }
        i++;
        try
        {
            var res1 = this.LazyProperty.Value;
            Console.WriteLine(res1);
            //Hello World
        }
        catch { }

    }

    public Lazy<string> LazyProperty { get; }

}
</code>```

Note the use of LazyThreadSafetyMode.PublicationOnly.

If the initialization method throws an exception on any thread, the
  exception is propagated out of the Value property on that thread. The
  exception is not cached.

I then invoke it in the following way.

```<code>TestClass _testClass = new TestClass();
_testClass.DoSomething();
</code>```

and it works exactly as you would expect, where the first result is omitted because an exception occurs, the result remains uncached and the subsequent attempt to read the value succeeds returning 'Hello World'.

Unfortunately however if I change my code to something like this:

```<code>public Lazy<Task<string>> AsyncLazyProperty { get; } = new Lazy<Task<string>>(async () =>
{
    if (i == 0)
        throw new Exception("My exception");

    return await Task.FromResult("Hello World");
}, LazyThreadSafetyMode.PublicationOnly);
</code>```

The code fails the first time it is invoked and subsequent calls to the property are cached (and can therefore never recover).

This somewhat makes sense because I suspect that the exception is never actually bubbling up beyond the task, however what I cannot determine is a way to notify the Lazy<T> that the task/object initialisation has failed and should not be cached.

Anyone able to provide any input?

EDIT:

Thanks for your answer Ivan. I have successfully managed to get a basic example  with your feedback but it turns out my problem is actually more complicated than the basic example above demonstrates and undoubtedly this problem will affect others in a similar situation.

So if I change my property signature to something like this (as per Ivans suggestion)

```<code>this.LazyProperty = new Lazy<Task<string>>(() =>
{
    if (i == 0)
        throw new NotImplementedException();

    return DoLazyAsync();
}, LazyThreadSafetyMode.PublicationOnly);
</code>```

and then invoke it like this.

```<code>await this.LazyProperty.Value;
</code>```

the code works.

However if you have a method like this

```<code>this.LazyProperty = new Lazy<Task<string>>(() =>
{
    return ExecuteAuthenticationAsync();
}, LazyThreadSafetyMode.PublicationOnly);
</code>```

which then itself calls another Async method.

```<code>private static async Task<AccessTokenModel> ExecuteAuthenticationAsync()
{
    var response = await AuthExtensions.AuthenticateAsync();
    if (!response.Success)
        throw new Exception($"Could not authenticate {response.Error}");

    return response.Token;
}
</code>```

The Lazy caching bug manifests again and the problem can be reproduced.

Here is a complete example to reproduce the problem:

```<code>this.AccessToken = new Lazy<Task<string>>(() =>
{
    return OuterFunctionAsync(counter);
}, LazyThreadSafetyMode.PublicationOnly);

public Lazy<Task<string>> AccessToken { get; private set; }

private static async Task<bool> InnerFunctionAsync(int counter)
{
    await Task.Delay(1000);
    if (counter == 0)
        throw new InvalidOperationException();
    return false;
}

private static async Task<string> OuterFunctionAsync(int counter)
{
    bool res = await InnerFunctionAsync(counter);
    await Task.Delay(1000);
    return "12345";
}

try
{
    var r = await this.AccessToken.Value;
}
catch (Exception ex) { }

counter++;

try
{
    //Retry is never performed, cached task returned.
    var r1 = await this.AccessToken.Value;

}
catch (Exception ex) { }
</code>```

答:
The problem is how Lazy<T> defines "failed" interfering with how Task<T> defines "failed".

For an Lazy<T> initialization to "fail", it has to raise an exception. This is perfectly natural and acceptable, although it is implicitly synchronous.

For Task<T> to "fail", exceptions are captured and placed on the task. This is the normal pattern for asynchronous code.

Combining the two causes problems. The Lazy<T> part of Lazy<Task<T>> will only "fail" if exceptions are raised directly, and the async pattern of Task<T> does not propagate exceptions directly. So async factory methods will always appear to (synchronously) "succeed" since they return a Task<T>. At this point the Lazy<T> part is actually done; its value is generated (even if the Task<T> hasn't completed yet).

You can build your own AsyncLazy<T> type without much trouble. You don't have to take a dependency on AsyncEx just for that one type:

```<code>public sealed class AsyncLazy<T>
{
  private readonly object _mutex;
  private readonly Func<Task<T>> _factory;
  private Lazy<Task<T>> _instance;

  public AsyncLazy(Func<Task<T>> factory)
  {
    _mutex = new object();
    _factory = RetryOnFailure(factory);
    _instance = new Lazy<Task<T>>(_factory);
  }

  private Func<Task<T>> RetryOnFailure(Func<Task<T>> factory)
  {
    return async () =>
    {
      try
      {
        return await factory().ConfigureAwait(false);
      }
      catch
      {
        lock (_mutex)
        {
          _instance = new Lazy<Task<T>>(_factory);
        }
        throw;
      }
    };
  }

  public Task<T> Task
  {
    get
    {
      lock (_mutex)
        return _instance.Value;
    }
  }

  public TaskAwaiter<T> GetAwaiter()
  {
    return Task.GetAwaiter();
  }

  public ConfiguredTaskAwaitable<T> ConfigureAwait(bool continueOnCapturedContext)
  {
    return Task.ConfigureAwait(continueOnCapturedContext);
  }
}
</code>```

Body:
I have a need for a simple AsyncLazy<T> which behaves exactly like Lazy<T> but correctly supports handling exceptions and avoids caching them.

Specifically the issue I am running into is as follows:

I can write a piece of code as such:

public class TestClass
{
    private int i = 0;

    public TestClass()
    {
        this.LazyProperty = new Lazy<string>(() =>
        {
            if (i == 0)
                throw new Exception("My exception");

            return "Hello World";

        }, LazyThreadSafetyMode.PublicationOnly);
    }

    public void DoSomething()
    {
        try
        {
            var res = this.LazyProperty.Value;
            Console.WriteLine(res);
            //Never gets here
        }
        catch { }
        i++;
        try
        {
            var res1 = this.LazyProperty.Value;
            Console.WriteLine(res1);
            //Hello World
        }
        catch { }

    }

    public Lazy<string> LazyProperty { get; }

}

Note the use of LazyThreadSafetyMode.PublicationOnly.

If the initialization method throws an exception on any thread, the
  exception is propagated out of the Value property on that thread. The
  exception is not cached.

I then invoke it in the following way.

TestClass _testClass = new TestClass();
_testClass.DoSomething();

and it works exactly as you would expect, where the first result is omitted because an exception occurs, the result remains uncached and the subsequent attempt to read the value succeeds returning 'Hello World'.

Unfortunately however if I change my code to something like this:

public Lazy<Task<string>> AsyncLazyProperty { get; } = new Lazy<Task<string>>(async () =>
{
    if (i == 0)
        throw new Exception("My exception");

    return await Task.FromResult("Hello World");
}, LazyThreadSafetyMode.PublicationOnly);

The code fails the first time it is invoked and subsequent calls to the property are cached (and can therefore never recover).

This somewhat makes sense because I suspect that the exception is never actually bubbling up beyond the task, however what I cannot determine is a way to notify the Lazy<T> that the task/object initialisation has failed and should not be cached.

Anyone able to provide any input?

EDIT:

Thanks for your answer Ivan. I have successfully managed to get a basic example  with your feedback but it turns out my problem is actually more complicated than the basic example above demonstrates and undoubtedly this problem will affect others in a similar situation.

So if I change my property signature to something like this (as per Ivans suggestion)

this.LazyProperty = new Lazy<Task<string>>(() =>
{
    if (i == 0)
        throw new NotImplementedException();

    return DoLazyAsync();
}, LazyThreadSafetyMode.PublicationOnly);

and then invoke it like this.

await this.LazyProperty.Value;

the code works.

However if you have a method like this

this.LazyProperty = new Lazy<Task<string>>(() =>
{
    return ExecuteAuthenticationAsync();
}, LazyThreadSafetyMode.PublicationOnly);

which then itself calls another Async method.

private static async Task<AccessTokenModel> ExecuteAuthenticationAsync()
{
    var response = await AuthExtensions.AuthenticateAsync();
    if (!response.Success)
        throw new Exception($"Could not authenticate {response.Error}");

    return response.Token;
}

The Lazy caching bug manifests again and the problem can be reproduced.

Here is a complete example to reproduce the problem:

this.AccessToken = new Lazy<Task<string>>(() =>
{
    return OuterFunctionAsync(counter);
}, LazyThreadSafetyMode.PublicationOnly);

public Lazy<Task<string>> AccessToken { get; private set; }

private static async Task<bool> InnerFunctionAsync(int counter)
{
    await Task.Delay(1000);
    if (counter == 0)
        throw new InvalidOperationException();
    return false;
}

private static async Task<string> OuterFunctionAsync(int counter)
{
    bool res = await InnerFunctionAsync(counter);
    await Task.Delay(1000);
    return "12345";
}

try
{
    var r = await this.AccessToken.Value;
}
catch (Exception ex) { }

counter++;

try
{
    //Retry is never performed, cached task returned.
    var r1 = await this.AccessToken.Value;

}
catch (Exception ex) { }

Body:
The problem is how Lazy<T> defines "failed" interfering with how Task<T> defines "failed".

For an Lazy<T> initialization to "fail", it has to raise an exception. This is perfectly natural and acceptable, although it is implicitly synchronous.

For Task<T> to "fail", exceptions are captured and placed on the task. This is the normal pattern for asynchronous code.

Combining the two causes problems. The Lazy<T> part of Lazy<Task<T>> will only "fail" if exceptions are raised directly, and the async pattern of Task<T> does not propagate exceptions directly. So async factory methods will always appear to (synchronously) "succeed" since they return a Task<T>. At this point the Lazy<T> part is actually done; its value is generated (even if the Task<T> hasn't completed yet).

You can build your own AsyncLazy<T> type without much trouble. You don't have to take a dependency on AsyncEx just for that one type:

public sealed class AsyncLazy<T>
{
  private readonly object _mutex;
  private readonly Func<Task<T>> _factory;
  private Lazy<Task<T>> _instance;

  public AsyncLazy(Func<Task<T>> factory)
  {
    _mutex = new object();
    _factory = RetryOnFailure(factory);
    _instance = new Lazy<Task<T>>(_factory);
  }

  private Func<Task<T>> RetryOnFailure(Func<Task<T>> factory)
  {
    return async () =>
    {
      try
      {
        return await factory().ConfigureAwait(false);
      }
      catch
      {
        lock (_mutex)
        {
          _instance = new Lazy<Task<T>>(_factory);
        }
        throw;
      }
    };
  }

  public Task<T> Task
  {
    get
    {
      lock (_mutex)
        return _instance.Value;
    }
  }

  public TaskAwaiter<T> GetAwaiter()
  {
    return Task.GetAwaiter();
  }

  public ConfiguredTaskAwaitable<T> ConfigureAwait(bool continueOnCapturedContext)
  {
    return Task.ConfigureAwait(continueOnCapturedContext);
  }
}


问:
How to convert an app/apk as system/user app, including split-apk apps

Background

Without root, I know that it's possible to install a single, normal APK using Intent (here).

Given root, I know that it's possible to install it using this .

This will install the app like a normal installation process, as a user-app.

There is also a way to install a split apk app (here), though for some reason I didn't succeed using it.

The problem

I want to know how to convert and/or install an app to be a system-installed-app, and back to be a user-app.

This includes both APK files of apps that aren't yet installed, and of apps that are already installed.

What I've found

I've found some very old ways to convert an existing app (or installing a new one) into a system app (here, for example or here), saying (in short) I should just move the APK file into /system/app/ path.

Thing is, this might have worked in the past, but now it's not. I think the reason for this is that the apps on /system/app/ exist in a different way now: each app has a folder with some files inside of it.

As for converting back to user app, I can't find it. Same goes for installing a split apk app to system app and convert it back to user app.

In fact, there are apps on the Play store (such as this one) that I remember that could convert other apps into system apps just fine (using root) - now can't do anything.

The questions

When did the method of installing/converting an app to system app worked? How come it doesn't work anymore?

What should be done installing/converting an app to system app, and back to user app, on both old and new Android versions?

Is the same thing possible for split-apk apps (example: AirBnb app) , or at least installed ones?

答:
Below described process won't work with every android build versions but in most cases it will work as expected.

1 - When did the method of installing/converting an app to system app
  worked? How come it doesn't work anymore?

You have two situations to install the application like system app.

When building an android image
You can place the application you want system privileges in /system/app folder and building system will sign it with the platform key and it will work as a system application.

After gaining root permission of installed images
If you can access your android system as the root user, then you can simply push the certain application to /system/app directory on android device.

2 - What should be done installing/converting an app to system app,
  and back to user app, on both old and new Android versions?

If you want to make your application as a system application, you need to add android:sharedUserId="android.uid.system" as application attribute on your AndroiManifest.xml file

```<code><application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:sharedUserId="android.uid.system"
        android:theme="@style/AppTheme">
</code>```

For most of the custom images, manufacturer toolkit is provided and it can be used to create a new image file with system applications. If you don't have such a tool, you can root your device and push apk file to system/app directory.
According to my understanding, we don't have any straight forward way to revert back system app to user app. What you can do is simply uninstall system application and again install it as user application.

3 - Is the same thing possible for split-apk apps (example: AirBnb
  app), or at least installed ones?

Above procedure should work with split-apk apps. But unable to confirm because I have no prior experience.

Body:
Below described process won't work with every android build versions but in most cases it will work as expected.

1 - When did the method of installing/converting an app to system app
  worked? How come it doesn't work anymore?

You have two situations to install the application like system app.

When building an android image
You can place the application you want system privileges in /system/app folder and building system will sign it with the platform key and it will work as a system application.

After gaining root permission of installed images
If you can access your android system as the root user, then you can simply push the certain application to /system/app directory on android device.

2 - What should be done installing/converting an app to system app,
  and back to user app, on both old and new Android versions?

If you want to make your application as a system application, you need to add android:sharedUserId="android.uid.system" as application attribute on your AndroiManifest.xml file

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:sharedUserId="android.uid.system"
        android:theme="@style/AppTheme">

For most of the custom images, manufacturer toolkit is provided and it can be used to create a new image file with system applications. If you don't have such a tool, you can root your device and push apk file to system/app directory.
According to my understanding, we don't have any straight forward way to revert back system app to user app. What you can do is simply uninstall system application and again install it as user application.

3 - Is the same thing possible for split-apk apps (example: AirBnb
  app), or at least installed ones?

Above procedure should work with split-apk apps. But unable to confirm because I have no prior experience.


问:
Why can't I use var in this instance?
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

```<code>var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;
</code>```

Thanks to anyone who can tell me the correct method of making this work.

答:
You should also fix your orderby or else you are just reordering

```<code>orderby brand_family.brand_family_name
orderby brand.priority
orderby brand.genre_id
</code>```

Should become

orderby brand_family.brand_family_name, brand.priority, brand.genre_id

Title: Why can't I use var in this instance?

Body:
I am using the code below and for some reason I can't use var to declare my variable. I am brand new to asp/c# so please go easy on me. I've had a look around and I can't find the correct way of doing this:

var brandslist = from brand in brandDB.brands
                         join brand_family in brandDB.brand_family on brand.brand_family_id equals brand_family.bf_id
                         orderby brand_family.brand_family_name
                         orderby brand.priority
                         orderby brand.genre_id
                         select brand_family.brand_family_name, priority, roll_image;

Thanks to anyone who can tell me the correct method of making this work.

Body:
You should also fix your orderby or else you are just reordering

orderby brand_family.brand_family_name
orderby brand.priority
orderby brand.genre_id

Should become

orderby brand_family.brand_family_name, brand.priority, brand.genre_id


问:
How does callback functions work in NodeJS?
Considering the following code:

rectangle.js:

```<code>module.exports = (x,y,callback) => {
    if (x <= 0 || y <= 0)
        setTimeout(() =>
            callback(new Error("Rectangle dimensions should be greater than zero: l = "
                + x + ", and b = " + y),
            null),
            2000);
    else
        setTimeout(() =>
            callback(null, {
                perimeter: () => (2*(x+y)),
                area:() => (x*y)
            }),
            2000);
}
</code>```

index.js:

```<code>var rect = require('./rectangle');

function solveRect(l,b) {
    console.log("Solving for rectangle with l = "
                + l + " and b = " + b);
    rect(l,b, (err,rectangle) => {
        if (err) {
            console.log("ERROR: ", err.message);
        }
        else {
            console.log("The area of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.area());
            console.log("The perimeter of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.perimeter());
        }
    });
    console.log("This statement after the call to rect()");
};

solveRect(2,4);
solveRect(3,5);
solveRect(0,5);
solveRect(-3,5);
</code>```

In this line rect(l,b, (err,rectangle) we call the rect function and pass l,b, err,rectangle to it. I can see what are l,b but can't see and understand what are err, rectangle ?

Also can't understand where is the definition of callback function? Is it an inner function?

答:
The arrow notation can be confusing here, especially since it takes up most of the rect function call. It is equivalent to

```<code>
var callback = function(err,rectangle){
  if(err) {
    // do stuff
  } else {
    // do stuff
  }
};

rect(l,b, callback);
</code>```

When we call rect(l,b, callback) inside of index.js, it calls the function inside of rectangle.js, passing in a reference to the function in index.js (which i named callback above). This means that when rectangle calls callback(new Error( ... it is passing in an Error object to the callback defined in index.js. And when it calls callback(null, ... it is passing null for the err parameter and the rectangle object for the rectangle parameter in callback.

At the moment we call rect(l,b, callback) we don't have the err or rectangle parameters though, javascript just knows it's passing a function that takes 2 parameters.

Body:
Considering the following code:

rectangle.js:

module.exports = (x,y,callback) => {
    if (x <= 0 || y <= 0)
        setTimeout(() =>
            callback(new Error("Rectangle dimensions should be greater than zero: l = "
                + x + ", and b = " + y),
            null),
            2000);
    else
        setTimeout(() =>
            callback(null, {
                perimeter: () => (2*(x+y)),
                area:() => (x*y)
            }),
            2000);
}

index.js:

var rect = require('./rectangle');

function solveRect(l,b) {
    console.log("Solving for rectangle with l = "
                + l + " and b = " + b);
    rect(l,b, (err,rectangle) => {
        if (err) {
            console.log("ERROR: ", err.message);
        }
        else {
            console.log("The area of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.area());
            console.log("The perimeter of the rectangle of dimensions l = "
                + l + " and b = " + b + " is " + rectangle.perimeter());
        }
    });
    console.log("This statement after the call to rect()");
};

solveRect(2,4);
solveRect(3,5);
solveRect(0,5);
solveRect(-3,5);

In this line rect(l,b, (err,rectangle) we call the rect function and pass l,b, err,rectangle to it. I can see what are l,b but can't see and understand what are err, rectangle ?

Also can't understand where is the definition of callback function? Is it an inner function?

Body:
The arrow notation can be confusing here, especially since it takes up most of the rect function call. It is equivalent to

var callback = function(err,rectangle){
  if(err) {
    // do stuff
  } else {
    // do stuff
  }
};

rect(l,b, callback);

When we call rect(l,b, callback) inside of index.js, it calls the function inside of rectangle.js, passing in a reference to the function in index.js (which i named callback above). This means that when rectangle calls callback(new Error( ... it is passing in an Error object to the callback defined in index.js. And when it calls callback(null, ... it is passing null for the err parameter and the rectangle object for the rectangle parameter in callback.

At the moment we call rect(l,b, callback) we don't have the err or rectangle parameters though, javascript just knows it's passing a function that takes 2 parameters.


问:
Python click call command first then options
is there a way in Python Click library change the execution order?

I want to have cli my_command --options --options

now I have cli --options --options my_command

I don't want a command to be called at the end.

答:
The structure of a click command is as follows:

```<code>command <options> subcommand <subcommand options>
</code>```

I'm not sure how you would have two options with the same name for one command. However, the two '--options' options apply to the 'cli' command and not your 'my_command' command.

To achieve something like what you want:

```<code>import click

@click.group()
@click.option('--options/--not-options', default=False)
def cli(options):
    if options:
        click.echo("Recieved options")

@cli.command()
@click.option('--options/--not-options', default=False)
def my_command(options):
    if options:
        click.echo("Recieved options")

if __name__ == '__main__':
    cli(obj={})
</code>```

To run this from the terminal (filename replaces the 'cli' command entrypoint):

```<code>python mytool.py --options my-command --options

>>Recieved options
>>Received options
</code>```

Body:
The structure of a click command is as follows:

command <options> subcommand <subcommand options>

I'm not sure how you would have two options with the same name for one command. However, the two '--options' options apply to the 'cli' command and not your 'my_command' command.

To achieve something like what you want:

import click

@click.group()
@click.option('--options/--not-options', default=False)
def cli(options):
    if options:
        click.echo("Recieved options")

@cli.command()
@click.option('--options/--not-options', default=False)
def my_command(options):
    if options:
        click.echo("Recieved options")

if __name__ == '__main__':
    cli(obj={})

To run this from the terminal (filename replaces the 'cli' command entrypoint):

python mytool.py --options my-command --options

>>Recieved options
>>Received options


答:
```<code>var test = "#xxx";
alert($(test));
</code>```

Alternatively, you can use:

```<code>var test = "xxx";
alert($("#" + test));
</code>```

Title: JQuery select a variable by passing a text string of its name

Body:
var test = "#xxx";
alert($(test));

Alternatively, you can use:

var test = "xxx";
alert($("#" + test));


问:
pygame.transform.scale does not work on the "game" surface
I am writing a program and I want to zoom in and out where the cursor is positioned.

I have tried (maybe foolishly) to pygame.transform.scale2x the window (which is basically my whole window with the game so:

```<code>window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.transform.scale2x(window)
</code>```

)

Is there any other solution? What am I doing wrong with the pygame.transform.scale2x (I reckon pygame.transform is just for images so how can I use it on a surface?)?
It would be great if the solution did not include changing all of the coordinates of pygame.draw methods as I have a lot of them in my program.
Thanks in advance!

答:
I want to zoom in and out where the cursor is positioned.

Define a zoom factor and calculate the size of the of the zoom area. e.g. If the zoom factor is 2, the area that needs to be zoomed on the window is half the width and height of the window:

zoom = 2

wnd_w, wnd_h = window.get_size()
zoom_size = (round(wnd_w/zoom), round(wnd_h/zoom))
```
<p>Define the rectangular zoom area. The center point of the area is the position where to zoom to. (e.g the cursor position):</p>
<pre class="lang-py prettyprint-override"><code>zoom_area = pygame.Rect(0, 0, *zoom_size)
zoom_area.center = (pos_x, pos_y)
</code>```

Create a new pygame.Surface with the size of the zoom area and copy the region of the window to the surface, by using ,blit, where the area parameter is set to the zoom region:

zoom_surf = pygame.Surface(zoom_area.size)
zoom_surf.blit(screen, (0, 0), zoom_area)
```
<p>Scale <code>zoom_surf</code> by either <code>pygame.transform.scale()</code> or <code>pygame.transform.smoothscale()</code>:</p>
<pre class="lang-py prettyprint-override"><code>zoom_surf = pygame.transform.scale(zoom_surf, (wnd_w, wnd_h))
</code>```

Now zoom_surf has the same size as the window. .blit the surface to the window:

window.blit(zoom_surf, (0, 0))
```

Body:
I am writing a program and I want to zoom in and out where the cursor is positioned.

I have tried (maybe foolishly) to pygame.transform.scale2x the window (which is basically my whole window with the game so:

window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.transform.scale2x(window)

)

Is there any other solution? What am I doing wrong with the pygame.transform.scale2x (I reckon pygame.transform is just for images so how can I use it on a surface?)?
It would be great if the solution did not include changing all of the coordinates of pygame.draw methods as I have a lot of them in my program.
Thanks in advance!

Body:
I want to zoom in and out where the cursor is positioned.

Define a zoom factor and calculate the size of the of the zoom area. e.g. If the zoom factor is 2, the area that needs to be zoomed on the window is half the width and height of the window:

zoom = 2

wnd_w, wnd_h = window.get_size()
zoom_size = (round(wnd_w/zoom), round(wnd_h/zoom))

Define the rectangular zoom area. The center point of the area is the position where to zoom to. (e.g the cursor position):

zoom_area = pygame.Rect(0, 0, *zoom_size)
zoom_area.center = (pos_x, pos_y)

Create a new pygame.Surface with the size of the zoom area and copy the region of the window to the surface, by using ,blit, where the area parameter is set to the zoom region:

zoom_surf = pygame.Surface(zoom_area.size)
zoom_surf.blit(screen, (0, 0), zoom_area)

Scale zoom_surf by either pygame.transform.scale() or pygame.transform.smoothscale():

zoom_surf = pygame.transform.scale(zoom_surf, (wnd_w, wnd_h))

Now zoom_surf has the same size as the window. .blit the surface to the window:

window.blit(zoom_surf, (0, 0))


问:
Came across True false statements in function javascript, what is the point?
I was ripping apart some code from sharepoint and noticed that they have random true false statements in their functions. My first thought was that they would stop the next statement from being ran, but when I made a simple test, the console log showed it ran no matter what.

Could someone let me know what this is for, what the point is, and why you would do it.

here is an example I came across, and will post my test.

```<code> function _SubmitFormPost(a, d, c) {
    if (typeof MSOWebPartPageFormName != "undefined") {

        var b = document.forms[MSOWebPartPageFormName];

        if (null != b)
        {
            if (d != undefined && d == true || typeof b.onsubmit == "undefined" || b.onsubmit == null || b.onsubmit() != false) {
                //HERE IS A RANDOM EXAMPLE OF T/F
                typeof window.WebForm_OnSubmit == "function" && window.WebForm_OnSubmit();
                if (ajaxNavigate.get_search().match(new RegExp("[?&]IsDlg=1")) != null)
                a += a.indexOf("?") == -1 ? "?IsDlg=1" : "&IsDlg=1";
                if (FV4UI())
                try {
                    var e = SP.Ribbon.PageManager.get_instance().get_ribbon().get_selectedTabId();
                    if (Boolean(e)) {
                        a = StURLSetVar2(a, "InitialTabId", escapeProperly(e));
                        a = StURLSetVar2(a, "VisibilityContext", "WSSTabPersistence")
                    }
                } catch (f) {}
                if (c != undefined && c == true) {
                    a = DemoteIntoFormBody(b, a, "owsfileref");
                    a = DemoteIntoFormBody(b, a, "NextUsing")
                }
                b.action = STSPageUrlValidation(a);
                b.method = "POST";
                if (isPortalTemplatePage(a))
                b.target = "_top";
                !bValidSearchTerm && _ClearSearchTerm("");
                b.submit()
            }
        }
    }
}
</code>```

and here was my test, the console window was hitting all the console.logs that I thought it wouldn't

```<code>function s(){
    console.log('in s')
    //is true
    if(1==1){
        //is true
        if(2==2){
            console.log(' if 2==2 and eval of t/f is ',typeof(1) =="function")
            //is false -- expexted to skip console.log
            typeof(1) =="function"
            console.log('2 is 2')
        }
        //is true
        2==3
        if(3==3){
            console.log('3==3')
        }
    }
}
s()
</code>```

答:
&& doesn't just return a value. It also has a (flow control) effect: Its second operand is only evaluated if its first operand is true. That is, A && B doesn't run B if A is already false. (This is known as short-circuit evaluation.)

In other words,

```<code>typeof window.WebForm_OnSubmit == "function" && window.WebForm_OnSubmit();
</code>```

behaves like

```<code>if (typeof window.WebForm_OnSubmit == "function")
    window.WebForm_OnSubmit();
</code>```

but is slightly shorter.

The point is not to return true or false (the result is ignored); the point is to only call window.WebForm_OnSubmit if it is defined as a function.

Similarly,

```<code>!bValidSearchTerm && _ClearSearchTerm("");
</code>```

works like:

```<code>if (!bValidSearchTerm)
    _ClearSearchTerm("");
</code>```

Body:
I was ripping apart some code from sharepoint and noticed that they have random true false statements in their functions. My first thought was that they would stop the next statement from being ran, but when I made a simple test, the console log showed it ran no matter what.

Could someone let me know what this is for, what the point is, and why you would do it.

here is an example I came across, and will post my test.

 function _SubmitFormPost(a, d, c) {
    if (typeof MSOWebPartPageFormName != "undefined") {

        var b = document.forms[MSOWebPartPageFormName];

        if (null != b)
        {
            if (d != undefined && d == true || typeof b.onsubmit == "undefined" || b.onsubmit == null || b.onsubmit() != false) {
                //HERE IS A RANDOM EXAMPLE OF T/F
                typeof window.WebForm_OnSubmit == "function" && window.WebForm_OnSubmit();
                if (ajaxNavigate.get_search().match(new RegExp("[?&]IsDlg=1")) != null)
                a += a.indexOf("?") == -1 ? "?IsDlg=1" : "&IsDlg=1";
                if (FV4UI())
                try {
                    var e = SP.Ribbon.PageManager.get_instance().get_ribbon().get_selectedTabId();
                    if (Boolean(e)) {
                        a = StURLSetVar2(a, "InitialTabId", escapeProperly(e));
                        a = StURLSetVar2(a, "VisibilityContext", "WSSTabPersistence")
                    }
                } catch (f) {}
                if (c != undefined && c == true) {
                    a = DemoteIntoFormBody(b, a, "owsfileref");
                    a = DemoteIntoFormBody(b, a, "NextUsing")
                }
                b.action = STSPageUrlValidation(a);
                b.method = "POST";
                if (isPortalTemplatePage(a))
                b.target = "_top";
                !bValidSearchTerm && _ClearSearchTerm("");
                b.submit()
            }
        }
    }
}

and here was my test, the console window was hitting all the console.logs that I thought it wouldn't

function s(){
    console.log('in s')
    //is true
    if(1==1){
        //is true
        if(2==2){
            console.log(' if 2==2 and eval of t/f is ',typeof(1) =="function")
            //is false -- expexted to skip console.log
            typeof(1) =="function"
            console.log('2 is 2')
        }
        //is true
        2==3
        if(3==3){
            console.log('3==3')
        }
    }
}
s()

Body:
&& doesn't just return a value. It also has a (flow control) effect: Its second operand is only evaluated if its first operand is true. That is, A && B doesn't run B if A is already false. (This is known as short-circuit evaluation.)

In other words,

typeof window.WebForm_OnSubmit == "function" && window.WebForm_OnSubmit();

behaves like

if (typeof window.WebForm_OnSubmit == "function")
    window.WebForm_OnSubmit();

but is slightly shorter.

The point is not to return true or false (the result is ignored); the point is to only call window.WebForm_OnSubmit if it is defined as a function.

Similarly,

!bValidSearchTerm && _ClearSearchTerm("");

works like:

if (!bValidSearchTerm)
    _ClearSearchTerm("");


问:
Using map to return a new array with a sentence for each object
I am trying to use map to return a new array containing sentences for each object.

I've tried a few things but can not seem to get the logic right for returning the values of each object.

An object as such:

```<code>const person = [
  {
    name: "James",
    nationality: "English",
    age: 26
  },
  {
    name: "Pierre",
    nationality: "French",
    age: "23"
  }
]
</code>```

Should return:

```<code>[
  "My name is James, I am English and I am 26",
  "My name is Pierre, I am French and I am 23"
]

</code>```

答:
You can use map to loop thru the array. Use Template literals to construct the desired string.

const person = [{
    name: "James",
    nationality: "English",
    age: 26
  },
  {
    name: "Pierre",
    nationality: "French",
    age: "23"
  }
];

const result = person.map(o => `My name is ${o.name}, I am ${o.nationality} and I am ${o.age}`);

console.log(result);```

Body:
I am trying to use map to return a new array containing sentences for each object.

I've tried a few things but can not seem to get the logic right for returning the values of each object.

An object as such:

const person = [
  {
    name: "James",
    nationality: "English",
    age: 26
  },
  {
    name: "Pierre",
    nationality: "French",
    age: "23"
  }
]

Should return:

[
  "My name is James, I am English and I am 26",
  "My name is Pierre, I am French and I am 23"
]


问:
Pass an additional counter as parameter to a callback
I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

```<code>for (var i=1;i<=daysNum;i++)
{

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + i);

    var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
    var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();

    $("#events").append("<div><div id='event"+i+"'></div><div id='date"+i+"'>"+tmd+"</div></div>");
    $("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"

        ,  function (data){
             if($("event"+i).html()=="")
                $("date"+i).html("");

           }
    );

}
</code>```

答:
```<code>for(var i=0; i<x; i++){
  Ajax(...,function(i) {
    // in callback !
    return function(data) {
      //Work with i:)
    };
  }(i));
</code>```

Body:
I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

for (var i=1;i<=daysNum;i++)
{

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + i);

    var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
    var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();

    $("#events").append("

"+tmd+"

");
    $("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"

        ,  function (data){
             if($("event"+i).html()=="")
                $("date"+i).html("");

           }
    );

}


问:
Nuget pack - Multiple errors with Microsoft tutorial
Following the Microsoft tutorial on NuGet .NET Framework here. I AM using VS 2019.

Everything goes fine until I get to NuGet pack. I get the following error:

'C:\Users\erics\source\repos\AppLogger.vs\AppLogger\v16\Server\sqlite3\db.lock' because it is being used by another process.

The .vs folder is created automatically in all my projects. If I close VS and delete the folder it is recreated. If I close the solution and then try pack again I get:

WARNING: NU5100: The assembly 'AppLogger\bin\Debug\AppLogger.dll' is not inside the 'lib' folder and hence it won't be added as a reference when the package is installed into a project. Move it into the 'lib' folder if it needs to be referenced.

WARNING: NU5100: The assembly 'AppLogger\bin\Release\AppLogger.dll' is not inside the 'lib' folder and hence it won't be added as a reference when the package is installed into a project. Move it into the 'lib' folder if it needs to be referenced.

WARNING: NU5100: The assembly 'AppLogger\obj\Debug\AppLogger.dll' is not inside the 'lib' folder and hence it won't be added as a reference when the package is installed into a project. Move it into the 'lib' folder if it needs to be referenced.

WARNING: NU5100: The assembly 'AppLogger\obj\Release\AppLogger.dll' is not inside the 'lib' folder and hence it won't be added as a reference when the package is installed into a project. Move it into the 'lib' folder if it needs to be referenced.

答:
The NuGet docs were written before SDK style projects existed (before .NET Core was created), and mostly has not been updated since. Therefore the tutorials are very much out of date.

My 30 second tutorial for creating NuGet packages:

Create a "Class library (.NET Core)" project, even if you want to target the .NET Framework. You can also do this from the command line using dotnet new classlib. If you want to target the .NET Framework, right click the project in Solution Explorer, and select "edit project file" (or edit the csproj in your favourite text editor) and change <TargetFramework>netcoreapp2.2</TargetFramework> to <TargetFramework>net472</TargetFramework>, or whatever .NET Framework version you want (remove the dots so 4.7.2 is 472, 4.7 is 47, not 470). Finally, right click the project in Solution Explorer and select Pack, or run dotnet pack from the command line.

Packing SDK style projects (or traditional projects with the MSBuild pack targets) is much improved over using nuget.exe pack and nuspec files, so I strongly suggest using that instead. We (NuGet team) really need to find the time to update the docs.