问:
can't install react-navigation-stack
hi trying to install react-navigation-stack via this code:
npm install @react-navigation/stack

which is what is written at reactnavigation.org

but after installation i get an error that the @react-navigation/stack
could not be found
and i know it is duo to the failed installation which gives this warn at the end of the command line:

npm WARN react-navigation-stack@2.10.4 requires a peer of react-navigation@^4.1.1 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.20.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.

i also tried to install react-navigation dependecies as the website says to do so.
but still can't install after that.

答: Try installing an older version of react-navigation, like 4.2.0 or 4.4.1, I use both of them till now and they work perfectly. After that install @react-navigation/stack. If there is still an error, then give the specific @react-navigation/stack@^5.14.0</p>

Title: can't install react-navigation-stack


来源: stackexchange

问:
Unable to receive integer return value when calling Python function from C++
I am calling a Python function from my C++ code. The Python function takes two numbers as input and returns the sum. I am unable to retrieve the sum value in C++ code. Below are code for both C++ and Python files.

C++ code:

```<code>#include<iostream>
#include "Python.h"

int main()
{
    Py_Initialize();

    PyRun_SimpleString("import sys; sys.path.insert(0, '/home/aakash/Desktop/code/testpc')");

    //Run a python function
    PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
    pName = PyUnicode_FromString((char*)"sample");
    pModule = PyImport_Import(pName);
    pFunc = PyObject_GetAttrString(pModule, (char*)"main2");

    // pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"Greg"));
    pArgs = PyTuple_New(2);
    PyTuple_SetItem(pArgs, 0, PyLong_FromLong(5));
    PyTuple_SetItem(pArgs, 1, PyLong_FromLong(6));
    pValue = PyObject_CallObject(pFunc, pArgs);
    auto result = _PyUnicode_AsString(pValue);
    std::cout << result << std::endl;
    Py_Finalize();
    return 0;
}
</code>```

Python code in sample.py file:

```<code>def main2(a, b):
    print("getting sum ")
    c = a + b
    return c
</code>```

Getting error:- TypeError: bad argument type for built-in operation.
Request to help for other datatypes too.

答: I got the solution by replacing auto result = _PyUnicode_AsString(pValue); with int result = PyFloat_AsDouble(pValue);. But I am not fully convinced as I needed an integer, but I had to use a function which looks to be meant for dealing with Float/Double. So, waiting for an accurate answer. Thanks!

ContentLicense: CC BY-SA 4.0

Body:
I am calling a Python function from my C++ code. The Python function takes two numbers as input and returns the sum. I am unable to retrieve the sum value in C++ code. Below are code for both C++ and Python files.

C++ code:

#include<iostream>
#include "Python.h"

int main()
{
    Py_Initialize();

    PyRun_SimpleString("import sys; sys.path.insert(0, '/home/aakash/Desktop/code/testpc')");

    //Run a python function
    PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
    pName = PyUnicode_FromString((char*)"sample");
    pModule = PyImport_Import(pName);
    pFunc = PyObject_GetAttrString(pModule, (char*)"main2");

    // pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"Greg"));
    pArgs = PyTuple_New(2);
    PyTuple_SetItem(pArgs, 0, PyLong_FromLong(5));
    PyTuple_SetItem(pArgs, 1, PyLong_FromLong(6));
    pValue = PyObject_CallObject(pFunc, pArgs);
    auto result = _PyUnicode_AsString(pValue);
    std::cout << result << std::endl;
    Py_Finalize();
    return 0;
}

Python code in sample.py file:

def main2(a, b):
    print("getting sum ")
    c = a + b
    return c

Getting error:- TypeError: bad argument type for built-in operation.
Request to help for other datatypes too.


问:
How can I escape a double quote inside double quotes?
How can I escape double quotes inside a double string in Bash?

For example, in my shell script

```<code>#!/bin/bash

dbload="load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"
</code>```

I can't get the ENCLOSED BY '\"' with double quote to escape correctly. I can't use single quotes for my variable, because I want to use variable $dbtable.

答:
For use with variables that might contain spaces in you Bash script, use triple quotes inside the main quote, e.g.:

```<code>[ "$(date -r """$touchfile""" +%Y%m%d)" -eq "$(date +%Y%m%d)" ]
</code>```

Body:
How can I escape double quotes inside a double string in Bash?

For example, in my shell script

#!/bin/bash

dbload="load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"

I can't get the ENCLOSED BY '\"' with double quote to escape correctly. I can't use single quotes for my variable, because I want to use variable $dbtable.

Body:
For use with variables that might contain spaces in you Bash script, use triple quotes inside the main quote, e.g.:

[ "$(date -r """$touchfile""" +%Y%m%d)" -eq "$(date +%Y%m%d)" ]


问:
How to get the tabController from subview in tabs
I have a Class: myTabController, in this class I have a UITabBarController, which has 4 subviews in this UITabBarController.

Now I am in my first subview, say it's tab1,
I can call self.parentViewController to get the UITabBarController, and this UITabBarController is owned by myTabController, but How can I get myTabController then? Cause I want to access some data in myTabController.

Thanks Ahead,
Regards

答:
From your wording I am assuming that you have not subclassed UITabBarController.  I would suggest having a property on all four view controllers, something like theTabController, which points to an instance of your class.  Declare this property like this (in the subviews):

```<code>@class myTabController;
...
@interface MySubview : UIView {
    ...
    myTabController * theTabController;
    ...
}
...
@property (nonatomic, assign) myTabController * theTabController;
</code>```

Then, in each subview's implementation, add a synthesize statement.  It's also a good idea to import the header of myTabController in the .m, even though we have an @class in the subview's header.  I used an @class to prevent circular imports.

```<code>#import "myTabController."
...
@implementation MySubview
@synthesize theTabController;
...
@end
</code>```

From myTabController, you need to set this property on each subview like this:

```<code>subview1.theTabController = self;
subview2.theTabController = self;
...
subviewx.theTabController = self;
</code>```

Finally, use the theTabController property sub inside each subview with self.theTabController.

I also have to point out: it's never good to have a class name that starts with a lower case letter.  myTabController should really be MyTabController.

ContentLicense: CC BY-SA 3.0

Body:
From your wording I am assuming that you have not subclassed UITabBarController.  I would suggest having a property on all four view controllers, something like theTabController, which points to an instance of your class.  Declare this property like this (in the subviews):

@class myTabController;
...
@interface MySubview : UIView {
    ...
    myTabController * theTabController;
    ...
}
...
@property (nonatomic, assign) myTabController * theTabController;

Then, in each subview's implementation, add a synthesize statement.  It's also a good idea to import the header of myTabController in the .m, even though we have an @class in the subview's header.  I used an @class to prevent circular imports.

#import "myTabController."
...
@implementation MySubview
@synthesize theTabController;
...
@end

From myTabController, you need to set this property on each subview like this:

subview1.theTabController = self;
subview2.theTabController = self;
...
subviewx.theTabController = self;

Finally, use the theTabController property sub inside each subview with self.theTabController.

I also have to point out: it's never good to have a class name that starts with a lower case letter.  myTabController should really be MyTabController.


问:
How do I change the GitHub URL in Visual Studio?
I know this is probably a really dumb question, but I can't figure it out.
When you go to your branches, right click on one, and click publish, the first time it asks you for a URL and I put in the wrong one (one that doesn't even exist haha). So now whenever I try to publish a branch, it says it can't find it and I don't know how to change the URL because the option doesn't come up anymore.</p>

答:
Goto Git

Select Setting

Source Control > Git Repository Setting > Remote

Edit and Modify


问:
While using a dialogflow mega-agent, according to a user setting I want to be able to query a specific sub agent at a time
While using a dialogflow mega-agent, according to a user setting I want to be able to query a specific sub agent at a time. I have 3 sub agents. Each subagent has similar training phrases but should request different data. The user should be able to select which sub agent they want to use and the query should only go to the selected subagent</p>

答:
To specify one or more sub-agents for a detect intent request, set the subAgents field of QueryParameters.

For example:

```<code>{
  "queryInput": {
    "text": {
      "text": "reserve a meeting room for six people",
      "languageCode": "en-US"
    }
  },
  "queryParams": {
    "subAgents": [
       {"project": "projects/sub-agent-1-project-id"},
       {"project": "projects/sub-agent-2-project-id"}
    ]
  }
}
</code>```

For more information on Dialogflow ES mega agents, see the Mega agents documentation.

Body:
To specify one or more sub-agents for a detect intent request, set the subAgents field of QueryParameters.

For example:

{
  "queryInput": {
    "text": {
      "text": "reserve a meeting room for six people",
      "languageCode": "en-US"
    }
  },
  "queryParams": {
    "subAgents": [
       {"project": "projects/sub-agent-1-project-id"},
       {"project": "projects/sub-agent-2-project-id"}
    ]
  }
}

For more information on Dialogflow ES mega agents, see the Mega agents documentation.


问:
PromTail JSON Scrape Special Character
For a PromTail scrape config, I am using a JSON stage.

I have a JSON log that looks like this:

{
   "@l": "info",
   "foo": "bar"
}
```
<p>I am looking to use the JSON stage to extract the <code>@l</code> property into the map.</p>
<p>I tried this:</p>
```- json:
     expressions:
       level: '"@l"'
- labels:
     level:
```

The agent starts but no logs are scraped. If I remove the JSON stage, tons of logs come in.

What could I be doing wrong with the @ escape sequence?

答:
I have confirmed. To escape a @ or ., you use double quotes.

so examples:

```<code>{
   "@l": "Debug",
   "foo.bar": "value"
}
</code>```

'"@l"'

or

'"foo.bar"'

Source

Using a JMESPath Literal

This pipeline uses a literal JMESPath expression to parse JSON fields with special characters in the name, like @ or .

Title: PromTail JSON Scrape Special Character

Body:
For a PromTail scrape config, I am using a JSON stage.

I have a JSON log that looks like this:

{
   "@l": "info",
   "foo": "bar"
}

I am looking to use the JSON stage to extract the @l property into the map.

I tried this:

- json:
     expressions:
       level: '"@l"'
- labels:
     level:

The agent starts but no logs are scraped. If I remove the JSON stage, tons of logs come in.

What could I be doing wrong with the @ escape sequence?

Body:
I have confirmed. To escape a @ or ., you use double quotes.

so examples:

{
   "@l": "Debug",
   "foo.bar": "value"
}

'"@l"'

or

'"foo.bar"'

Source

Using a JMESPath Literal

This pipeline uses a literal JMESPath expression to parse JSON fields with special characters in the name, like @ or .


问:
int() function not working when accepting an input
I need to write a python program to accept an integer and display its binary and octal equivalent. I have tried different formats, but keep getting errors on my int() function.

This is what I have

dec = int(input())

print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
```
<p>This is the error:</p>
```5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-154-9d3dcb9e828e> in <module>()
----> 1 dec = int(input())
      2
      3 print("The decimal value of", dec, "is:")
      4 print(bin(dec), "in binary.")
      5 print(oct(dec), "in octal.")

TypeError: 'str' object is not callable
```

答: There is an issue with the value of input not referencing the built-in function by that name. Did you define a variable, input, prior to the code you provided? If you set something like input = 'test', and then tried to run dec = int(input()), you will get the error you describe. Change the name of the variable, input, so that it isn't overwriting the built-in function, input, that you would like to call.

Body:
I need to write a python program to accept an integer and display its binary and octal equivalent. I have tried different formats, but keep getting errors on my int() function.

This is what I have

dec = int(input())

print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")

This is the error:

5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-154-9d3dcb9e828e> in <module>()
----> 1 dec = int(input())
      2
      3 print("The decimal value of", dec, "is:")
      4 print(bin(dec), "in binary.")
      5 print(oct(dec), "in octal.")

TypeError: 'str' object is not callable


问:
Polynomial Multiplication using divide and conquer
I'm trying to write code that performs polynomial multiplication using a divide and conquer method. It uses a trick to do only 3 multiplications instead of 4 multiplications, involving splitting each polynomial into two halves and factoring out an x^n/2 from one of the two halves. My code is returning the wrong answer with some test cases and I'm not sure what I'm doing wrong.

Edit: Adding naive multiply function and test cases.

Here's what I've tried so far:

```<code>class Polynom:
    """stores polynomial object"""

    def __init__(self, coefficients):
        """pass coefficient list in increasing order, i.e. x^0 + x^1 + x^2 + ... + x^n"""
        self.coefficients = coefficients
        self.length = len(coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)

    def __add__(self, other):
        for i in range(0,other.length):
            try:
                self.coefficients[i] = self.coefficients[i] + other.coefficients[i]
            except:
                self.coefficients.append(0)
                self.coefficients[i] = self.coefficients[i] + other.coefficients[i]
        self.length = len(self.coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)
        return self

    def __sub__(self, other):
        for i in range(0,other.length):
            self.coefficients[i] = self.coefficients[i] - other.coefficients[i]
        self.length = len(self.coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)
        return self

    def split(self):
        first_max_ind = int((self.length-1)/2)
        first_coefs = self.coefficients[:first_max_ind]
        first = Polynom(first_coefs)
        second_coefs = self.coefficients[first_max_ind:]
        second = Polynom(second_coefs)
        return first, second

def divideAndConquer(a,b):
    """simple divide and conquer algorithm for multiplication"""

    if a.nonZero == 2 and b.nonZero == 2:
        c = naiveMultiply(a,b)
        return c
    else:
        a0, a1 = a.split()
        b0, b1 = b.split()

        # calculate y, u, and z
        y = divideAndConquer(a0 + a1, b0 + b1)
        u = divideAndConquer(a0, b0)
        z = divideAndConquer(a1, b1)
        middleTerm = y - u - z

        NOver2 = int(max(a.length/2, b.length/2))
        lyst = [0] * int(NOver2 + 1)
        lyst[NOver2] = 1
        xNOver2 = Polynom(lyst)

        return u + naiveMultiply(middleTerm, xNOver2) + naiveMultiply(z, xNOver2)

def naiveMultiply(a,b):
    """takes two polynomials and multiplies using naive approach"""

    maxLength = a.length + b.length - 1
    coefficientList = [0] * maxLength

    for i in range(0,a.length):
        for j in range(0, b.length):
            power = i + j
            coefficient = a.coefficients[i] * b.coefficients[j]
            coefficientList[power] += coefficient

    return Polynom(coefficientList)

a = Polynom([1,2,3,4,5])
b = Polynom([1,2,3,4,5])

naiveMultiply(a,b)
divideAndConquer(a,b)
</code>```

The correct answer for test case: (1 + 2x + 3x^2 + 4x^3 + 5x^4)^2
should be:
1 + 4x + 10x^2 + 20x^3 + 35x^4 + 44x^5 + 46x^6 + 40x^7 + 25x^8

but I'm getting:
100 + 100x + 25x^2 + 0x^3 + 0x^4 + 0x^5

答:
In addition to the Pyton-level implementation bugs, there are also math-level bugs here: the polynomials are split down their own middles, but that creates a problem when putting the pieces back together. Also the z piece shouldn't be scaled by the same amount as the middleTerm.

This already looks suspicious anyway:

```<code>    NOver2 = int(max(a.length/2, b.length/2))
</code>```

The goal with the calculation of middleTerm is that the scaled middleTerm (after shifting it) is identical to a0 * b1 * scaleB + a1 * scaleA * b0 (where scaleA corresponds to the size of a0, and scaleB corresponds to the size of b0). If scaleA == scaleB then that's no problem, multiply by the scale afterwards (by shifting - if you implement this scaling as a naiveMultiply then the algorithm isn't efficient). But in this code, the scales are not necessarily the same, they depend on the sizes of a and b. That's a problem.

The z piece is the products of two "upper halves", so it picks up two of those scale factors. So it should be multiplied by the square of the factor that the middle term is scaled by, or rather, shifted by twice as much as the middle term is shifted by.

Body:
I'm trying to write code that performs polynomial multiplication using a divide and conquer method. It uses a trick to do only 3 multiplications instead of 4 multiplications, involving splitting each polynomial into two halves and factoring out an x^n/2 from one of the two halves. My code is returning the wrong answer with some test cases and I'm not sure what I'm doing wrong.

Edit: Adding naive multiply function and test cases.

Here's what I've tried so far:

class Polynom:
    """stores polynomial object"""

    def __init__(self, coefficients):
        """pass coefficient list in increasing order, i.e. x^0 + x^1 + x^2 + ... + x^n"""
        self.coefficients = coefficients
        self.length = len(coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)

    def __add__(self, other):
        for i in range(0,other.length):
            try:
                self.coefficients[i] = self.coefficients[i] + other.coefficients[i]
            except:
                self.coefficients.append(0)
                self.coefficients[i] = self.coefficients[i] + other.coefficients[i]
        self.length = len(self.coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)
        return self

    def __sub__(self, other):
        for i in range(0,other.length):
            self.coefficients[i] = self.coefficients[i] - other.coefficients[i]
        self.length = len(self.coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)
        return self

    def split(self):
        first_max_ind = int((self.length-1)/2)
        first_coefs = self.coefficients[:first_max_ind]
        first = Polynom(first_coefs)
        second_coefs = self.coefficients[first_max_ind:]
        second = Polynom(second_coefs)
        return first, second

def divideAndConquer(a,b):
    """simple divide and conquer algorithm for multiplication"""

    if a.nonZero == 2 and b.nonZero == 2:
        c = naiveMultiply(a,b)
        return c
    else:
        a0, a1 = a.split()
        b0, b1 = b.split()

        # calculate y, u, and z
        y = divideAndConquer(a0 + a1, b0 + b1)
        u = divideAndConquer(a0, b0)
        z = divideAndConquer(a1, b1)
        middleTerm = y - u - z

        NOver2 = int(max(a.length/2, b.length/2))
        lyst = [0] * int(NOver2 + 1)
        lyst[NOver2] = 1
        xNOver2 = Polynom(lyst)

        return u + naiveMultiply(middleTerm, xNOver2) + naiveMultiply(z, xNOver2)

def naiveMultiply(a,b):
    """takes two polynomials and multiplies using naive approach"""

    maxLength = a.length + b.length - 1
    coefficientList = [0] * maxLength

    for i in range(0,a.length):
        for j in range(0, b.length):
            power = i + j
            coefficient = a.coefficients[i] * b.coefficients[j]
            coefficientList[power] += coefficient

    return Polynom(coefficientList)

a = Polynom([1,2,3,4,5])
b = Polynom([1,2,3,4,5])

naiveMultiply(a,b)
divideAndConquer(a,b)

The correct answer for test case: (1 + 2x + 3x^2 + 4x^3 + 5x^4)^2
should be:
1 + 4x + 10x^2 + 20x^3 + 35x^4 + 44x^5 + 46x^6 + 40x^7 + 25x^8

but I'm getting:
100 + 100x + 25x^2 + 0x^3 + 0x^4 + 0x^5

Body:
In addition to the Pyton-level implementation bugs, there are also math-level bugs here: the polynomials are split down their own middles, but that creates a problem when putting the pieces back together. Also the z piece shouldn't be scaled by the same amount as the middleTerm.

This already looks suspicious anyway:

    NOver2 = int(max(a.length/2, b.length/2))

The goal with the calculation of middleTerm is that the scaled middleTerm (after shifting it) is identical to a0 * b1 * scaleB + a1 * scaleA * b0 (where scaleA corresponds to the size of a0, and scaleB corresponds to the size of b0). If scaleA == scaleB then that's no problem, multiply by the scale afterwards (by shifting - if you implement this scaling as a naiveMultiply then the algorithm isn't efficient). But in this code, the scales are not necessarily the same, they depend on the sizes of a and b. That's a problem.

The z piece is the products of two "upper halves", so it picks up two of those scale factors. So it should be multiplied by the square of the factor that the middle term is scaled by, or rather, shifted by twice as much as the middle term is shifted by.


问:
JSDOC: Is it possible to link to a module property?
I'd like know if it's possible to link from one module to another module`s property/method.

What I've tried so far but wasn't working:

```<code>/**
 * {@link module:modules/modulName#id}
 */
</code>```

My modules follow this pattern:

```<code>/**
 * @module modules/modulName
 */
define(function() {

    'use strict';

    /**
     * @alias module:modules/modulName
     */
    var module = {
        /** Initialisation */
        init: function() {}
    };

    return module;

});
</code>```

Is there a way to achieve what I want?

答:
For this, I declare the property I want to reference as @memberof its own module (yes, it is in the same module where the @link tag is).

Then, I just do: {@link module:moduleName.property|textOfTheLink}

Example:

i18n.js module

```<code>/**
 * @category Lib
 * @subcategory i18n
 * @module i18n
 */

/**
 * Memoized translate method.
 *
 * @memberof module:i18n          <----- THIS
 * @type {MemoizedFunction}
 * @function translate
 * @param {i18n.Scope} scope - The translation scope.
 * @param {i18n.TranslateOptions} [options] - Translate options.
 * @version 1.0.0
 * @since 1.0.0
 * @example
 * return <Text>{translate("home.title")}</Text>;
 */
export const translate = memoize(
  (scope, options = undefined) => i18n.t(scope, options),
  (scope, options = undefined) =>
    options ? scope + JSON.stringify(options) : scope
);

/**
 * Shorthand version of the {@link module:i18n.translate|translate} method.  <----- COMBINED WITH THIS :)
 *
 * @function t
 * @example
 * const translatedError = t(`errors.codes.${errorCode}`, {
 *   defaults: [{ message: t("errors.codes.default") }],
 * });
 */
export const t = translate;
</code>```

Body:
I'd like know if it's possible to link from one module to another module`s property/method.

What I've tried so far but wasn't working:

/**
 * {@link module:modules/modulName#id}
 */

My modules follow this pattern:

/**
 * @module modules/modulName
 */
define(function() {

    'use strict';

    /**
     * @alias module:modules/modulName
     */
    var module = {
        /** Initialisation */
        init: function() {}
    };

    return module;

});

Is there a way to achieve what I want?

Body:
For this, I declare the property I want to reference as @memberof its own module (yes, it is in the same module where the @link tag is).

Then, I just do: {@link module:moduleName.property|textOfTheLink}

Example:

i18n.js module

/**
 * @category Lib
 * @subcategory i18n
 * @module i18n
 */

/**
 * Memoized translate method.
 *
 * @memberof module:i18n          <----- THIS
 * @type {MemoizedFunction}
 * @function translate
 * @param {i18n.Scope} scope - The translation scope.
 * @param {i18n.TranslateOptions} [options] - Translate options.
 * @version 1.0.0
 * @since 1.0.0
 * @example
 * return <Text>{translate("home.title")}</Text>;
 */
export const translate = memoize(
  (scope, options = undefined) => i18n.t(scope, options),
  (scope, options = undefined) =>
    options ? scope + JSON.stringify(options) : scope
);

/**
 * Shorthand version of the {@link module:i18n.translate|translate} method.  <----- COMBINED WITH THIS :)
 *
 * @function t
 * @example
 * const translatedError = t(`errors.codes.${errorCode}`, {
 *   defaults: [{ message: t("errors.codes.default") }],
 * });
 */
export const t = translate;


问:
Why in HorizontalPager is the page number returned by the lambda different from the currentPage?
I am using this component and I was having a problem, as I don't get the same result like this:

HorizontalPager(count = tabTitles.size, state = pageState) { page ->
     Log.i("Polaris", "Hi, I'm page $page")
     Log.i("Polaris", "Hi, I'm currentPage $currentPage")
}
```
<p>The result I get is:</p>
```2022-02-05 17:16:06.461 31070-31070/com.polaris I/Polaris: Hi, I'm page 0
2022-02-05 17:16:06.461 31070-31070/com.polaris I/Polaris: Hi, I'm currentPage 0
2022-02-05 17:16:06.464 31070-31070/com.polaris I/Polaris: Hi, I'm page 1
2022-02-05 17:16:06.464 31070-31070/com.polaris I/Polaris: Hi, I'm currentPage 0
```
<p>Why does currentPage always return me the current page I'm on and page returns me the current and next page?</p>
<p><strong>I edit the publication</strong> to add the rest of the code. The problem is that given the result that the page parameter gives me, the call that I have inside the Prediction component, when going from one page to another, replicates the same information that I get from the service in each one, instead of putting the one that corresponds to each one:</p>
<pre class="lang-kotlin prettyprint-override"><code>@ExperimentalPagerApi
@Composable
fun Tabs(zodiacName: String?, modifier: Modifier = Modifier) {
    val viewModel = getViewModel<DetailViewModel>()
    val tabTitles = listOf("Yesterday", "Today", "Tomorrow")
    val coroutineScope = rememberCoroutineScope()
    val pageState = rememberPagerState()
    Column(
        modifier
    ) {
        TabRow(
            modifier = Modifier.fillMaxWidth(),
            selectedTabIndex = pageState.currentPage,
            backgroundColor = Color.Transparent,
            indicator = { tabPositions ->
                TabRowDefaults.Indicator(
                    color = Color.White,
                    modifier = Modifier.pagerTabIndicatorOffset(
                        pageState,
                        tabPositions
                    ),
                    height = 2.dp
                )
            }) {
            tabTitles.forEachIndexed { index, title ->
                Tab(selected = pageState.currentPage == index,
                    onClick = {
                        coroutineScope.launch {
                            pageState.animateScrollToPage(index)
                        }
                    },
                    text = {
                        Text(
                            text = title,
                            color = Color.White,
                            fontSize = 14.sp,
                            fontFamily = Helvetica
                        )
                    })
            }
        }
        HorizontalPager(count = tabTitles.size, state = pageState) {
            when (currentPage) {
                0 -> Prediction(
                    viewModel = viewModel,
                    zodiacName = zodiacName,
                    day = "yesterday"
                )
                1 -> Prediction(
                    viewModel = viewModel,
                    zodiacName = zodiacName,
                    day = "today"
                )
                2 -> Prediction(
                    viewModel = viewModel,
                    zodiacName = zodiacName,
                    day = "tomorrow"
                )
            }
        }
    }
}
</code>```

The content of the Prediction component is as follows:

@Composable
fun Prediction(viewModel: DetailViewModel, zodiacName: String?, day: String?) {
    val errorMessage = viewModel.errorMessage.value
    val horoscope = viewModel.horoscopeResponse.value
    if (errorMessage.isEmpty()) {
        LazyColumn(
            modifier = Modifier
                .padding(top = 20.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
        ) {
            item {
                LaunchedEffect(Unit) {
                    viewModel.getHoroscopeDetail(zodiacName, day)
                }
                if (horoscope.checkDescriptionContent()) {
                    PredictionCard(horoscope = horoscope)

                } else {
                    ShimmerCard()
                }
            }
        }

    } else {
        ErrorComponent(
            viewModel = viewModel,
            sign = zodiacName,
            day = day
        )
    }
}
```

Why then if I use currentPage it works fine, it makes the calls and places all the information correctly, but if I use the page parameter contained in the lambda, it duplicates the information?

答:
The HorizontalPager pre-draws a pair of adjacent pages, so that when you start scrolling, you don't have to wait for rendering.

This is exactly what happens in your logs: content is called for the first page and for the second, but currentPage is 0 in both cases.

You must always use the page parameter when creating a view within content, otherwise the view will be built on the wrong value during scrolling. When scrolling is over, the view will be recomposed with the new currentPage value, so it may look fine when scrolling fast, but if you scroll slowly, you will se the problem.

You can easily see how this works in the following example. See how I first scroll through the page without releasing my finger and currentPage shows the "wrong" number, which is updated when I release my finger and the animation ends.

```<code>HorizontalPager(
    count = 10,
) { page ->
    Column {
        Text("page $page")
        Text("currentPage $currentPage")
    }
}
</code>```

Body:
I am using this component and I was having a problem, as I don't get the same result like this:

HorizontalPager(count = tabTitles.size, state = pageState) { page ->
     Log.i("Polaris", "Hi, I'm page $page")
     Log.i("Polaris", "Hi, I'm currentPage $currentPage")
}

The result I get is:

2022-02-05 17:16:06.461 31070-31070/com.polaris I/Polaris: Hi, I'm page 0
2022-02-05 17:16:06.461 31070-31070/com.polaris I/Polaris: Hi, I'm currentPage 0
2022-02-05 17:16:06.464 31070-31070/com.polaris I/Polaris: Hi, I'm page 1
2022-02-05 17:16:06.464 31070-31070/com.polaris I/Polaris: Hi, I'm currentPage 0

Why does currentPage always return me the current page I'm on and page returns me the current and next page?

I edit the publication to add the rest of the code. The problem is that given the result that the page parameter gives me, the call that I have inside the Prediction component, when going from one page to another, replicates the same information that I get from the service in each one, instead of putting the one that corresponds to each one:

@ExperimentalPagerApi
@Composable
fun Tabs(zodiacName: String?, modifier: Modifier = Modifier) {
    val viewModel = getViewModel<DetailViewModel>()
    val tabTitles = listOf("Yesterday", "Today", "Tomorrow")
    val coroutineScope = rememberCoroutineScope()
    val pageState = rememberPagerState()
    Column(
        modifier
    ) {
        TabRow(
            modifier = Modifier.fillMaxWidth(),
            selectedTabIndex = pageState.currentPage,
            backgroundColor = Color.Transparent,
            indicator = { tabPositions ->
                TabRowDefaults.Indicator(
                    color = Color.White,
                    modifier = Modifier.pagerTabIndicatorOffset(
                        pageState,
                        tabPositions
                    ),
                    height = 2.dp
                )
            }) {
            tabTitles.forEachIndexed { index, title ->
                Tab(selected = pageState.currentPage == index,
                    onClick = {
                        coroutineScope.launch {
                            pageState.animateScrollToPage(index)
                        }
                    },
                    text = {
                        Text(
                            text = title,
                            color = Color.White,
                            fontSize = 14.sp,
                            fontFamily = Helvetica
                        )
                    })
            }
        }
        HorizontalPager(count = tabTitles.size, state = pageState) {
            when (currentPage) {
                0 -> Prediction(
                    viewModel = viewModel,
                    zodiacName = zodiacName,
                    day = "yesterday"
                )
                1 -> Prediction(
                    viewModel = viewModel,
                    zodiacName = zodiacName,
                    day = "today"
                )
                2 -> Prediction(
                    viewModel = viewModel,
                    zodiacName = zodiacName,
                    day = "tomorrow"
                )
            }
        }
    }
}

The content of the Prediction component is as follows:

@Composable
fun Prediction(viewModel: DetailViewModel, zodiacName: String?, day: String?) {
    val errorMessage = viewModel.errorMessage.value
    val horoscope = viewModel.horoscopeResponse.value
    if (errorMessage.isEmpty()) {
        LazyColumn(
            modifier = Modifier
                .padding(top = 20.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
        ) {
            item {
                LaunchedEffect(Unit) {
                    viewModel.getHoroscopeDetail(zodiacName, day)
                }
                if (horoscope.checkDescriptionContent()) {
                    PredictionCard(horoscope = horoscope)

                } else {
                    ShimmerCard()
                }
            }
        }

    } else {
        ErrorComponent(
            viewModel = viewModel,
            sign = zodiacName,
            day = day
        )
    }
}

Why then if I use currentPage it works fine, it makes the calls and places all the information correctly, but if I use the page parameter contained in the lambda, it duplicates the information?

Body:
The HorizontalPager pre-draws a pair of adjacent pages, so that when you start scrolling, you don't have to wait for rendering.

This is exactly what happens in your logs: content is called for the first page and for the second, but currentPage is 0 in both cases.

You must always use the page parameter when creating a view within content, otherwise the view will be built on the wrong value during scrolling. When scrolling is over, the view will be recomposed with the new currentPage value, so it may look fine when scrolling fast, but if you scroll slowly, you will se the problem.

You can easily see how this works in the following example. See how I first scroll through the page without releasing my finger and currentPage shows the "wrong" number, which is updated when I release my finger and the animation ends.

HorizontalPager(
    count = 10,
) { page ->
    Column {
        Text("page $page")
        Text("currentPage $currentPage")
    }
}


问:
How to disable interaction while ProgressView showing (SwiftUI)
I have a view with structure like this:

struct ContentView: View {
    @ObservedObject private var viewModel = MyViewModel()

    var body: some View {
        ZStack {
            VStack {
                // Several buttons and input forms
            }

            // the viewModel has published states.
            switch viewModel.state {
                case .loading:
                    ProgressView()
                case .finish:
                    // ...
                case .error:
                    // ...
            }
        }
    }
}

```

What I want to achieve is to simply avoid user interacting with any other components if the ProgressView appeared, but couldn't find a good way...

答:
You can use the .disabled modifier on your controls.

For example:

```<code>Button("Button") { //action }.disabled(isLoading)
</code>```

(You may want some sort convince property like this: private var isLoading : Bool { viewModel.state == .loading } )

In fact, because SwiftUI view modifiers like this will apply down to child views, you can apply it to a whole stack or group of controls:

```<code>VStack {
  //controls in here
}.disabled(isLoading)
</code>```

Body:
I have a view with structure like this:

struct ContentView: View {
    @ObservedObject private var viewModel = MyViewModel()

    var body: some View {
        ZStack {
            VStack {
                // Several buttons and input forms
            }

            // the viewModel has published states.
            switch viewModel.state {
                case .loading:
                    ProgressView()
                case .finish:
                    // ...
                case .error:
                    // ...
            }
        }
    }
}

What I want to achieve is to simply avoid user interacting with any other components if the ProgressView appeared, but couldn't find a good way...

Body:
You can use the .disabled modifier on your controls.

For example:

Button("Button") { //action }.disabled(isLoading)

(You may want some sort convince property like this: private var isLoading : Bool { viewModel.state == .loading } )

In fact, because SwiftUI view modifiers like this will apply down to child views, you can apply it to a whole stack or group of controls:

VStack {
  //controls in here
}.disabled(isLoading)


问:
How do I change the title?
I started making a Launcher for my game in c++, but I don't have any experience. (I don't want to make it in java, as I want the launcher to be accessed without java). I started up Visual Studio Code and made a new project from a template, but as I said idk how to change the title. Here is the code:

// LucaClientLauncher.cpp : Defines the entry point for the application.
//

#include "framework.h"
#include "LucaClientLauncher.h"

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;                                // current instance
WCHAR szTitle[MAX_LOADSTRING] = L"Luca Client Launcher";                  // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING] = L"Luca Client Launcher";            // the main window class name

// Forward declarations of functions included in this code module:
ATOM                MyRegisterClass(HINSTANCE hInstance);
BOOL                InitInstance(HINSTANCE, int);
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    // TODO: Place code here.

    // Initialize global strings
    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadStringW(hInstance, IDC_LUCACLIENTLAUNCHER, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

    // Perform application initialization:
    if (!InitInstance (hInstance, nCmdShow))
    {
        return FALSE;
    }

    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LUCACLIENTLAUNCHER));

    MSG msg;

    // Main message loop:
    while (GetMessage(&msg, nullptr, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}

//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEXW wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LUCACLIENTLAUNCHER));
    wcex.hCursor        = LoadCursor(nullptr, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = MAKEINTRESOURCEW(IDC_LUCACLIENTLAUNCHER);
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

    return RegisterClassExW(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   hInst = hInstance; // Store instance handle in our global variable

   HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE: Processes messages for the main window.
//
//  WM_COMMAND  - process the application menu
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_COMMAND:
        {
            int wmId = LOWORD(wParam);
            // Parse the menu selections:
            switch (wmId)
            {
            case IDM_ABOUT:
                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
                break;
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;
    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);
            // TODO: Add any drawing code that uses hdc here...
            EndPaint(hWnd, &ps);
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:
        return (INT_PTR)TRUE;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}
```

答: in your resource file (xx.rc), there is IDS_APP_TITLE in String Table section and by changing it, you can change Windows title text.</p>

Title: How do I change the title?


问:
Adding custom text to View Field type Single Line of Text not working
I am working with Dynamics and need to add custom url/text to a field via JScript.
I have tried

adding new Field creating its type as "Single line of text" and Format as "Url".

Attach the field to View with Custom Function webResource

But even adding a simple console message to the function in this field is not working.

Can someone make me understand how will it work?

答:
That kind of approach is not the one you would use to add an event inside the form (what you wrote is used only if you want to add a webresource indicator beside the column inside a view), also the use of $(document).ready is not supported inside Dynamics, specific methods exist to interact with Dynamics UI.

There are several videos on youtube on how to start with javascript development for a Dynamics instance, you can check them.


问:
How to capture the single-click or double-click on window title in JavaFX?
As we all know, when a user double-clicks on a window title bar, that window gets resized to the full available screen size. At least I have seen this happening in Mac OS. Any idea how to capture this event? What should I listen to in my code so that I know that the user has single or double-clicked the Window title?</p>

答:
Don’t try to intercept interactions with Window decorations directly

Don’t try to work with clicks. Handling state changes due to keyboard or window decoration interactions differs between OSes and isn’t a JavaFX function anyway.

Use Stage properties and API instead

Stage has a maximized property (and iconifed), listen for changes on relevant properties. Similarly, there is a full screen mode which is a bit different (see Stage Java doc).

Creating your own window decorations

If you really want complete control, you can use an undecorated stage style and add your own decorations in JavaFX for handling basic window system functions.  That way, a lot of the decoration functionality can be handled internally by your app, but I really don’t recommend that.  There was an old project named Undecorator which assisted doing this if you wanted to go that route (I don’t advise coding it yourself).


问:
Apps Script Google Calendar API Integration String Class Error
I'm super new to JavaScript, am a marketing executive by trade, but need to create a Google Calendar view from a Google Sheet for our content calendar for myself. After following some YT tutorials and finally running the code itself, I received the following error message:

Exception: The parameters (String,String,(class)) don't match the method signature for CalendarApp.Calendar.createAllDayEvent.

The following is my code:

```<code>function addEvents(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var cal = CalendarApp.getCalendarById("CalendarID");

  var data = ss.getRange("A3:C" + lr).getValues();

  for(var i = 0; i<data.length; i++){
    cal.createAllDayEvent(data[i][1], data[i][0], {description: data[i][2]});

  }

}
</code>```

In my Google Spreadsheet, the order of the data is as follows (data only appears in A3:C3 and downwards to the bottom rows): column A: Date, B: Event Title, C: Description

Hope to get some help, would appreciate it :'D

答:
You could also try:

cal.createAllDayEvent(new Date(data[i][1]), new Date(data[i][0]), {description: data[i][2]});

Body:
I'm super new to JavaScript, am a marketing executive by trade, but need to create a Google Calendar view from a Google Sheet for our content calendar for myself. After following some YT tutorials and finally running the code itself, I received the following error message:

Exception: The parameters (String,String,(class)) don't match the method signature for CalendarApp.Calendar.createAllDayEvent.

The following is my code:

function addEvents(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var cal = CalendarApp.getCalendarById("CalendarID");

  var data = ss.getRange("A3:C" + lr).getValues();

  for(var i = 0; i<data.length; i++){
    cal.createAllDayEvent(data[i][1], data[i][0], {description: data[i][2]});

  }

}

In my Google Spreadsheet, the order of the data is as follows (data only appears in A3:C3 and downwards to the bottom rows): column A: Date, B: Event Title, C: Description

Hope to get some help, would appreciate it :'D


问:
How to render variables into a target file from differnet dotenv environment files like envsubst
I have all my env vars in .env files.
They get automatically loaded when I open my shell-terminal.

I normally render shell environment variables into my target files with envsubst. similar to the example below.

What I search is a solution where I can pass a dotenv-file as well my template-file to a script which outputs the rendered result.

Something like this:

```<code>aScript --input .env.production --template template-file.yml --output result.yml
</code>```

I want to be able to parse different environment variables into my yaml. The output should be sealed via "Sealed secrets" and finally saved in the regarding kustomize folder

```<code>envsub.sh .env.staging templates/secrets/backend-secrets.yml | kubeseal -o yaml > kustomize/overlays/staging
</code>```

I hope you get the idea.

example

.env.production-file:

FOO=bar
PASSWROD=abc

content of template-file.yml

```<code>stringData:
  foo: $FOO
  password: $PASSWORD
</code>```

Then running this:

```<code>envsubst < template-file.yml > file-with-vars.yml
</code>```

the result is:

```<code>stringData:
  foo: bar
  password: abc
</code>```

My approach so far does not work because Dotenv also supports different environments like .env, .env.production, .env.staging asf..

答:
What about:

```<code>#!/bin/sh

# envsub - subsitute environment variables

env=$1
template=$2

sh -c "
. \"$env\"

cat <<EOF
$(cat "$template")
EOF"
</code>```

Usage:

```<code>./envsub .env.production template-file.yaml > result.yaml
</code>```

A here-doc with an unquoted delimiter (EOF) expands variables, whilst preserving quotes, backslashes, and other shell sequences.

sh -c is used like eval, to expand the command substitution, then run that output through a here-doc.

Be aware that this extra level of indirection creates potential for code injection, if someone can modify the yaml file.

For example, adding this:

```<code>EOF
echo malicous commands
</code>```

But it does get the result you want.

Body:
I have all my env vars in .env files.
They get automatically loaded when I open my shell-terminal.

I normally render shell environment variables into my target files with envsubst. similar to the example below.

What I search is a solution where I can pass a dotenv-file as well my template-file to a script which outputs the rendered result.

Something like this:

aScript --input .env.production --template template-file.yml --output result.yml

I want to be able to parse different environment variables into my yaml. The output should be sealed via "Sealed secrets" and finally saved in the regarding kustomize folder

envsub.sh .env.staging templates/secrets/backend-secrets.yml | kubeseal -o yaml > kustomize/overlays/staging

I hope you get the idea.

example

.env.production-file:

FOO=bar
PASSWROD=abc

content of template-file.yml

stringData:
  foo: $FOO
  password: $PASSWORD

Then running this:

envsubst < template-file.yml > file-with-vars.yml

the result is:

stringData:
  foo: bar
  password: abc

My approach so far does not work because Dotenv also supports different environments like .env, .env.production, .env.staging asf..

Body:
What about:

#!/bin/sh

# envsub - subsitute environment variables

env=$1
template=$2

sh -c "
. \"$env\"

cat <<EOF
$(cat "$template")
EOF"

Usage:

./envsub .env.production template-file.yaml > result.yaml

A here-doc with an unquoted delimiter (EOF) expands variables, whilst preserving quotes, backslashes, and other shell sequences.

sh -c is used like eval, to expand the command substitution, then run that output through a here-doc.

Be aware that this extra level of indirection creates potential for code injection, if someone can modify the yaml file.

For example, adding this:

EOF
echo malicous commands

But it does get the result you want.


问:
Why is the content rendered under the navigation menu?
There is a navigation menu that I developed in . However, the
 element I use after the  element and the  components overlap. Why does this issue occur and how do I fix this issue?

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  font-family: cabin, sans-serif;
}
header {
  display: block;
}
.primary {
  color: blue;
  font-weight: bold;
}
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 70px;
  position: fixed;
  top:0px;
  padding: 0 30px;
  background: transparent;
}
.navbar ul {
  display: flex;
}
.navbar li {
  list-style: none;
}
.navbar a {
  text-decoration: none;
  margin: 0 5px;
  padding: 10px 20px;
  font-weight: bolder;
}
.navbar a:hover{
  border-bottom: 2px blue solid;
}
.navbar a:visited{
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <!-- Navigation Menu -->
  <header>
    <div class="navbar">
        <h1 class="logo"><span class="primary">benj</span>.codes</h1>

        <ul>
          <li>Home</li>
          <li>About</li>
          <li>Projects</li>
          <li>Contact</li>
        </ul>
    </div>
  </header>

  <!-- Content -->
  <p>test</p>
</body></code>```

答:
This issue occurs in the .navbar class style position: fixed; caused by its use. In this case, the navigation menu remains fixed when the scrollbar is opened. So you can enclose other elements after the  element in a
 element; apply a margin-top style to this element and you will see all other content scroll.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  font-family: cabin, sans-serif;
}
header {
  display: block;
}
.primary {
  color: blue;
  font-weight: bold;
}
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 70px;
  /* This style applied causes the
 element to render above. */
  position: fixed;
  top:0px;
  padding: 0 30px;
  background: yellow;
}
.navbar ul {
  display: flex;
}
.navbar li {
  list-style: none;
}
.navbar a {
  text-decoration: none;
  margin: 0 5px;
  padding: 10px 20px;
  font-weight: bolder;
}
.navbar a:hover{
  border-bottom: 2px blue solid;
}
.navbar a:visited{
  color: blue;
}
/* The following style has been applied to the
 element that encloses other elements. */
.container {
  margin-top: 70px; /* To avoid shifting caused by the "position: fixed" class style */
  height: 1500px;   /* To make the scrollbar pop up */
}
p {
  height: 200px;
  border: 1px solid red;
  background-color: lightgray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <header>
    <div class="navbar">
      <h1 class="logo"><span class="primary">benj</span>.codes</h1>
      <ul>
        <li>Home</li>
        <li>About</li>
        <li>Projects</li>
        <li>Contact</li>
      </ul>
    </div>
  </header>

  <div class="container">
    <p>Content</p>
  </div>
</body></code>```

Body:
There is a navigation menu that I developed in . However, the
 element I use after the  element and the  components overlap. Why does this issue occur and how do I fix this issue?

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  font-family: cabin, sans-serif;
}
header {
  display: block;
}
.primary {
  color: blue;
  font-weight: bold;
}
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 70px;
  position: fixed;
  top:0px;
  padding: 0 30px;
  background: transparent;
}
.navbar ul {
  display: flex;
}
.navbar li {
  list-style: none;
}
.navbar a {
  text-decoration: none;
  margin: 0 5px;
  padding: 10px 20px;
  font-weight: bolder;
}
.navbar a:hover{
  border-bottom: 2px blue solid;
}
.navbar a:visited{
  color: blue;
}

benj.codes

Home

About

Projects

Contact

test

Body:
This issue occurs in the .navbar class style position: fixed; caused by its use. In this case, the navigation menu remains fixed when the scrollbar is opened. So you can enclose other elements after the <header> element in a <div> element; apply a margin-top style to this element and you will see all other content scroll.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  font-family: cabin, sans-serif;
}
header {
  display: block;
}
.primary {
  color: blue;
  font-weight: bold;
}
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 70px;
  /* This style applied causes the <p> element to render above. */
  position: fixed;
  top:0px;
  padding: 0 30px;
  background: yellow;
}
.navbar ul {
  display: flex;
}
.navbar li {
  list-style: none;
}
.navbar a {
  text-decoration: none;
  margin: 0 5px;
  padding: 10px 20px;
  font-weight: bolder;
}
.navbar a:hover{
  border-bottom: 2px blue solid;
}
.navbar a:visited{
  color: blue;
}
/* The following style has been applied to the <div> element that encloses other elements. */
.container {
  margin-top: 70px; /* To avoid shifting caused by the "position: fixed" class style */
  height: 1500px;   /* To make the scrollbar pop up */
}
p {
  height: 200px;
  border: 1px solid red;
  background-color: lightgray;
}

<body>
  <header>
    <div class="navbar">
      <h1 class="logo"><span class="primary">benj</span>.codes</h1>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
    </div>
  </header>

  <div class="container">
    <p>Content</p>
  </div>
</body>


问:
SendEmail in ASP.net shows me Syntax error, command unrecognized. The server response was: Dovecot ready
I want to send mail using ASP.NET with this code:

```<code> public void Semail(string subject, string messageBody, string toAddress)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(toAddress);
        //mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = new MailAddress("noreplykaramaoozi@eesharif.edu");
        mail.Subject = subject;
        string Body = messageBody;
        mail.Body = Body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "sina.sharif.ir"; //Or Your SMTP Server Address

        smtp.Credentials = new System.Net.NetworkCredential
            ("noreplykaramaoozi@eesharif.edu", "******");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
</code>```

But after executing i got this error :

```<code> Syntax error, command unrecognized. The server response was: Dovecot ready.
</code>```

This is the stacktrace

```<code>[SmtpException: Syntax error, command unrecognized. The server response was: Dovecot ready.]
   System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) +2176152
   System.Net.Mail.SmtpClient.Send(MailMessage message) +2188821
   Novitiate.fa.Register.btnLogin_Click(Object sender, EventArgs e) +2948
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707
</code>```

答: When using gmail smtp server and ssl be sure to use 587 port instead of 465, this solved the issue for me.</p>

Body:
I want to send mail using ASP.NET with this code:

 public void Semail(string subject, string messageBody, string toAddress)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(toAddress);
        //mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = new MailAddress("noreplykaramaoozi@eesharif.edu");
        mail.Subject = subject;
        string Body = messageBody;
        mail.Body = Body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "sina.sharif.ir"; //Or Your SMTP Server Address

        smtp.Credentials = new System.Net.NetworkCredential
            ("noreplykaramaoozi@eesharif.edu", "******");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }

But after executing i got this error :

 Syntax error, command unrecognized. The server response was: Dovecot ready.

This is the stacktrace

[SmtpException: Syntax error, command unrecognized. The server response was: Dovecot ready.]
   System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) +2176152
   System.Net.Mail.SmtpClient.Send(MailMessage message) +2188821
   Novitiate.fa.Register.btnLogin_Click(Object sender, EventArgs e) +2948
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707


问:
How to call an outer method from within a handler
So I have A MouseListener class inside a public class with a few methods.
I have attached the mouseListener to a component in the public class.

The problem is I can't figure out a simple way to call the methods in the public class, whenever I say for example this.showRemove(); the scope is from within the handler class and not the public class. Here is some example code

```<code>public class Game {

 public Game() {

  JPanel pnl = new JPanel();
  pnl.addMouseListener(new GameMouseListener());

 }

 public void showRemove(){

  //Code Here

 }

 class GameMouseListener implements MouseListener {

  public void mouseClicked(MouseEvent e) {
     this.showRemove(); //Can't Find Symbol Here

  }

 }

}
</code>```

答:
You need a reference to a Game object to be able to call the method. When you say this.showRemoved() "this" is referencing the MouseListener object instead of the Game object.

One possibility is to have the Game class extend MouseListener, and put the mouseClicked() method inside the Game class.

Body:
So I have A MouseListener class inside a public class with a few methods.
I have attached the mouseListener to a component in the public class.

The problem is I can't figure out a simple way to call the methods in the public class, whenever I say for example this.showRemove(); the scope is from within the handler class and not the public class. Here is some example code

public class Game {

 public Game() {

  JPanel pnl = new JPanel();
  pnl.addMouseListener(new GameMouseListener());

 }

 public void showRemove(){

  //Code Here

 }

 class GameMouseListener implements MouseListener {

  public void mouseClicked(MouseEvent e) {
     this.showRemove(); //Can't Find Symbol Here

  }

 }

}


问:
How can a choropleth map be combined with a shaded raster in Python?
I want to plot characteristics of areas on a map, but with very uneven population density, the larger tiles misleadingly attract attention. Think of averages (of test scores, say) by ZIP codes.

High-resolution maps are available to separate inhabited locales and even density within them. The Python code below does produce a raster colored according to the average such density for every pixel.

However, what I would really need is coloring from a choropleth map of the same area (ZIP codes of Hungary in this case) but the coloring affecting only points that would show up on the raster anyway. The raster could only determine the gamma of the pixel (or maybe height in some 3D analog). What is a good way to go about this?

A rasterio.mask.mask somehow?

(By the way, an overlay with the ZIP code boundaries would also be nice, but I have a better understanding of how that could work with GeoViews.)

```<code>import rasterio
import os
import datashader as ds
from datashader import transfer_functions as tf
import xarray as xr
from matplotlib.cm import viridis

# download a GeoTIFF from this location: https://data.humdata.org/dataset/hungary-high-resolution-population-density-maps-demographic-estimates
data_path = '~/Downloads/'
file_name = 'HUN_youth_15_24.tif'  # young people
file_path = os.path.join(data_path, file_name)
src = rasterio.open(file_path)
da = xr.open_rasterio(file_path)
cvs = ds.Canvas(plot_width=5120, plot_height=2880)
img = tf.shade(cvs.raster(da,layer=1), cmap=viridis)
ds.utils.export_image(img, "map", export_path=data_path, fmt=".png")
</code>```

答:
I am not sure if I understand, so please just tell me if I am mistaken. If I understood well, you can achieve what you want using numpy only (I am sure translating this to xarray will be easy):

# ---- snipped code already in the question -----
import numpy as np
import matplotlib.pyplot as plt

#  fake a choropleth in a dirty, fast way
height, width = 2880, 5120
choropleth = np.empty((height, width, 3,), dtype=np.uint8)
CHUNKS = 10
x_size = width // CHUNKS
for x_step, x in enumerate(range(0, width, width // CHUNKS)):
    y_size = height // CHUNKS
    for y_step, y in enumerate(range(0, height, height // CHUNKS)):
        choropleth[y: y+y_size, x: x+x_size] = (255-x_step*255//CHUNKS,
                                                0, y_step*255//CHUNKS)
plt.figure("Fake Choropleth")
plt.imshow(choropleth)

# Option 1: play with alpha only
outimage = np.empty((height, width, 4,), dtype=np.uint8)  # RGBA image
outimage[:, :, 3] = img  # Set alpha channel
outimage[:, :, :3] = choropleth  # Set color
plt.figure("Alpha filter only")
plt.imshow(outimage)

# Option 2: clear the empty points
outimage[img == 0, :3] = 0  # White. use 0 for black
plt.figure("Points erased")
plt.imshow(outimage[:,:,:3])  # change to 'outimage' to see the image with alpha
```

Results:
Dummy choroplet

Alpha filtered figure

Black background, no alpha filter

Note that the images might seem different because of matplotlib's antialiasing.

Body:
I want to plot characteristics of areas on a map, but with very uneven population density, the larger tiles misleadingly attract attention. Think of averages (of test scores, say) by ZIP codes.

High-resolution maps are available to separate inhabited locales and even density within them. The Python code below does produce a raster colored according to the average such density for every pixel.

However, what I would really need is coloring from a choropleth map of the same area (ZIP codes of Hungary in this case) but the coloring affecting only points that would show up on the raster anyway. The raster could only determine the gamma of the pixel (or maybe height in some 3D analog). What is a good way to go about this?

A rasterio.mask.mask somehow?

(By the way, an overlay with the ZIP code boundaries would also be nice, but I have a better understanding of how that could work with GeoViews.)

import rasterio
import os
import datashader as ds
from datashader import transfer_functions as tf
import xarray as xr
from matplotlib.cm import viridis

# download a GeoTIFF from this location: https://data.humdata.org/dataset/hungary-high-resolution-population-density-maps-demographic-estimates
data_path = '~/Downloads/'
file_name = 'HUN_youth_15_24.tif'  # young people
file_path = os.path.join(data_path, file_name)
src = rasterio.open(file_path)
da = xr.open_rasterio(file_path)
cvs = ds.Canvas(plot_width=5120, plot_height=2880)
img = tf.shade(cvs.raster(da,layer=1), cmap=viridis)
ds.utils.export_image(img, "map", export_path=data_path, fmt=".png")

Body:
I am not sure if I understand, so please just tell me if I am mistaken. If I understood well, you can achieve what you want using numpy only (I am sure translating this to xarray will be easy):

# ---- snipped code already in the question -----
import numpy as np
import matplotlib.pyplot as plt

#  fake a choropleth in a dirty, fast way
height, width = 2880, 5120
choropleth = np.empty((height, width, 3,), dtype=np.uint8)
CHUNKS = 10
x_size = width // CHUNKS
for x_step, x in enumerate(range(0, width, width // CHUNKS)):
    y_size = height // CHUNKS
    for y_step, y in enumerate(range(0, height, height // CHUNKS)):
        choropleth[y: y+y_size, x: x+x_size] = (255-x_step*255//CHUNKS,
                                                0, y_step*255//CHUNKS)
plt.figure("Fake Choropleth")
plt.imshow(choropleth)

# Option 1: play with alpha only
outimage = np.empty((height, width, 4,), dtype=np.uint8)  # RGBA image
outimage[:, :, 3] = img  # Set alpha channel
outimage[:, :, :3] = choropleth  # Set color
plt.figure("Alpha filter only")
plt.imshow(outimage)

# Option 2: clear the empty points
outimage[img == 0, :3] = 0  # White. use 0 for black
plt.figure("Points erased")
plt.imshow(outimage[:,:,:3])  # change to 'outimage' to see the image with alpha

Results:
Dummy choroplet

Alpha filtered figure

Black background, no alpha filter

Note that the images might seem different because of matplotlib's antialiasing.


问:
Lifetime does not live long enough
There is a code that produces the following error:

fn foo<'a, F1, F2>(f: F1)
    where
        F1: FnOnce(&'a mut i32) -> F2,
        F2: FnOnce() + 'a,
{
    let mut a = 0;
    f(&mut a)();
}

fn main() {
    foo(|a| {
        || {
            *a += 1;
            ()
        }
    });
}
```
```error[E0597]: `a` does not live long enough
 --> src/main.rs:7:7
  |
1 | fn foo<'a, F1, F2>(f: F1)
  |        -- lifetime `'a` defined here
...
7 |     f(&mut a)();
  |     --^^^^^^-
  |     | |
  |     | borrowed value does not live long enough
  |     argument requires that `a` is borrowed for `'a`
8 | }
  | - `a` dropped here while still borrowed
```

I'm very confused because error message says that a is still borrowed but foo returns nothing!

答:
Your code has two issues:

a Lifetime issue

it tries to return a closure

1. The lifetime issue

You can reduce the example in your question to

```<code>fn foo<'a, F1>(f: F1)
where
    F1: FnOnce(&'a mut i32),
{
    let mut a = 0;
    f(&mut a);
}

fn main() {
    foo(|a| {
            *a += 1;
    });
}
</code>```

and here you can probably see more clearly, that

```<code>fn foo<'a, F1>(f: F1)
where
    F1: FnOnce(&'a mut i32)
</code>```

means, that the caller of foo can decide, what 'a
will be.

But in

```<code>let mut a = 0;
f(&mut a);
</code>```

you create a, which has its concrete lifetime (essentially
the body of foo) and try to call f with it. But 'a which
the caller has chosen, doesn't need to have to do anything
with the lifetime of a, it can be wildly larger for example.

Worded differently

```<code>    fn foo<'a, F1>(f: F1)
    where
        F1: FnOnce(&'a mut i32)
</code>```

means: If you call foo you can hand it something function
like f (function pointer, closure, ...), which needs its parameter
to live at least as long as 'a. 'a could be 'static
for example.

So inside foo you can't just create a thing with its concrete
lifetime and hand if to f, as you don't know, what 'a the
caller of foo will choose.

You might now be surprised, that

```<code>fn foo<F1>(f: F1)
    where
        F1: FnOnce(&mut i32),
{
    let mut a = 0;
    f(&mut a);
}

fn main() {
    foo(|a| {
            *a += 1;
    });
}
</code>```

compiles just fine, but that is simply, because foo in this example desugars to

```<code>fn foo<F1>(f: F1)
    where
        F1: for<'a> FnOnce(&'a mut i32),
{
    let mut a = 0;
    f(&mut a);
}
</code>```

which means, that not the caller of foo decides, what the lifetime 'a will be, but f has to be something, that can work with a parameter of any lifetime. So foo can choose 'a in this case.

But to be able to return anything, which has the lifetime 'a chosen by foo, you would need to be able to write it into foos signature, which you can't, to the best of my knowledge.

2. it tries to return a closure

The Rust Book, "Returning Closures" tells us, you can't
return closures.

But

```<code>fn returns_closure(a: &mut i32) -> impl FnMut() + '_ {
    || {
      *a += 1;
      println!("{}", *a);
    }
}

fn main() {
  let mut sum: i32 = 5;
  let mut f = returns_closure(&mut sum);
  f();
  f();

  let mut sum2: i32 = 10;
  let mut g = returns_closure(&mut sum2);
  g();
  g();
}
</code>```

just works fine for me on rustc version 1.58.1.

The Rust Book, "Returning Types that Implement Traits" tells us that you can use the
impl SomeTrait syntax only in return types of functions and methods, which
always return the same concrete type on all function exits.

So the above syntax doesn't apply to closures.

But with generic types we can still do something similar.

```<code>fn foo<F1, F2>(f: &mut F1)
where
    F1: FnMut(i32) -> F2,
    F2: FnMut(),
{
    let mut g = f(1);
    g();
    g();
    let mut h = f(2);
    h();
    h();
}

fn main() {
    foo(&mut (|_a: i32| || println!("wtf")));
    foo(&mut (|_a: i32| {
        let mut a = 5;
        move || {
            a += 1;
            println!("wtf: {}", a);
        }
    }));
}
</code>```

still works fine for me. So it seems as long as the compiler can
figure out the concrete types and the closure returning a closures
also always returns the same concrete type, it works for
rustc 1.58.1.

So my guess is, the syntax simply lacks. There needs to be
some syntax to write something like the following pseudo code:

```<code>fn foo<F1, F2>(f: &mut F1)
where
    F2: FnMut(),
    F1: for<'a> FnMut(&'a mut i32) -> F2 + 'a,
{
    ...
}
</code>```

I guess the lifetime bound is part of the type at the moment and so
the caller, which chooses F2 would need to know the required lifetime,
that gets choosen in the call ... but thats just guessing.

As the required lifetime bound shouldn't influence the size
needed for the closure returned by f,
something like that might be possible?

In

```<code>fn foo2<F1>(f: &mut F1)
where
    F1: for<'a> FnMut(&'a mut i32) -> Box<dyn FnMut() + 'a>,
{
    ...
}
</code>```

we can neatly express what we want at the unfortunate cost of allocating ...
But now f can of course return different closures with different types
wrapped up in the Box, so it is also more flexible.

Title: Lifetime does not live long enough

Body:
There is a code that produces the following error:

fn foo<'a, F1, F2>(f: F1)
    where
        F1: FnOnce(&'a mut i32) -> F2,
        F2: FnOnce() + 'a,
{
    let mut a = 0;
    f(&mut a)();
}

fn main() {
    foo(|a| {
        || {
            *a += 1;
            ()
        }
    });
}

error[E0597]: `a` does not live long enough
 --> src/main.rs:7:7
  |
1 | fn foo<'a, F1, F2>(f: F1)
  |        -- lifetime `'a` defined here
...
7 |     f(&mut a)();
  |     --^^^^^^-
  |     | |
  |     | borrowed value does not live long enough
  |     argument requires that `a` is borrowed for `'a`
8 | }
  | - `a` dropped here while still borrowed

I'm very confused because error message says that a is still borrowed but foo returns nothing!

Body:
Your code has two issues:

a Lifetime issue

it tries to return a closure

1. The lifetime issue

You can reduce the example in your question to

fn foo<'a, F1>(f: F1)
where
    F1: FnOnce(&'a mut i32),
{
    let mut a = 0;
    f(&mut a);
}

fn main() {
    foo(|a| {
            *a += 1;
    });
}

and here you can probably see more clearly, that

fn foo<'a, F1>(f: F1)
where
    F1: FnOnce(&'a mut i32)

means, that the caller of foo can decide, what 'a
will be.

But in

let mut a = 0;
f(&mut a);

you create a, which has its concrete lifetime (essentially
the body of foo) and try to call f with it. But 'a which
the caller has chosen, doesn't need to have to do anything
with the lifetime of a, it can be wildly larger for example.

Worded differently

    fn foo<'a, F1>(f: F1)
    where
        F1: FnOnce(&'a mut i32)

means: If you call foo you can hand it something function
like f (function pointer, closure, ...), which needs its parameter
to live at least as long as 'a. 'a could be 'static
for example.

So inside foo you can't just create a thing with its concrete
lifetime and hand if to f, as you don't know, what 'a the
caller of foo will choose.

You might now be surprised, that

fn foo<F1>(f: F1)
    where
        F1: FnOnce(&mut i32),
{
    let mut a = 0;
    f(&mut a);
}

fn main() {
    foo(|a| {
            *a += 1;
    });
}

compiles just fine, but that is simply, because foo in this example desugars to

fn foo<F1>(f: F1)
    where
        F1: for<'a> FnOnce(&'a mut i32),
{
    let mut a = 0;
    f(&mut a);
}

which means, that not the caller of foo decides, what the lifetime 'a will be, but f has to be something, that can work with a parameter of any lifetime. So foo can choose 'a in this case.

But to be able to return anything, which has the lifetime 'a chosen by foo, you would need to be able to write it into foos signature, which you can't, to the best of my knowledge.

2. it tries to return a closure

The Rust Book, "Returning Closures" tells us, you can't
return closures.

But

fn returns_closure(a: &mut i32) -> impl FnMut() + '_ {
    || {
      *a += 1;
      println!("{}", *a);
    }
}

fn main() {
  let mut sum: i32 = 5;
  let mut f = returns_closure(&mut sum);
  f();
  f();

  let mut sum2: i32 = 10;
  let mut g = returns_closure(&mut sum2);
  g();
  g();
}

just works fine for me on rustc version 1.58.1.

The Rust Book, "Returning Types that Implement Traits" tells us that you can use the
impl SomeTrait syntax only in return types of functions and methods, which
always return the same concrete type on all function exits.

So the above syntax doesn't apply to closures.

But with generic types we can still do something similar.

fn foo<F1, F2>(f: &mut F1)
where
    F1: FnMut(i32) -> F2,
    F2: FnMut(),
{
    let mut g = f(1);
    g();
    g();
    let mut h = f(2);
    h();
    h();
}

fn main() {
    foo(&mut (|_a: i32| || println!("wtf")));
    foo(&mut (|_a: i32| {
        let mut a = 5;
        move || {
            a += 1;
            println!("wtf: {}", a);
        }
    }));
}

still works fine for me. So it seems as long as the compiler can
figure out the concrete types and the closure returning a closures
also always returns the same concrete type, it works for
rustc 1.58.1.

So my guess is, the syntax simply lacks. There needs to be
some syntax to write something like the following pseudo code:

fn foo<F1, F2>(f: &mut F1)
where
    F2: FnMut(),
    F1: for<'a> FnMut(&'a mut i32) -> F2 + 'a,
{
    ...
}

I guess the lifetime bound is part of the type at the moment and so
the caller, which chooses F2 would need to know the required lifetime,
that gets choosen in the call ... but thats just guessing.

As the required lifetime bound shouldn't influence the size
needed for the closure returned by f,
something like that might be possible?

In

fn foo2<F1>(f: &mut F1)
where
    F1: for<'a> FnMut(&'a mut i32) -> Box<dyn FnMut() + 'a>,
{
    ...
}

we can neatly express what we want at the unfortunate cost of allocating ...
But now f can of course return different closures with different types
wrapped up in the Box, so it is also more flexible.


问:
how can i loop this code to make a pattern?
***I have an assignment to create a tile pattern. I finished the pattern, but I am struggling to get the code to repeat. I need to be able to run it with the following specs:

```<code>column_ct=10,row_ct=10
column_ct=16,row_ct=9
column_ct=100,row_ct=100
</code>```

with column_ct and row_ct referring to the number of columns and rows respectively.
my code is pretty simple as I am very new to coding.
If someone could give me advice on how to implement my code into a loop, I would be very grateful.
Here is my code:***

```<code>import turtle

def tile():
    t = turtle.Turtle()

    t.fillcolor("black")
    t.begin_fill()
    t.circle(20)
    t.end_fill()

    t.penup()
    t.back(30)
    t.fillcolor("red")
    t.pendown()
    t.begin_fill()
    t.circle(50)
    t.end_fill()

    t.penup()
    t.back(50)
    t.pendown()
    t.forward(100)  # Forward turtle by 100 units
    t.left(90)  # Turn turtle by 90 degree
    t.forward(100)
    t.left(90)
    t.forward(100)
    t.left(90)
    t.forward(100)
    t.left(90)

column_ct= 10

row_ct=10

def tile_repeat (column_ct, row_ct,):
    for r in range(row_ct):
        for y in range(column_ct):
            tile()
            t.penup()
            t.forward(100)
            t.pendown

tile_repeat(10, 10)
turtle.done()
</code>```

答:
To loop the pattern into a grid shape you can do:

```<code>def tile_repeat (column_ct, row_ct,):
    t = turtle.Turtle()
    for r in range(row_ct):
        for y in range(column_ct):
            tile(t) # passing the turtle object to the function
            t.penup()
            t.forward(180)
            t.pendown()
        # return to left most part of drawings
        t.penup()
        t.right(180)
        t.forward(100*column_ct)
        # go down one row
        t.left(90)
        t.forward(100 )
        t.left(90)
        t.pendown()

tile_repeat(3, 3)
turtle.done()
</code>```

Using this you have to pass the t variable to your function

```<code>def tile(t):
</code>```

and remove the

```<code>t = turtle.Turtle()
</code>```

inside of tile()

Body:
***I have an assignment to create a tile pattern. I finished the pattern, but I am struggling to get the code to repeat. I need to be able to run it with the following specs:

column_ct=10,row_ct=10
column_ct=16,row_ct=9
column_ct=100,row_ct=100

with column_ct and row_ct referring to the number of columns and rows respectively.
my code is pretty simple as I am very new to coding.
If someone could give me advice on how to implement my code into a loop, I would be very grateful.
Here is my code:***

import turtle

def tile():
    t = turtle.Turtle()

    t.fillcolor("black")
    t.begin_fill()
    t.circle(20)
    t.end_fill()

    t.penup()
    t.back(30)
    t.fillcolor("red")
    t.pendown()
    t.begin_fill()
    t.circle(50)
    t.end_fill()

    t.penup()
    t.back(50)
    t.pendown()
    t.forward(100)  # Forward turtle by 100 units
    t.left(90)  # Turn turtle by 90 degree
    t.forward(100)
    t.left(90)
    t.forward(100)
    t.left(90)
    t.forward(100)
    t.left(90)

column_ct= 10

row_ct=10

def tile_repeat (column_ct, row_ct,):
    for r in range(row_ct):
        for y in range(column_ct):
            tile()
            t.penup()
            t.forward(100)
            t.pendown

tile_repeat(10, 10)
turtle.done()

Body:
To loop the pattern into a grid shape you can do:

def tile_repeat (column_ct, row_ct,):
    t = turtle.Turtle()
    for r in range(row_ct):
        for y in range(column_ct):
            tile(t) # passing the turtle object to the function
            t.penup()
            t.forward(180)
            t.pendown()
        # return to left most part of drawings
        t.penup()
        t.right(180)
        t.forward(100*column_ct)
        # go down one row
        t.left(90)
        t.forward(100 )
        t.left(90)
        t.pendown()

tile_repeat(3, 3)
turtle.done()

Using this you have to pass the t variable to your function

def tile(t):

and remove the

t = turtle.Turtle()

inside of tile()


问:
Material UI Responsive based Appbar covering over main contect? How can I fix this?
I am trying to write out a website with responsive-based app bar with a drawer tagged onto it. I am using this design found at https://medium.com/@tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69 and modifying it accordingly. But unfortunately, I am getting this issue, in which the drawer covers the portion of the content trying to be displayed. Please know that I have seen similar questions on this site, but I couldn't figure out how to solve them or the answers were kind of vague. Any help would be much appreciated, please let me know if I need to clarify anything further. All of this is using Material UI components.

Here is my code:

Material UI App-Bar

//Used code: https://medium.com/@tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69

//Picture/Icon Imports
import home from "../Icons/home.png";
import about from "../Icons/about.png";
import contact from "../Icons/contact.png";
import resume from "../Icons/resume.png";
import minecraft from "../Icons/minecraft.png";
import github from "../Icons/github.png"

import React from 'react';
import PropTypes from 'prop-types';
import AppBar from '@material-ui/core/AppBar';
import CssBaseline from '@material-ui/core/CssBaseline';
import Drawer from '@material-ui/core/Drawer';
import Hidden from '@material-ui/core/Hidden';
import IconButton from '@material-ui/core/IconButton';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import MenuIcon from '@material-ui/icons/Menu';
import CloseIcon from '@material-ui/icons/Close';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {Link} from "react-router-dom";
const drawerWidth = 240;

const useStyles = makeStyles(theme => ({
    root: {
        display: 'flex',
    },
    drawer: {
        [theme.breakpoints.up('sm')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },
    appBar: {
        zIndex: theme.zIndex.drawer + 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
        [theme.breakpoints.up('sm')]: {
            display: 'none',
        },
    },
    toolbar: theme.mixins.toolbar,
    drawerPaper: {
        width: drawerWidth
    },
    content: {
        flexGrow: 1,
        padding: theme.spacing(0),
    },
    closeMenuButton: {
        marginRight: 'auto',
        marginLeft: 0,
    },
}));
function NavBar() {
    const DifferentPages = [
        {Text: "Home", location: "/", Image: home},
        {Text: "About", location: "/about", Image: about},
        {Text: "Contact", location: "/contact", Image: contact},
        {Text: "Resume", location: "/resume", Image: resume},
        {Text: "Minecraft", location: "/minecraft", Image: minecraft},
    ]

    const classes = useStyles();
    const theme = useTheme();
    const [mobileOpen, setMobileOpen] = React.useState(false);
    function handleDrawerToggle() {
        setMobileOpen(!mobileOpen)
    }
    const drawer = (

            <List>
                {DifferentPages.map((Text) => (
                    <ListItem button component={Link} to={Text.location}>

                        <ListItemText primary={Text.Text} />
                    </ListItem>
                ))}
                <ListItem button href={"example.com"}>

                    <ListItemText>
                        Github
                    </ListItemText>
                </ListItem>
            </List>

    );
    return (

            <CssBaseline />
            <AppBar position="fixed" className={classes.appBar}>
                <Toolbar>
                    <IconButton
                        color="inherit"
                        aria-label="Open drawer"
                        edge="start"
                        onClick={handleDrawerToggle}
                        className={classes.menuButton}
                    >
                        <MenuIcon />
                    </IconButton>
                    <Typography variant="h6" noWrap>
                        Responsive drawer
                    </Typography>
                </Toolbar>
            </AppBar>

                <Hidden smUp implementation="css">
                    <Drawer
                        variant="temporary"
                        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
                        open={mobileOpen}
                        onClose={handleDrawerToggle}
                        classes={{
                            paper: classes.drawerPaper,
                        }}
                        ModalProps={{
                            keepMounted: true, // Better open performance on mobile.
                        }}
                    >
                        <IconButton onClick={handleDrawerToggle} className={classes.closeMenuButton}>
                            <CloseIcon/>
                        </IconButton>
                        {drawer}
                    </Drawer>
                </Hidden>
                <Hidden xsDown implementation="css">
                    <Drawer
                        className={classes.drawer}
                        variant="permanent"
                        classes={{
                            paper: classes.drawerPaper,
                        }}
                    >

                        {drawer}
                    </Drawer>
                </Hidden>

    );
}
NavBar.propTypes = {
    container: PropTypes.object,
};
export default NavBar;```
</div>
</div>
</p>
<p>App.js: NOTE** in App.js, I can add style={{paddingleft:240}} to the div before routes and it kind of remedy this issue, however, once the screen is small enough (i.e.like mobile) view and the drawer is hidden, 240px padding is still there.
(edited down for simplicity - content still the same)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import './App.css';
import { HashRouter as Router, Routes, Route} from 'react-router-dom';

//Page Routes
import NavigationAppBar from "./Navigation-Bar/NavigationAppBar";
import Home from './Page-Information/main';

function App() {
    return (
        <Router>
            <NavigationAppBar/>
            <div>
                <Routes>
                    <Route exact path='/' exact element={<Home />} />
                </Routes>
            </div>
        </Router>
    );
}

export default App;</code>```

Home.js: (edited down for simplicity - content still the same)

import React from 'react';

const Home = () => {
    return (

Example

    );
};

export default Home;```

答:
You can add breakpoint for smaller device to remove margin or padding as appropriate.</p>
```<code>const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })(
  ({ theme, open }) => ({
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    }),
    marginLeft: `-${drawerWidth}px`,
    ...(open && {
      transition: theme.transitions.create("margin", {
        easing: theme.transitions.easing.easeOut,
        duration: theme.transitions.duration.enteringScreen
      }),
      marginLeft: 0
    }),
    [theme.breakpoints.down('sm')]: {
      //add CSS here.
    }

  })
);
</code>```

Body:
I am trying to write out a website with responsive-based app bar with a drawer tagged onto it. I am using this design found at https://medium.com/@tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69 and modifying it accordingly. But unfortunately, I am getting this issue, in which the drawer covers the portion of the content trying to be displayed. Please know that I have seen similar questions on this site, but I couldn't figure out how to solve them or the answers were kind of vague. Any help would be much appreciated, please let me know if I need to clarify anything further. All of this is using Material UI components.

Here is my code:

Material UI App-Bar

//Used code: https://medium.com/@tsubasakondo_36683/create-responsive-drawer-menu-with-react-material-ui-617a42764b69

//Picture/Icon Imports
import home from "../Icons/home.png";
import about from "../Icons/about.png";
import contact from "../Icons/contact.png";
import resume from "../Icons/resume.png";
import minecraft from "../Icons/minecraft.png";
import github from "../Icons/github.png"

import React from 'react';
import PropTypes from 'prop-types';
import AppBar from '@material-ui/core/AppBar';
import CssBaseline from '@material-ui/core/CssBaseline';
import Drawer from '@material-ui/core/Drawer';
import Hidden from '@material-ui/core/Hidden';
import IconButton from '@material-ui/core/IconButton';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import MenuIcon from '@material-ui/icons/Menu';
import CloseIcon from '@material-ui/icons/Close';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {Link} from "react-router-dom";
const drawerWidth = 240;

const useStyles = makeStyles(theme => ({
    root: {
        display: 'flex',
    },
    drawer: {
        [theme.breakpoints.up('sm')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },
    appBar: {
        zIndex: theme.zIndex.drawer + 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
        [theme.breakpoints.up('sm')]: {
            display: 'none',
        },
    },
    toolbar: theme.mixins.toolbar,
    drawerPaper: {
        width: drawerWidth
    },
    content: {
        flexGrow: 1,
        padding: theme.spacing(0),
    },
    closeMenuButton: {
        marginRight: 'auto',
        marginLeft: 0,
    },
}));
function NavBar() {
    const DifferentPages = [
        {Text: "Home", location: "/", Image: home},
        {Text: "About", location: "/about", Image: about},
        {Text: "Contact", location: "/contact", Image: contact},
        {Text: "Resume", location: "/resume", Image: resume},
        {Text: "Minecraft", location: "/minecraft", Image: minecraft},
    ]

    const classes = useStyles();
    const theme = useTheme();
    const [mobileOpen, setMobileOpen] = React.useState(false);
    function handleDrawerToggle() {
        setMobileOpen(!mobileOpen)
    }
    const drawer = (

            <List>
                {DifferentPages.map((Text) => (
                    <ListItem button component={Link} to={Text.location}>

                        <ListItemText primary={Text.Text} />
                    </ListItem>
                ))}
                <ListItem button href={"example.com"}>

                    <ListItemText>
                        Github
                    </ListItemText>
                </ListItem>
            </List>

    );
    return (

            <CssBaseline />
            <AppBar position="fixed" className={classes.appBar}>
                <Toolbar>
                    <IconButton
                        color="inherit"
                        aria-label="Open drawer"
                        edge="start"
                        onClick={handleDrawerToggle}
                        className={classes.menuButton}
                    >
                        <MenuIcon />
                    </IconButton>
                    <Typography variant="h6" noWrap>
                        Responsive drawer
                    </Typography>
                </Toolbar>
            </AppBar>

                <Hidden smUp implementation="css">
                    <Drawer
                        variant="temporary"
                        anchor={theme.direction === 'rtl' ? 'right' : 'left'}
                        open={mobileOpen}
                        onClose={handleDrawerToggle}
                        classes={{
                            paper: classes.drawerPaper,
                        }}
                        ModalProps={{
                            keepMounted: true, // Better open performance on mobile.
                        }}
                    >
                        <IconButton onClick={handleDrawerToggle} className={classes.closeMenuButton}>
                            <CloseIcon/>
                        </IconButton>
                        {drawer}
                    </Drawer>
                </Hidden>
                <Hidden xsDown implementation="css">
                    <Drawer
                        className={classes.drawer}
                        variant="permanent"
                        classes={{
                            paper: classes.drawerPaper,
                        }}
                    >

                        {drawer}
                    </Drawer>
                </Hidden>

    );
}
NavBar.propTypes = {
    container: PropTypes.object,
};
export default NavBar;

App.js: NOTE** in App.js, I can add style={{paddingleft:240}} to the div before routes and it kind of remedy this issue, however, once the screen is small enough (i.e.like mobile) view and the drawer is hidden, 240px padding is still there.
(edited down for simplicity - content still the same)

import React from 'react';
import './App.css';
import { HashRouter as Router, Routes, Route} from 'react-router-dom';

//Page Routes
import NavigationAppBar from "./Navigation-Bar/NavigationAppBar";
import Home from './Page-Information/main';

function App() {
    return (
        <Router>
            <NavigationAppBar/>

                <Routes>
                    <Route exact path='/' exact element={<Home />} />
                </Routes>

        </Router>
    );
}

export default App;

Home.js: (edited down for simplicity - content still the same)

import React from 'react';

const Home = () => {
    return (

Example

    );
};

export default Home;

Body:
You can add breakpoint for smaller device to remove margin or padding as appropriate.

const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })(
  ({ theme, open }) => ({
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    }),
    marginLeft: `-${drawerWidth}px`,
    ...(open && {
      transition: theme.transitions.create("margin", {
        easing: theme.transitions.easing.easeOut,
        duration: theme.transitions.duration.enteringScreen
      }),
      marginLeft: 0
    }),
    [theme.breakpoints.down('sm')]: {
      //add CSS here.
    }

  })
);