答:
It would be hard for you to configure the same function to send_mail again to send OTP, as you said this sends the email when the user gets registered. So why not modify the verifyEmail itself.

First, you don't need a user instance here as the user is already authenticated and you already have the User Id.

So in the else statement of verifyEmail, you can send_email without calling send_email_otp() function.

Update the verifyEmail to.

```<code>@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def verifyEmail(request, pk):

    user = CustomUser.objects.get(id=pk)

    data = request.data
    otp_to_verify = data['otpForEmail']

    if otp_to_verify == user.otpForEmail:
        user.isEmailVerified = True

        user.save()
        message = {'detail': 'Your email is now verified'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        subject = "Your email needs to be verified to use site "
        message = f'Hi, Dear {user.name} use this following OTP to Get verified your email : OTP({user.otpForEmail})'

        email_from = settings.EMAIL_HOST_USER
        recipient_list = [user.email]
        send_mail(subject, message, email_from, recipient_list)
        print(f"Email Sent to {user.email}")
        message = {
            'detail': 'OTP is not valid and expired, Use New OTP which we have sent you on the email'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
</code>```

Title: How to merge a function into another

Body:
It would be hard for you to configure the same function to send_mail again to send OTP, as you said this sends the email when the user gets registered. So why not modify the verifyEmail itself.

First, you don't need a user instance here as the user is already authenticated and you already have the User Id.

So in the else statement of verifyEmail, you can send_email without calling send_email_otp() function.

Update the verifyEmail to.

@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def verifyEmail(request, pk):

    user = CustomUser.objects.get(id=pk)

    data = request.data
    otp_to_verify = data['otpForEmail']

    if otp_to_verify == user.otpForEmail:
        user.isEmailVerified = True

        user.save()
        message = {'detail': 'Your email is now verified'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)
    else:
        subject = "Your email needs to be verified to use site "
        message = f'Hi, Dear {user.name} use this following OTP to Get verified your email : OTP({user.otpForEmail})'

        email_from = settings.EMAIL_HOST_USER
        recipient_list = [user.email]
        send_mail(subject, message, email_from, recipient_list)
        print(f"Email Sent to {user.email}")
        message = {
            'detail': 'OTP is not valid and expired, Use New OTP which we have sent you on the email'}
        return Response(message, status=status.HTTP_400_BAD_REQUEST)


来源: stackexchange

问:
Parsing out data from pytest assert and converting into a string
I want to collect data about test to an external database, where I would collect all assert and parse the expected value versus the actual result.

To describe what I want in code:

```<code>test_something.py:

def test_me_1(send_to_test):
    """
    Docstring to pad even more
    """
    x,y = send_to_test(3)
    assert x == 3**2
    assert y == 3**3
    assert y == 3**2 # I want this to fail intentionally

conftest.py:

@pytest.fixture(scope='function')
def send_to_test() -> Callable:
    return lambda x: (x ** 2, x ** 3)

</code>```

The data I want to collect is (Any other way is fine as long as I get this data):

```<code>test_data = [{'func': 'test_me_1', 'variable': 'x', 'expected_value': 9, 'actual_value': 9},
             {'func': 'test_me_1', 'variable': 'y', 'expected_value': 27, 'actual_value': 27},
             {'func': 'test_me_1', 'variable': 'y', 'expected_value': 27, 'actual_value': 9}]
</code>```

My current idea is a wrapper, that can easily be implemented to existing test and will collect the assert statements and their value.

Collecting the number of assert statements is straightforward if I use AST, but these are good only for static analysis.
I've also tried to use the inspect module, but have hard time figuring out how to use it for this purpose

My poor attempt thus far (print statements are temporary since I want to collect the data)

```<code>def get_this(func: Callable):
    @functools.wraps(func)
    def wrapper(*arg, **kwargs):
        print(func.__name__)
        func_content = inspect.getsource(func)
        func_root = ast.parse(func_content)
        for node in func_root.body:
            for content in node.body:
                if isinstance(content, ast.Assert):
                    print(content)
        return func(*arg, **kwargs)

    return wrapper
</code>```

答:
You could try this:

import inspect
import json
from typing import Callable

import pytest

@pytest.fixture(scope="function")
def send_to_test() -> Callable:
    return lambda x: (x ** 2, x ** 3)

# Helper function to run and monitor a test
def run_test(test_func, variable, expected_value, actual_value, data):
    try:
        with open("./data.json", "r") as f:
            data = json.load(f)
    except FileNotFoundError:
        data = []

    data.append(
        {
            "func": test_func,
            "variable": variable,
            "expected_value": expected_value,
            "actual_value": actual_value,
        }
    )
    with open("./data.json", "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

    assert actual_value == expected_value

# Reformatted tests
def test_me_1(send_to_test):
    # setup
    data = []
    x, y = send_to_test(3)

    # tests
    run_test(
        test_func=inspect.stack()[0][3],
        variable="x",
        expected_value=3 ** 2,
        actual_value=x,
        data=data,
    )
    run_test(
        test_func=inspect.stack()[0][3],
        variable="y",
        expected_value=3 ** 3,
        actual_value=y,
        data=data,
    )
    run_test(
        test_func=inspect.stack()[0][3],
        variable="y",
        expected_value=3 ** 2,
        actual_value=y,
        data=data,
    )
```
<p>And so, when you run pytest, a new <code>data.json</code>file is created with the expected  content:</p>
<pre class="lang-json prettyprint-override"><code>[
    {
        "func": "test_me_1",
        "variable": "x",
        "expected_value": 9,
        "actual_value": 9
    },
    {
        "func": "test_me_1",
        "variable": "y",
        "expected_value": 27,
        "actual_value": 27
    },
    {
        "func": "test_me_1",
        "variable": "y",
        "expected_value": 9,
        "actual_value": 27
    }
]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to collect data about test to an external database, where I would collect all assert and parse the expected value versus the actual result.

To describe what I want in code:

test_something.py:

def test_me_1(send_to_test):
    """
    Docstring to pad even more
    """
    x,y = send_to_test(3)
    assert x == 3**2
    assert y == 3**3
    assert y == 3**2 # I want this to fail intentionally

conftest.py:

@pytest.fixture(scope='function')
def send_to_test() -> Callable:
    return lambda x: (x ** 2, x ** 3)

The data I want to collect is (Any other way is fine as long as I get this data):

test_data = [{'func': 'test_me_1', 'variable': 'x', 'expected_value': 9, 'actual_value': 9},
             {'func': 'test_me_1', 'variable': 'y', 'expected_value': 27, 'actual_value': 27},
             {'func': 'test_me_1', 'variable': 'y', 'expected_value': 27, 'actual_value': 9}]

My current idea is a wrapper, that can easily be implemented to existing test and will collect the assert statements and their value.

Collecting the number of assert statements is straightforward if I use AST, but these are good only for static analysis.
I've also tried to use the inspect module, but have hard time figuring out how to use it for this purpose

My poor attempt thus far (print statements are temporary since I want to collect the data)

def get_this(func: Callable):
    @functools.wraps(func)
    def wrapper(*arg, **kwargs):
        print(func.__name__)
        func_content = inspect.getsource(func)
        func_root = ast.parse(func_content)
        for node in func_root.body:
            for content in node.body:
                if isinstance(content, ast.Assert):
                    print(content)
        return func(*arg, **kwargs)

    return wrapper

Body:
You could try this:

import inspect
import json
from typing import Callable

import pytest

@pytest.fixture(scope="function")
def send_to_test() -> Callable:
    return lambda x: (x ** 2, x ** 3)

# Helper function to run and monitor a test
def run_test(test_func, variable, expected_value, actual_value, data):
    try:
        with open("./data.json", "r") as f:
            data = json.load(f)
    except FileNotFoundError:
        data = []

    data.append(
        {
            "func": test_func,
            "variable": variable,
            "expected_value": expected_value,
            "actual_value": actual_value,
        }
    )
    with open("./data.json", "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

    assert actual_value == expected_value

# Reformatted tests
def test_me_1(send_to_test):
    # setup
    data = []
    x, y = send_to_test(3)

    # tests
    run_test(
        test_func=inspect.stack()[0][3],
        variable="x",
        expected_value=3 ** 2,
        actual_value=x,
        data=data,
    )
    run_test(
        test_func=inspect.stack()[0][3],
        variable="y",
        expected_value=3 ** 3,
        actual_value=y,
        data=data,
    )
    run_test(
        test_func=inspect.stack()[0][3],
        variable="y",
        expected_value=3 ** 2,
        actual_value=y,
        data=data,
    )

And so, when you run pytest, a new data.jsonfile is created with the expected  content:

[
    {
        "func": "test_me_1",
        "variable": "x",
        "expected_value": 9,
        "actual_value": 9
    },
    {
        "func": "test_me_1",
        "variable": "y",
        "expected_value": 27,
        "actual_value": 27
    },
    {
        "func": "test_me_1",
        "variable": "y",
        "expected_value": 9,
        "actual_value": 27
    }
]


问:
my code for linked list is printing address in python
```<code>class Node:

    def __init__(self, data = None, next = None):
        self.data = data
        self.next = next

class link:

    def __init__(self):
        self.head = None

    def insert_begining(self, data):
       node = Node(data, self.head)
       self.head = node

    def print(self):

        itr = self.head
        space = ''

        while itr:
            space += str(itr.next) + '-->'
            itr = itr.next
        print(space)

if __name__ == '__main__':
    root = link()

    root.insert_begining(5)

    root.insert_begining(10)

    root.print()
#output of my code = <__main__.Node object at 0x00000209175AB9A0>-->None-->
</code>```

答:
You should add the str method to Node class

```<code>    def __str__(self):
        return 'The string that represent the node'
</code>```

If data is a string then it could be:

```<code>    def __str__(self):
        return self.data
</code>```

Body:
You should add the str method to Node class

    def __str__(self):
        return 'The string that represent the node'

If data is a string then it could be:

    def __str__(self):
        return self.data


问:
Reactjs "Error: ENOENT: no such file or directory, open.." after converting jsx file to tsx
I have a create-react-app app and I am translation files from jsx to typescript. For example, one file is called /code/app_react/src/common/Action.jsx and I renamed it to /code/app_react/src/common/Action.tsx. I made the necessary changes to successfully convert it to tsx, but I am getting an error related to the name change:

./src/common/Action.jsx Error: ENOENT: no such file or
  directory, open
  '/code/src/common/Action.jsx'

rebuilding the does not help

for some reason, the old version of the file is expected

The file importing this file is a jsx file, but now I am importing a tsx file into it.

This is a CRA app, so is there a correct way to clear this error?

SOLUTION:
I had to remove them from the git repository, using the git rm command, like this:

```<code>git rm /code/src/common/Action.jsx
</code>```

Once I did that, it removed the jsx from the committed files and then I was able to use the new tsx files

答:
I also had the problem in a React Application (started with yarn start and displayed at localhost:3000). The problem arised after renaming a component and forgetting the suffix .js. After adding the suffix .js the already started App still was searching for the file without the suffix. The solution was similar to Umanda's recommendation:

Ctrl-C

yarn start

Then the App worked.

Body:
I have a create-react-app app and I am translation files from jsx to typescript. For example, one file is called /code/app_react/src/common/Action.jsx and I renamed it to /code/app_react/src/common/Action.tsx. I made the necessary changes to successfully convert it to tsx, but I am getting an error related to the name change:

./src/common/Action.jsx Error: ENOENT: no such file or
  directory, open
  '/code/src/common/Action.jsx'

rebuilding the does not help

for some reason, the old version of the file is expected

The file importing this file is a jsx file, but now I am importing a tsx file into it.

This is a CRA app, so is there a correct way to clear this error?

SOLUTION:
I had to remove them from the git repository, using the git rm command, like this:

git rm /code/src/common/Action.jsx

Once I did that, it removed the jsx from the committed files and then I was able to use the new tsx files


问:
Avoid & Count non-numerical values computing basic statistics in Mathematica
Please consider:

```<code>dalist={{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
       {2.88`, 2.04`, 4.64`,0.56`, 4.92`, 2.06`, 3.46`, 2.68`, 2.72`,0.820},
       {"Laura1", "Laura1", "Laura1", "Laura1", "Laura1",
       "Laura1", "Laura1", "Laura1", "Laura1","Laura1"},
       {"RIGHT", 0, 1, 15.1`, 0.36`, 505, 20.059375`,15.178125`, ".", "."}}
</code>```

The actual dataset is about 6 000 rows and 147 columns. However the above reflects its content. I would like to compute some basic statistics, such as the mean. My attempt:

```<code>Table[Mean@dalist[[colNO]], {colNO, 1, 4}]
</code>```

How could I create a function such as to:

Avoid non-numerical values and

Count the number of non numerical values found in each lists.

I have not succeeded in finding the right pattern mechanism yet.

答:
The key to answering your question is the NumberQ function: "*NumberQ[expr] gives True if expr is a number, and False otherwise."

To compute the mean of only numeric elements in each list:

```<code>Map[Function[lst, Mean[Select[lst, NumberQ]]], dalist]
</code>```

To count the number of non-numeric elements in each list:

```<code>Map[Function[lst, Length[Select[lst, Function[x, !NumberQ[x]]]]], dalist]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please consider:

dalist={{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
       {2.88`, 2.04`, 4.64`,0.56`, 4.92`, 2.06`, 3.46`, 2.68`, 2.72`,0.820},
       {"Laura1", "Laura1", "Laura1", "Laura1", "Laura1",
       "Laura1", "Laura1", "Laura1", "Laura1","Laura1"},
       {"RIGHT", 0, 1, 15.1`, 0.36`, 505, 20.059375`,15.178125`, ".", "."}}

The actual dataset is about 6 000 rows and 147 columns. However the above reflects its content. I would like to compute some basic statistics, such as the mean. My attempt:

Table[Mean@dalist[[colNO]], {colNO, 1, 4}]

How could I create a function such as to:

Avoid non-numerical values and

Count the number of non numerical values found in each lists.

I have not succeeded in finding the right pattern mechanism yet.

Body:
The key to answering your question is the NumberQ function: "*NumberQ[expr] gives True if expr is a number, and False otherwise."

To compute the mean of only numeric elements in each list:

Map[Function[lst, Mean[Select[lst, NumberQ]]], dalist]

To count the number of non-numeric elements in each list:

Map[Function[lst, Length[Select[lst, Function[x, !NumberQ[x]]]]], dalist]


问:
C# Pong Game - problem with ball scripting
I was just copying a tutorial on YouTube on how to make the pong game and when it came to scripting the ball, there was an error for me but not the guy in the video.

I have no experience in C#, only Python. This is the error message:

Assets\Ball.cs(24,26): error CS0117: 'Random' does not contain a definition for 'range'

Anyone know what's wrong?

This is the script for it:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour
{
    public float speed;
    public Rigidbody2D rb;

    //Start is called before the first frame update
    void Start()
    {
        Launch();
    }
    //Update is called once per frame
    void Update()
    {

    }
    private void Launch()

    {
        float x = Random.range(0,2) == 0 ? -1 : 1;
        float y = Random.range(0,2) == 0 ? -1 : 1;
        rb.velocity = new Vector2(speed * x, speed * y);
    }
}
</code>```

答: You need to capitalize "range",  Random.Range is a method and most methods start with a capital letter so instead of "Random.range", you need to type "Random.Range"</p>

Body:
I was just copying a tutorial on YouTube on how to make the pong game and when it came to scripting the ball, there was an error for me but not the guy in the video.

I have no experience in C#, only Python. This is the error message:

Assets\Ball.cs(24,26): error CS0117: 'Random' does not contain a definition for 'range'

Anyone know what's wrong?

This is the script for it:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour
{
    public float speed;
    public Rigidbody2D rb;

    //Start is called before the first frame update
    void Start()
    {
        Launch();
    }
    //Update is called once per frame
    void Update()
    {

    }
    private void Launch()

    {
        float x = Random.range(0,2) == 0 ? -1 : 1;
        float y = Random.range(0,2) == 0 ? -1 : 1;
        rb.velocity = new Vector2(speed * x, speed * y);
    }
}


问:
Using R ode models as functions in nls
I try to estimate parameters for an ode model in R using nls (and later nlme). My testing code gives me error messages.

```<code>library(deSolve)
seed=2423
dat2<-data.frame(days=(runif(20)+1)*10, X1=runif(20), X2=runif(20))
dat2$y<-0.4*exp(dat2$X1)+0.6*exp(dat2$X2)+rnorm(20, sd=0.3)
# example intentionally simple. I would usually solve it analysically
#***************************************************
#*Model definition
#***************************************************
decomp<-function(t, state, parameters){
  with(as.list(c(state, parameters)), {
    dX1<-a1*X1
    dX2<-a2*X2#+a1*X1
    list(c(dX1, dX2))
  } )
}
# Testing the code to demonstrate that it works
parameters<-c(a1=0.05,a2=0.05)
state<-c(X1=0.5, X2=0.5)
times<-seq(0,100, by=1)
out<-ode(y=state, times=times, func=decomp, parms=parameters)
out[100,]
#*****************************
#* Wrapper function to be passed to nls or nlme
#**************************************
calcdecom<-function(a1,a2,t,x1, x2)
{
  state<-c(X1=x1, X2=x2)
  times<-c(0,t)
  parameters<-c(a1=a1,a2=a2)
  out<-ode(y=state, times=times, func=decomp, parms=parameters)
  return(as.numeric(out[2,2]+out[2,3]))
}
# ******************** test
calcdecom(0.1,0.1,5,0.3,0.3)

test<-nls(y~calcdecom(a1, a2, days, X1, X2 ),
          start=list(a1=0.02, a2=0.4), data=dat2)
</code>```

My error messages for the nls function is:

Error in lsoda(y, times, func, parms, ...) :
illegal input detected before taking any integration steps - see written message

答:
Here a possible approach. One remaining question is, whether the data should really come from independent cases (simulations or measurements) and not from a time series. If the first is intended, then ode must be called for each case separately. This can be done in a for-loop or with an applyfunction. Note also the correction of the set.seed-call, the plot function and the reduced standard deviation in the data generating process. It seems to me that the ode model and the data generating process do not match yet, so that the fitted parameters differ. It would be nice if the OP could post a corrected version by editing the question.

library("deSolve")

## use set.seed to make example reproducible
set.seed(2423)

## simulated data
dat2 <- data.frame(
  days = (runif(20) + 1) + 10,
  X1 = runif(20),
  X2 = runif(20)
)

## reduced error for testing
dat2$y <- 0.4 * exp(dat2$X1) + 0.6 * exp(dat2$X2) + rnorm(20, sd = 0.1)

plot(dat2)

decomp <- function(t, state, parameters){
  with(as.list(c(state, parameters)), {
    dX1 <- a1 * X1
    dX2 <- a2 * X2 + a1 * X1
    list(c(dX1, dX2))
  } )
}

## test the ode moel to demonstrate that it works
parameters <- c(a1 = 0.05, a2 = 0.05)
state <- c(X1 = 0.5, X2 = 0.5)
times <- seq(0, 100, by = 1)
out <- ode(y = state, times = times, func = decomp, parms = parameters)
plot(out)
out[100,]

## Wrapper function to be passed to nls or nlme
calcdecom <- function(a1, a2, t, x1, x2) {
  ret <- numeric(length(t))
  parameters <- c(a1 = a1, a2 = a2)
  for (i in 1:length(t)) {
    times <- c(0, t[i])
    state <- c(X1 = x1[i], X2 = x2[i])
    out <- ode(y = state, times = times, func = decomp, parms = parameters)
    ret[i] <- out[2, 2] + out[2, 3]
  }
  return(ret)
}

## test wrapper function
calcdecom(0.1, 0.1, 5, 0.3, 0.3)

## with time and state as vectors
calcdecom(0.1, 0.1, 1:10, dat2$X1, dat2$X2)

test <- nls(y ~ calcdecom(a1, a2, days, X1, X2 ),
          start = list(a1 = 0.02, a2 = 0.4), data = dat2)

summary(test)
```

Instead of nls one may also consider modFit from package FME, that has some more flexibility for this kind of models. Details are found in the package vignettes and the following JSS paper:  https://doi.org/10.18637/jss.v033.i03

Title: Using R ode models as functions in nls

Body:
I try to estimate parameters for an ode model in R using nls (and later nlme). My testing code gives me error messages.

library(deSolve)
seed=2423
dat2<-data.frame(days=(runif(20)+1)*10, X1=runif(20), X2=runif(20))
dat2$y<-0.4*exp(dat2$X1)+0.6*exp(dat2$X2)+rnorm(20, sd=0.3)
# example intentionally simple. I would usually solve it analysically
#***************************************************
#*Model definition
#***************************************************
decomp<-function(t, state, parameters){
  with(as.list(c(state, parameters)), {
    dX1<-a1*X1
    dX2<-a2*X2#+a1*X1
    list(c(dX1, dX2))
  } )
}
# Testing the code to demonstrate that it works
parameters<-c(a1=0.05,a2=0.05)
state<-c(X1=0.5, X2=0.5)
times<-seq(0,100, by=1)
out<-ode(y=state, times=times, func=decomp, parms=parameters)
out[100,]
#*****************************
#* Wrapper function to be passed to nls or nlme
#**************************************
calcdecom<-function(a1,a2,t,x1, x2)
{
  state<-c(X1=x1, X2=x2)
  times<-c(0,t)
  parameters<-c(a1=a1,a2=a2)
  out<-ode(y=state, times=times, func=decomp, parms=parameters)
  return(as.numeric(out[2,2]+out[2,3]))
}
# ******************** test
calcdecom(0.1,0.1,5,0.3,0.3)

test<-nls(y~calcdecom(a1, a2, days, X1, X2 ),
          start=list(a1=0.02, a2=0.4), data=dat2)

My error messages for the nls function is:

Error in lsoda(y, times, func, parms, ...) :
illegal input detected before taking any integration steps - see written message

Body:
Here a possible approach. One remaining question is, whether the data should really come from independent cases (simulations or measurements) and not from a time series. If the first is intended, then ode must be called for each case separately. This can be done in a for-loop or with an applyfunction. Note also the correction of the set.seed-call, the plot function and the reduced standard deviation in the data generating process. It seems to me that the ode model and the data generating process do not match yet, so that the fitted parameters differ. It would be nice if the OP could post a corrected version by editing the question.

library("deSolve")

## use set.seed to make example reproducible
set.seed(2423)

## simulated data
dat2 <- data.frame(
  days = (runif(20) + 1) + 10,
  X1 = runif(20),
  X2 = runif(20)
)

## reduced error for testing
dat2$y <- 0.4 * exp(dat2$X1) + 0.6 * exp(dat2$X2) + rnorm(20, sd = 0.1)

plot(dat2)

decomp <- function(t, state, parameters){
  with(as.list(c(state, parameters)), {
    dX1 <- a1 * X1
    dX2 <- a2 * X2 + a1 * X1
    list(c(dX1, dX2))
  } )
}

## test the ode moel to demonstrate that it works
parameters <- c(a1 = 0.05, a2 = 0.05)
state <- c(X1 = 0.5, X2 = 0.5)
times <- seq(0, 100, by = 1)
out <- ode(y = state, times = times, func = decomp, parms = parameters)
plot(out)
out[100,]

## Wrapper function to be passed to nls or nlme
calcdecom <- function(a1, a2, t, x1, x2) {
  ret <- numeric(length(t))
  parameters <- c(a1 = a1, a2 = a2)
  for (i in 1:length(t)) {
    times <- c(0, t[i])
    state <- c(X1 = x1[i], X2 = x2[i])
    out <- ode(y = state, times = times, func = decomp, parms = parameters)
    ret[i] <- out[2, 2] + out[2, 3]
  }
  return(ret)
}

## test wrapper function
calcdecom(0.1, 0.1, 5, 0.3, 0.3)

## with time and state as vectors
calcdecom(0.1, 0.1, 1:10, dat2$X1, dat2$X2)

test <- nls(y ~ calcdecom(a1, a2, days, X1, X2 ),
          start = list(a1 = 0.02, a2 = 0.4), data = dat2)

summary(test)

Instead of nls one may also consider modFit from package FME, that has some more flexibility for this kind of models. Details are found in the package vignettes and the following JSS paper:  https://doi.org/10.18637/jss.v033.i03


问:
Further Optimisation of Project Euler problem 14 (Collatz Sequence)
When I first starting trying the question, my code would take over a minute to even finish running and give me the answer. I have already tried dynamic programming and storing previous numbers so it doesn't have to run the same number multiple times. I have also tried compacting (n3)+1 and n / 2 into a single line with ((n3)+1) but both of these has only managed to cut my code to 10 seconds. Is there anything else I can try to speed up my code?

```<code>def Collatz(n):
  dic = {a: 0 for a in range(1,1000000)}
  dic[1] = 0
  dic[2] = 1
  number,length = 1,1
  for i in range(3,n,1):
    z = i
    testlength = 0
    loop = "T"
    while loop == "T":
      if z % 2 == 0:
        z = z / 2
        testlength += 1
      else:
        z = ((z*3)+1) / 2
        testlength += 2
      if z < i:
        testlength += dic[z]
        loop = "F"
    dic[i] = testlength
    if testlength > length:
      print(i,testlength)
      number,length = i,testlength
  return number,length
print(Collatz(1000000))
</code>```

答:
Although the answer from Matt Timmermanns is fast, it is not quite as easy to understand as a recursive function. Here is my attempt that is actually faster for n = 10*million and perhaps easier to understand...

```<code>f = 10000000

def collatz(n):
    if n>=collatz.bounds:
        if (n % 4) == 0:
            return collatz(n//4)+2
        if (n % 2) == 0:
            return collatz(n//2)+1
        return collatz((3*n+1)//2)+2
    if collatz.memory[n]>=0:
        return collatz.memory[n]
    if (n % 2) == 0:
        count = collatz(n//2)+1
    else:
        count = collatz((3*n+1)//2)+2
    collatz.memory[n] = count
    return count

collatz.memory = [-1]*f
collatz.memory[1] = 0
collatz.bounds = f

highest = max(collatz(i) for i in range(f//2, f+1))
highest_n = collatz.memory.index(highest)

print(f"collatz({highest_n}) is {highest}")
</code>```

My results:

```<code>$ time /usr/bin/python3 collatz.py
collatz(8400511) is 685

real    0m9.445s
user    0m9.375s
sys     0m0.060s
</code>```

Compared to

```<code>$ time /usr/bin/python3 mattsCollatz.py
(8400511, 685)

real    0m10.672s
user    0m10.599s
sys     0m0.066s
</code>```

Body:
When I first starting trying the question, my code would take over a minute to even finish running and give me the answer. I have already tried dynamic programming and storing previous numbers so it doesn't have to run the same number multiple times. I have also tried compacting (n3)+1 and n / 2 into a single line with ((n3)+1) but both of these has only managed to cut my code to 10 seconds. Is there anything else I can try to speed up my code?

def Collatz(n):
  dic = {a: 0 for a in range(1,1000000)}
  dic[1] = 0
  dic[2] = 1
  number,length = 1,1
  for i in range(3,n,1):
    z = i
    testlength = 0
    loop = "T"
    while loop == "T":
      if z % 2 == 0:
        z = z / 2
        testlength += 1
      else:
        z = ((z*3)+1) / 2
        testlength += 2
      if z  length:
      print(i,testlength)
      number,length = i,testlength
  return number,length
print(Collatz(1000000))

Body:
Although the answer from Matt Timmermanns is fast, it is not quite as easy to understand as a recursive function. Here is my attempt that is actually faster for n = 10*million and perhaps easier to understand...

f = 10000000

def collatz(n):
    if n>=collatz.bounds:
        if (n % 4) == 0:
            return collatz(n//4)+2
        if (n % 2) == 0:
            return collatz(n//2)+1
        return collatz((3*n+1)//2)+2
    if collatz.memory[n]>=0:
        return collatz.memory[n]
    if (n % 2) == 0:
        count = collatz(n//2)+1
    else:
        count = collatz((3*n+1)//2)+2
    collatz.memory[n] = count
    return count

collatz.memory = [-1]*f
collatz.memory[1] = 0
collatz.bounds = f

highest = max(collatz(i) for i in range(f//2, f+1))
highest_n = collatz.memory.index(highest)

print(f"collatz({highest_n}) is {highest}")

My results:

$ time /usr/bin/python3 collatz.py
collatz(8400511) is 685

real    0m9.445s
user    0m9.375s
sys     0m0.060s

Compared to

$ time /usr/bin/python3 mattsCollatz.py
(8400511, 685)

real    0m10.672s
user    0m10.599s
sys     0m0.066s


问:
How do I check whether a SQLite database file exists using Java?
I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists. </p>

```<code>public static void databaseConnect(String dbName) throws Exception
{
  if (/*same name exists*/) // How do I check this?
  {
    System.out.print("This database name already exists");
  }
  else
  {
    Class.forName("SQLite.JDBCDriver").newInstance();
    conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
    stat = conn.createStatement();
  }
}
</code>```

答:
```<code>public static void databaseConnect(String dbName) throws Exception {

   File file = new File (dbName);

  if(file.exists()) //here's how to check
     {
         System.out.print("This database name already exists");
     }
     else{

           Class.forName("SQLite.JDBCDriver").newInstance();
           conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
           stat = conn.createStatement();

     }
</code>```

Body:
I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists.

public static void databaseConnect(String dbName) throws Exception
{
  if (/*same name exists*/) // How do I check this?
  {
    System.out.print("This database name already exists");
  }
  else
  {
    Class.forName("SQLite.JDBCDriver").newInstance();
    conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
    stat = conn.createStatement();
  }
}


问:
HTML5 make empty div full viewport size
I’m trying to create an EMPTY div that takes up 100% of the viewport and that moves with the viewport (or position: fixed).
It also needs to be at top: 0, left 0 of the viewport. This is for a browser extension so I need this div to be added over any page.

The background reason for this is so I can use the div as a full page tooltip that shows the mouse x and y positions and the tooltip follows the mouse.

How can this full page div be achieved? My many attempts have failed to create a div with any height.

I am away from my pc but can add what I’ve tried already soon.

答:
Try this stylesheet and with some JavaScript code will help you to achieve a full page div.

```<code>#full-page-div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: none
}
</code>```

I have added the extra "overflow: none" because height may get more than browser window's height and we don't need to show the scrollbars.

Now, in the JavaScript code, we need to adjust the div height to the full page height, also need to add a handler to window "resize" event, so as to adjust that full page div height and width.

```<code>function ExtFullPageDivAdjust()
{
  let fullPageDiv = document.getElementById("full-page-div");
  fullPageDiv.style.height = Math.max(window.innerHeight, document.querySelector("body").clientHeight) + "px";
  fullPageDiv.style.width = window.innerWidth + "px";
}

ExtFullPageDivAdjust();
window.addEventListener("load", ExtFullPageDivAdjust);
window.addEventListener("resize", ExtFullPageDivAdjust);
</code>```

Title: HTML5 make empty div full viewport size

Body:
Try this stylesheet and with some JavaScript code will help you to achieve a full page div.

#full-page-div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: none
}

I have added the extra "overflow: none" because height may get more than browser window's height and we don't need to show the scrollbars.

Now, in the JavaScript code, we need to adjust the div height to the full page height, also need to add a handler to window "resize" event, so as to adjust that full page div height and width.

function ExtFullPageDivAdjust()
{
  let fullPageDiv = document.getElementById("full-page-div");
  fullPageDiv.style.height = Math.max(window.innerHeight, document.querySelector("body").clientHeight) + "px";
  fullPageDiv.style.width = window.innerWidth + "px";
}

ExtFullPageDivAdjust();
window.addEventListener("load", ExtFullPageDivAdjust);
window.addEventListener("resize", ExtFullPageDivAdjust);


问:
Extract all video frames as images with FFMPEG
I am trying to convert a MP4 video file into a series of jpg images (out-1.jpg, out-2.jpg etc.) using FFMPEG with,

```<code>mkdir frames
ffmpeg -i "%1" -r 1 frames/out-%03d.jpg
</code>```

However I keep getting errors like,

[image2 @ 00000037f5a811a0] Could not open file :
  frames/out-C:\Applications\FFMPEG\toGIF.bat3d.jpg
  av_interleaved_write_frame(): Input/output error frame=    1 fps=0.0
  q=5.9 Lsize=N/A time=00:00:01.00 bitrate=N/A video:63kB audio:0kB
  subtitle:0kB other streams:0kB global headers:0kB muxing overhead:
  unknown Conversion failed!

If I take out the %03d part, the conversion works but it only outputs the first frame and the program stops with error.

How can I correctly extract all the frames of the video with FFMPEG?

答: Impossible to do in a windows batch file because every %x are interpreted as prameters passed to batch file</p>

Body:
I am trying to convert a MP4 video file into a series of jpg images (out-1.jpg, out-2.jpg etc.) using FFMPEG with,

mkdir frames
ffmpeg -i "%1" -r 1 frames/out-%03d.jpg

However I keep getting errors like,

[image2 @ 00000037f5a811a0] Could not open file :
  frames/out-C:\Applications\FFMPEG\toGIF.bat3d.jpg
  av_interleaved_write_frame(): Input/output error frame=    1 fps=0.0
  q=5.9 Lsize=N/A time=00:00:01.00 bitrate=N/A video:63kB audio:0kB
  subtitle:0kB other streams:0kB global headers:0kB muxing overhead:
  unknown Conversion failed!

If I take out the %03d part, the conversion works but it only outputs the first frame and the program stops with error.

How can I correctly extract all the frames of the video with FFMPEG?


问:
CMAKE if regexp match
I'm just, ehh can any1 tell me what tiny symbol is missing.

```<code>    if (${exename} MATCHES "^(xxx)\\w+")
        message("WERE IN TEST : " ${exename})
    endif ()
</code>```

This fails to find names with xxx in them, I just want to find a name that contains a specific tag to add a flag n stuff.

TIA

答:
CMake does not support character classes in regular expressions; you need to use the character group with the same meaning. Furthermore I'm not sure why you add a capturing group that matches only a single string.

```<code>if (${exename} MATCHES "^(xxx)[A-Za-z0-9_]+")
...
</code>```

Note that this matches strings starting with xxx, not strings with xxx anywhere. The correct regular expression for the later would be .*xxx.*.

Title: CMAKE if regexp match

Body:
I'm just, ehh can any1 tell me what tiny symbol is missing.

    if (${exename} MATCHES "^(xxx)\\w+")
        message("WERE IN TEST : " ${exename})
    endif ()

This fails to find names with xxx in them, I just want to find a name that contains a specific tag to add a flag n stuff.

TIA

Body:
CMake does not support character classes in regular expressions; you need to use the character group with the same meaning. Furthermore I'm not sure why you add a capturing group that matches only a single string.

if (${exename} MATCHES "^(xxx)[A-Za-z0-9_]+")
...

Note that this matches strings starting with xxx, not strings with xxx anywhere. The correct regular expression for the later would be .*xxx.*.


问:
Why dont the buttons in my Drawer Do anything?
I have some icons in a drawer, but none of them seem to navigate to another page, and I have no clue why. There are no errors, etc. it's just a navigation drawer, with a few buttons, and MainDrawer.dart contains the Drawer, while DrawerListTile.dart contains the attributes of each tile on the drawer.

Here is the MainDrawer.dart

```<code>import 'package:iona_central/Screens/News/news.dart';
import 'package:iona_central/Screens/Exam/Exam_Rseult.dart';
import 'package:iona_central/Screens/Leave_Apply/Leave_apply.dart';
import 'package:iona_central/Screens/home.dart';
import 'package:iona_central/Widgets/DrawerListTile.dart';

class MainDrawer extends StatefulWidget {
  @override
  _MainDrawerState createState() => _MainDrawerState();
}

class _MainDrawerState extends State<MainDrawer> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: ListView(
      children: [
        DrawerListTile(
            imgpath: "home.png",
            name: "Home",
            ontap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (BuildContext context) => Home(),
                ),
              );
            }),
        DrawerListTile(
          imgpath: "news.png",
          name: "News",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => attendance(),
              ),
            );
          },
        ),

        //DrawerListTile(imgpath: "profile.png", name: "Profile", ontap: () {}),
        DrawerListTile(
          imgpath: "ipsports.png",
          name: "Sports",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => ExamResult(),
              ),
            );
          },
        ),
        /*DrawerListTile(
            imgpath: "calendar.png", name: "Time Table", ontap: () {}), */
        DrawerListTile(
          imgpath: "gfl.png",
          name: "GFL",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => LeaveApply(),
              ),
            );
          },
        ),
        DrawerListTile(
          imgpath: "club.png",
          name: "Clubs",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => LeaveApply(),
              ),
            );
          },
        ),
      ],
    ));
  }
}

</code>```

Here is DrawerListTile.dart

```<code>import 'package:flutter/material.dart';

class DrawerListTile extends StatelessWidget {
  final String name;
  final String imgpath;
  final Function ontap;

  const DrawerListTile(
      {Key? key,
      required this.name,
      required this.imgpath,
      required this.ontap})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: () => ontap,
      leading: Image.asset(
        "assets/${imgpath}",
        height: 30,
      ),
      contentPadding: EdgeInsets.only(
        left: 70,
        top: 5,
        bottom: 5,
      ),
      title: Text(
        "${name}",
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}

</code>```

答:
Change th line

onTap: () => ontap,

to

onTap: ontap,

or

onTap: () => ontap.call(),

Body:
I have some icons in a drawer, but none of them seem to navigate to another page, and I have no clue why. There are no errors, etc. it's just a navigation drawer, with a few buttons, and MainDrawer.dart contains the Drawer, while DrawerListTile.dart contains the attributes of each tile on the drawer.

Here is the MainDrawer.dart

import 'package:iona_central/Screens/News/news.dart';
import 'package:iona_central/Screens/Exam/Exam_Rseult.dart';
import 'package:iona_central/Screens/Leave_Apply/Leave_apply.dart';
import 'package:iona_central/Screens/home.dart';
import 'package:iona_central/Widgets/DrawerListTile.dart';

class MainDrawer extends StatefulWidget {
  @override
  _MainDrawerState createState() => _MainDrawerState();
}

class _MainDrawerState extends State<MainDrawer> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: ListView(
      children: [
        DrawerListTile(
            imgpath: "home.png",
            name: "Home",
            ontap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (BuildContext context) => Home(),
                ),
              );
            }),
        DrawerListTile(
          imgpath: "news.png",
          name: "News",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => attendance(),
              ),
            );
          },
        ),

        //DrawerListTile(imgpath: "profile.png", name: "Profile", ontap: () {}),
        DrawerListTile(
          imgpath: "ipsports.png",
          name: "Sports",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => ExamResult(),
              ),
            );
          },
        ),
        /*DrawerListTile(
            imgpath: "calendar.png", name: "Time Table", ontap: () {}), */
        DrawerListTile(
          imgpath: "gfl.png",
          name: "GFL",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => LeaveApply(),
              ),
            );
          },
        ),
        DrawerListTile(
          imgpath: "club.png",
          name: "Clubs",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => LeaveApply(),
              ),
            );
          },
        ),
      ],
    ));
  }
}

Here is DrawerListTile.dart

import 'package:flutter/material.dart';

class DrawerListTile extends StatelessWidget {
  final String name;
  final String imgpath;
  final Function ontap;

  const DrawerListTile(
      {Key? key,
      required this.name,
      required this.imgpath,
      required this.ontap})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: () => ontap,
      leading: Image.asset(
        "assets/${imgpath}",
        height: 30,
      ),
      contentPadding: EdgeInsets.only(
        left: 70,
        top: 5,
        bottom: 5,
      ),
      title: Text(
        "${name}",
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}


问:
TypeScript: Property 'data' does not exist on type '{ children?: ReactNode; }'. ts(2339)

Question

I'm working on a small project with BlitzJS. I'm fetching some data but I keep getting this Typescript issue:

```<code>Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339)
</code>```
```<code>import { BlitzPage } from "blitz"
import Layout from "app/core/layouts/Layout"

export async function getServerSideProps() {
  const response = await fetch(
    "https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=10&page=1&sparkline=false"
  )
  const data = await response.json()

  return {
    props: {
      data,
    },
  }
}

const MarketPage: BlitzPage = ({ data }) => { /////////// ERROR IS ON THIS LINE
  console.log(data)

  return (
    <div>
      <h1>This is Market Page</h1>

      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Current Price</th>
          </tr>
        </thead>
        <tbody>
          {data.map((coin) => (
            <tr key={coin.id}>
              <td>
                <p>{coin.name}</p>
              </td>
              <td>
                <p>{coin.current_price}</p>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

MarketPage.suppressFirstRenderFlicker = true
MarketPage.getLayout = (page) => <Layout>{page}</Layout>

export default MarketPage
</code>```

I guess it's something with Typescript types but I don't work with Typescript so much. I'm having hard time finding solution.

Please can you help me with some guidance here.

Thanks!

Solution

Thanks to Ajay, I resolved the issue!

Here's working example:

```<code>import { BlitzPage } from "blitz"
import Layout from "app/core/layouts/Layout"
import { Table, Th, Td } from "app/core/components/Table"

interface CoinType {
  id: string
  name: string
  current_price: string
}

interface PropType {
  data: CoinType[]
}

export async function getServerSideProps() {
  const response = await fetch(
    "https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=10&page=1&sparkline=false"
  )
  const data = await response.json()

  return {
    props: {
      data,
    },
  }
}

const MarketPage: BlitzPage<PropType> = ({ data }) => {
  return (
    <div>
      <h1>This is Market Page</h1>

      <Table>
        <thead>
          <tr>
            <Th>Name</Th>
            <Th hasNumber>Current Price</Th>
          </tr>
        </thead>
        <tbody>
          {data.map((coin) => (
            <tr key={coin.id}>
              <Td>
                <p>{coin.name}</p>
              </Td>
              <Td hasNumber>
                <p>{coin.current_price}</p>
              </Td>
            </tr>
          ))}
        </tbody>
      </Table>
    </div>
  )
}

MarketPage.suppressFirstRenderFlicker = true
MarketPage.getLayout = (page) => <Layout>{page}</Layout>

export default MarketPage
</code>```

答:
Typescript is showing errors because, You had not explain any type. You can create your type with

```<code>interface CoinType {
  id: string;
  name: string;
  current_price: string;
}

interface PropType {
  data: CoinType[];
}
</code>```

Once You have created Types, then

```<code>const MarketPage: BlitzPage = ({ data }:PropType) => {
  console.log(data)

  return (
    <div>
      <h1>This is Market Page</h1>

      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Current Price</th>
          </tr>
        </thead>
        <tbody>
          {data.map((coin) => (
            <tr key={coin.id}>
              <td>
                <p>{coin.name}</p>
              </td>
              <td>
                <p>{coin.current_price}</p>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
</code>```

I hope It would work correctly :-)

Body:
Question

I'm working on a small project with BlitzJS. I'm fetching some data but I keep getting this Typescript issue:

Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339)

import { BlitzPage } from "blitz"
import Layout from "app/core/layouts/Layout"

export async function getServerSideProps() {
  const response = await fetch(
    "https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=10&page=1&sparkline=false"
  )
  const data = await response.json()

  return {
    props: {
      data,
    },
  }
}

const MarketPage: BlitzPage = ({ data }) => { /////////// ERROR IS ON THIS LINE
  console.log(data)

  return (

This is Market Page

            Name
            Current Price

          {data.map((coin) => (

{coin.name}

{coin.current_price}

          ))}

  )
}

MarketPage.suppressFirstRenderFlicker = true
MarketPage.getLayout = (page) => <Layout>{page}</Layout>

export default MarketPage

I guess it's something with Typescript types but I don't work with Typescript so much. I'm having hard time finding solution.

Please can you help me with some guidance here.

Thanks!

Solution

Thanks to Ajay, I resolved the issue!

Here's working example:

import { BlitzPage } from "blitz"
import Layout from "app/core/layouts/Layout"
import { Table, Th, Td } from "app/core/components/Table"

interface CoinType {
  id: string
  name: string
  current_price: string
}

interface PropType {
  data: CoinType[]
}

export async function getServerSideProps() {
  const response = await fetch(
    "https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=10&page=1&sparkline=false"
  )
  const data = await response.json()

  return {
    props: {
      data,
    },
  }
}

const MarketPage: BlitzPage<PropType> = ({ data }) => {
  return (

This is Market Page

            Name
            Current Price

          {data.map((coin) => (

{coin.name}

{coin.current_price}

          ))}

  )
}

MarketPage.suppressFirstRenderFlicker = true
MarketPage.getLayout = (page) => <Layout>{page}</Layout>

export default MarketPage

Body:
Typescript is showing errors because, You had not explain any type. You can create your type with

interface CoinType {
  id: string;
  name: string;
  current_price: string;
}

interface PropType {
  data: CoinType[];
}

Once You have created Types, then

const MarketPage: BlitzPage = ({ data }:PropType) => {
  console.log(data)

  return (
    <div>
      <h1>This is Market Page</h1>

      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Current Price</th>
          </tr>
        </thead>
        <tbody>
          {data.map((coin) => (
            <tr key={coin.id}>
              <td>
                <p>{coin.name}</p>
              </td>
              <td>
                <p>{coin.current_price}</p>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

I hope It would work correctly :-)


问:
Trouble unit testing angular reactive form control reset from button click
I am facing an issue to write an unit test case in jasmine for my angular application.
Have a reactive form and trying to reset a particular form control from a button click.
Even though the scenario should be simple enough to test, it seems that I am missing something here.

Below is the code snippet from the app.

app.component.html:

```<code><form [formGroup]="userForm" novalidate (ngSubmit)="onSubmit()">
  <div>
    <input
      type="text"
      id="fNameFld"
      name="fName"
      formControlName="fName"
      placeholder="First Name"
    />
    <button (click)="clearField('fName')" id="clrFName">
      Clear First Name
    </button>
  </div>

  <div>
    <input
      type="text"
      id="lNameFld"
      name="lName"
      formControlName="lName"
      placeholder="Last Name"
    />
    <button (click)="clearField('lName')" id="clrLName">Clear Last Name</button>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
</code>```

app.component.ts

```<code>import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  userForm: FormGroup;

  constructor(private readonly fb: FormBuilder) {}

  ngOnInit() {
    this.userForm = this.fb.group({
      fName: this.fb.control(null),
      lName: this.fb.control(null),
    });
  }

  onSubmit() {
    console.log('Submitted Data', this.userForm.value);
  }

  clearField(controlName: string) {
    this.userForm.get(controlName).reset();
  }
}
</code>```

Unit test code

```<code>it('should clear fName control when the "Clear First Name" button is clicked', () => {
    const spy = spyOn(component, 'clearField');
    const clearBtn = fixture.debugElement.query(By.css("button#clrFName"));
    const form = component.userForm;

    form.patchValue({
      'fName': 'John,
      'lName': 'Doe'
    });

    clearBtn.nativeElement.click();
    fixture.detectChanges();
    expect(spy).toHaveBeenCalledTimes(1);  // passes
    expect(spy).toHaveBeenCalledWith('fName');  // passes
    expect(form.get('fName').value).toBeNull();  // fails: Expected 'John' to be null.
  });
</code>```

Angular: 10.0.14

Angular CLI: 10.0.8

StackBlitz: https://angular-ivy-fc6rik.stackblitz.io

答:
seems like you mocked clearField. Add this to actually execute its content when you mock it:

```<code>const spy = spyOn(component, 'clearField').and.callThrough();
</code>```

So everytime clearField is called, it will trigger the spy (so you know if it has been called), and will execute its content .

Body:
I am facing an issue to write an unit test case in jasmine for my angular application.
Have a reactive form and trying to reset a particular form control from a button click.
Even though the scenario should be simple enough to test, it seems that I am missing something here.

Below is the code snippet from the app.

app.component.html:

<form [formGroup]="userForm" novalidate (ngSubmit)="onSubmit()">

    <input
      type="text"
      id="fNameFld"
      name="fName"
      formControlName="fName"
      placeholder="First Name"
    />
    <button (click)="clearField('fName')" id="clrFName">
      Clear First Name
    </button>

    <input
      type="text"
      id="lNameFld"
      name="lName"
      formControlName="lName"
      placeholder="Last Name"
    />
    <button (click)="clearField('lName')" id="clrLName">Clear Last Name</button>

    <button type="submit">Submit</button>

</form>

app.component.ts

import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  userForm: FormGroup;

  constructor(private readonly fb: FormBuilder) {}

  ngOnInit() {
    this.userForm = this.fb.group({
      fName: this.fb.control(null),
      lName: this.fb.control(null),
    });
  }

  onSubmit() {
    console.log('Submitted Data', this.userForm.value);
  }

  clearField(controlName: string) {
    this.userForm.get(controlName).reset();
  }
}

Unit test code

it('should clear fName control when the "Clear First Name" button is clicked', () => {
    const spy = spyOn(component, 'clearField');
    const clearBtn = fixture.debugElement.query(By.css("button#clrFName"));
    const form = component.userForm;

    form.patchValue({
      'fName': 'John,
      'lName': 'Doe'
    });

    clearBtn.nativeElement.click();
    fixture.detectChanges();
    expect(spy).toHaveBeenCalledTimes(1);  // passes
    expect(spy).toHaveBeenCalledWith('fName');  // passes
    expect(form.get('fName').value).toBeNull();  // fails: Expected 'John' to be null.
  });

Angular: 10.0.14

Angular CLI: 10.0.8

StackBlitz: https://angular-ivy-fc6rik.stackblitz.io

Body:
seems like you mocked clearField. Add this to actually execute its content when you mock it:

const spy = spyOn(component, 'clearField').and.callThrough();

So everytime clearField is called, it will trigger the spy (so you know if it has been called), and will execute its content .


问:
Null terminating int arrays
If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?

```<code>int *array = new int[x];
..do some stuff..
delete array;
</code>```

I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?

答:
If you allocate an array with new[], you just need to free it with delete[].

The compiler is required to track the size and count of the allocation if the type you are allocating has a non-trivial destructor.

As for strings, the null terminator is for determining the length of the string, not the size of the underlying memory allocation.

Title: Null terminating int arrays

Body:
If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?

int *array = new int[x];
..do some stuff..
delete array;

I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?


问:
How can I keep the discord bot active without pycharm?
when you make a discord bot with javascript

```<code>"echo off"
color 0f
cls
:a
node bot.js
goto a"
</code>```

When I put this command in the folder and run it as .bat, it could run without the need for a client. Do you know how I can do this with python?

答: To run a Python Code you need to host it on a 24/7 client or server. You can use your own server like on AWS or Azure, and actually then what you do is keep it 24/7 running to keep your bot. Or you can use a hosting platform like DigitalOcean or Autocode.</p>

Body:
when you make a discord bot with javascript

"echo off"
color 0f
cls
:a
node bot.js
goto a"

When I put this command in the folder and run it as .bat, it could run without the need for a client. Do you know how I can do this with python?


答:
first add an empty div to body then use this :

```<code>{position: fixed;
top: 0;
left: 0;
background: red;
right: 0;
z-index: 999999999;
bottom: 0;}
</code>```

this pure css code is enough and you dont need any javascript even after resize.

Title: HTML5 make empty div full viewport size

Body:
I’m trying to create an EMPTY div that takes up 100% of the viewport and that moves with the viewport (or position: fixed).
It also needs to be at top: 0, left 0 of the viewport. This is for a browser extension so I need this div to be added over any page.

The background reason for this is so I can use the div as a full page tooltip that shows the mouse x and y positions and the tooltip follows the mouse.

How can this full page div be achieved? My many attempts have failed to create a div with any height.

I am away from my pc but can add what I’ve tried already soon.

Body:
first add an empty div to body then use this :

{position: fixed;
top: 0;
left: 0;
background: red;
right: 0;
z-index: 999999999;
bottom: 0;}

this pure css code is enough and you dont need any javascript even after resize.


问:
How to test an expected formatted error in idiomatic Go?
This question is NOT about validation. It is just an example, but could be any other thing with formatted errors.

Let's say I have a very simple Validate() method that validates an extension eg. .vcf from a filename and I want an error saying valid extension and current extension if they don't match. Ideally, this method would be extended to do other validations and return other validation errors.

Something like:

```<code>// main.go
package main

import (
    "fmt"
    "os"
    "path/filepath"
)

type ValidationError struct {
    Msg string
}

func (v ValidationError) Error() string {
    return v.Msg
}

func Validate(fileName string) error {
    // first validation
    wantExtension := ".vcf"
    gotExtension := filepath.Ext(fileName)
    if gotExtension != wantExtension {
        return ValidationError{Msg: fmt.Sprintf("Extension %q not accepted, please use a %s file.", gotExtension, wantExtension)}
    }
    // potentially other validations
    return nil
}

func main() {
    fileName := os.Args[1]
    Validate(fileName)
}
</code>```

I want to test it in a way that I check not only the error type (in this case error, but also the message). Something like:

```<code>// main_test.go
package main

import (
    "errors"
    "testing"
)

func TestValidate(t *testing.T) {
    testCases := []struct {
        name        string
        fileName    string
        expectedErr error
    }{
        {
            name:     "happy-path",
            fileName: "file.vcf",
        },
        {
            name:        "wrong-extension",
            fileName:    "file.md",
            expectedErr: ValidationError{Msg: "Extension .md not accepted, please use a .vcf file."},
        },
    }
    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            err := Validate(tc.fileName)
            if !errors.Is(err, tc.expectedErr) {
                t.Errorf("want (%v) got (%v)", tc.expectedErr, err)
            }
        })
    }
}
</code>```

This test will get:

```<code>--- FAIL: TestValidate (0.00s)
    --- FAIL: TestValidate/wrong-extension (0.00s)
        main_test.go:28: want (Extension .md not accepted, please use a .vcf file.) got (Extension ".md" not accepted, please use a .vcf file.)
</code>```

I does not work since errors.Is() expects same memory object. Also if I use errors.As() the test will pass but it will not really check if the message is correct.

I also tried defining a function to return an error with the message as parameter or simpler errors.New() instead of custom error, but I run into the same problem that the object in memory is different in the test side, also don't know which of the three approaches would be considered more idiomatic.

How would you implement that?

UPDATE: I updated the question code to use custom error instead of errors.New as it is probably more fit to the case as in the answer by @kingkupps.

答:
there is no problem in using errors.Is. The code did not fail at using it.

It is the test code that is not setup correctly.

In the program, the error message is defined as Extension ".md" not accepted, please use a .vcf file., like in, return ValidationError{Msg: fmt.Sprintf("Extension %q not accepted, please use a %s file.", gotExtension, wantExtension)}

In the test, the error message is defined as expectedErr: ValidationError{Msg: "Extension .md not accepted, please use a .vcf file."},

Hence, when trying to compare the two error values, the state is similar to

```<code>    fmt.Println(
        errors.Is(
            ValidationError{Msg: `Extension ".md" not accepted, please use a .vcf file.`},
            ValidationError{Msg: `Extension .md not accepted, please use a .vcf file.`},
        ),
    )
</code>```

Which is expected to return false using that api as it performs equality check of comparable values.

https://cs.opensource.google/go/go/+/refs/tags/go1.17.6:src/errors/wrap.go;l=46

For, reference, it is roughly equivalent to

```<code>    fmt.Println(
        ValidationError{Msg: `Extension ".md" not accepted, please use a .vcf file.`} ==
            ValidationError{Msg: `Extension .md not accepted, please use a .vcf file.`},
    )
</code>```

https://go.dev/ref/spec#Comparison_operators

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

Most certainly using errors, this one should be mentioned too

Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

Body:
This question is NOT about validation. It is just an example, but could be any other thing with formatted errors.

Let's say I have a very simple Validate() method that validates an extension eg. .vcf from a filename and I want an error saying valid extension and current extension if they don't match. Ideally, this method would be extended to do other validations and return other validation errors.

Something like:

// main.go
package main

import (
    "fmt"
    "os"
    "path/filepath"
)

type ValidationError struct {
    Msg string
}

func (v ValidationError) Error() string {
    return v.Msg
}

func Validate(fileName string) error {
    // first validation
    wantExtension := ".vcf"
    gotExtension := filepath.Ext(fileName)
    if gotExtension != wantExtension {
        return ValidationError{Msg: fmt.Sprintf("Extension %q not accepted, please use a %s file.", gotExtension, wantExtension)}
    }
    // potentially other validations
    return nil
}

func main() {
    fileName := os.Args[1]
    Validate(fileName)
}

I want to test it in a way that I check not only the error type (in this case error, but also the message). Something like:

// main_test.go
package main

import (
    "errors"
    "testing"
)

func TestValidate(t *testing.T) {
    testCases := []struct {
        name        string
        fileName    string
        expectedErr error
    }{
        {
            name:     "happy-path",
            fileName: "file.vcf",
        },
        {
            name:        "wrong-extension",
            fileName:    "file.md",
            expectedErr: ValidationError{Msg: "Extension .md not accepted, please use a .vcf file."},
        },
    }
    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            err := Validate(tc.fileName)
            if !errors.Is(err, tc.expectedErr) {
                t.Errorf("want (%v) got (%v)", tc.expectedErr, err)
            }
        })
    }
}

This test will get:

--- FAIL: TestValidate (0.00s)
    --- FAIL: TestValidate/wrong-extension (0.00s)
        main_test.go:28: want (Extension .md not accepted, please use a .vcf file.) got (Extension ".md" not accepted, please use a .vcf file.)

I does not work since errors.Is() expects same memory object. Also if I use errors.As() the test will pass but it will not really check if the message is correct.

I also tried defining a function to return an error with the message as parameter or simpler errors.New() instead of custom error, but I run into the same problem that the object in memory is different in the test side, also don't know which of the three approaches would be considered more idiomatic.

How would you implement that?

UPDATE: I updated the question code to use custom error instead of errors.New as it is probably more fit to the case as in the answer by @kingkupps.

Body:
there is no problem in using errors.Is. The code did not fail at using it.

It is the test code that is not setup correctly.

In the program, the error message is defined as Extension ".md" not accepted, please use a .vcf file., like in, return ValidationError{Msg: fmt.Sprintf("Extension %q not accepted, please use a %s file.", gotExtension, wantExtension)}

In the test, the error message is defined as expectedErr: ValidationError{Msg: "Extension .md not accepted, please use a .vcf file."},

Hence, when trying to compare the two error values, the state is similar to

    fmt.Println(
        errors.Is(
            ValidationError{Msg: `Extension ".md" not accepted, please use a .vcf file.`},
            ValidationError{Msg: `Extension .md not accepted, please use a .vcf file.`},
        ),
    )

Which is expected to return false using that api as it performs equality check of comparable values.

https://cs.opensource.google/go/go/+/refs/tags/go1.17.6:src/errors/wrap.go;l=46

For, reference, it is roughly equivalent to

    fmt.Println(
        ValidationError{Msg: `Extension ".md" not accepted, please use a .vcf file.`} ==
            ValidationError{Msg: `Extension .md not accepted, please use a .vcf file.`},
    )

https://go.dev/ref/spec#Comparison_operators

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

Most certainly using errors, this one should be mentioned too

Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.


问:
WPF Nested binding in a controltemplate
I have successfully created a textbox that displays / collapses an error message depending upon a validation rule set in its model / vm. The code goes like this for the email for ex.:

```<code>    <StackPanel Grid.Row="3" Grid.Column="1">
        <TextBox MaxLength="200" x:Name="mailTextBox"
                Style="{StaticResource SectionEditPropertyTextBox}"
                Text="{Binding Email, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
        <ContentPresenter Visibility="{Binding ElementName=mailTextBox, Path=(Validation.HasError), Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=True }"
                Content="{Binding ElementName=mailTextBox, Path=(Validation.Errors).CurrentItem}"
                HorizontalAlignment="Left">
            <ContentPresenter.ContentTemplate>
                <DataTemplate>
                    <Label Style="{StaticResource SectionEditErrorLabel}" Content="{Binding Path=ErrorContent}"/>
                </DataTemplate>
            </ContentPresenter.ContentTemplate>
        </ContentPresenter>
    </StackPanel>
</code>```

Since I have a bunch of these, I would have liked to put all of this in a control template and relocate this in a common resource file.

My template looks like this:

```<code><ControlTemplate x:Key="FormTextBox" TargetType="{x:Type TextBox}">
    <StackPanel Grid.Row="{TemplateBinding Grid.Row}" Grid.Column="{TemplateBinding Grid.Column}">
        <TextBox x:Name="validableText" MaxLength="{TemplateBinding MaxLength}"
                Style="{StaticResource SectionEditPropertyTextBox}"
                Text="{TemplateBinding Text}" />
        <ContentPresenter Visibility="{Binding ElementName=validableText, Path=(Validation.HasError), Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=True }"
                Content="{Binding ElementName=validableText, Path=(Validation.Errors).CurrentItem}"
                HorizontalAlignment="Left">
            <ContentPresenter.ContentTemplate>
                <DataTemplate>
                    <Label Style="{StaticResource SectionEditErrorLabel}" Content="{Binding Path=ErrorContent}"/>
                </DataTemplate>
            </ContentPresenter.ContentTemplate>
        </ContentPresenter>
    </StackPanel>
</ControlTemplate>
</code>```

and I link to it like this:

```<code>    <TextBox Grid.Row="3" Grid.Column="1" MaxLength="200" Template="{StaticResource FormTextBox}"
             Text="{Binding Email, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
</code>```

Unfortunately, it doesn't perform any validation so the binding must be broken somehow...

Please advise...

Thanks.

答:
You won't need the Grid.Row and Grid.Column bindings in the Template StackPanel since the StackPanel won't be the direct child of a Grid anyway,

TemplateBinding is always a OneWay binding so the Text property for the Templated TextBox will never get updated. Change it to a regular Binding with RelativeSource and TwoWay

Change ElementName=validableText to RelativeSource={RelativeSource TemplatedParent} in the bindings for ContentPresenter since we want to perform the validation check on the Templated TextBox and not the TextBox inside the Template.

```<code><ControlTemplate x:Key="FormTextBox" TargetType="{x:Type TextBox}">
    <StackPanel>
        <TextBox x:Name="validableText"
                 MaxLength="{TemplateBinding MaxLength}"
                 Style="{StaticResource SectionEditPropertyTextBox}"
                 Text="{Binding RelativeSource={RelativeSource TemplatedParent},
                                Path=Text,
                                Mode=TwoWay,
                                UpdateSourceTrigger=PropertyChanged}" />
        <ContentPresenter Visibility="{Binding RelativeSource={RelativeSource TemplatedParent},
                                               Path=(Validation.HasError),
                                               Converter={StaticResource BooleanToVisibilityConverter}
                                               ConverterParameter=True}"
                            Content="{Binding RelativeSource={RelativeSource TemplatedParent},
                                              Path=(Validation.Errors).CurrentItem}"
                            HorizontalAlignment="Left">
            <ContentPresenter.ContentTemplate>
                <DataTemplate>
                    <Label Style="{StaticResource SectionEditErrorLabel}" Content="{Binding Path=ErrorContent}"/>
                </DataTemplate>
            </ContentPresenter.ContentTemplate>
        </ContentPresenter>
    </StackPanel>
</ControlTemplate>
</code>```

On a side note, another alternative that you have here is to create a UserControl with the original piece of Xaml that you had. You could introduce the Dependency Properties needed for your scenario (Text etc.). It would only require small changes.

Title: WPF Nested binding in a controltemplate

Body:
I have successfully created a textbox that displays / collapses an error message depending upon a validation rule set in its model / vm. The code goes like this for the email for ex.:

    <StackPanel Grid.Row="3" Grid.Column="1">
        <TextBox MaxLength="200" x:Name="mailTextBox"
                Style="{StaticResource SectionEditPropertyTextBox}"
                Text="{Binding Email, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
        <ContentPresenter Visibility="{Binding ElementName=mailTextBox, Path=(Validation.HasError), Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=True }"
                Content="{Binding ElementName=mailTextBox, Path=(Validation.Errors).CurrentItem}"
                HorizontalAlignment="Left">
            <ContentPresenter.ContentTemplate>
                <DataTemplate>

                </DataTemplate>
            </ContentPresenter.ContentTemplate>
        </ContentPresenter>
    </StackPanel>

Since I have a bunch of these, I would have liked to put all of this in a control template and relocate this in a common resource file.

My template looks like this:

<ControlTemplate x:Key="FormTextBox" TargetType="{x:Type TextBox}">
    <StackPanel Grid.Row="{TemplateBinding Grid.Row}" Grid.Column="{TemplateBinding Grid.Column}">
        <TextBox x:Name="validableText" MaxLength="{TemplateBinding MaxLength}"
                Style="{StaticResource SectionEditPropertyTextBox}"
                Text="{TemplateBinding Text}" />
        <ContentPresenter Visibility="{Binding ElementName=validableText, Path=(Validation.HasError), Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=True }"
                Content="{Binding ElementName=validableText, Path=(Validation.Errors).CurrentItem}"
                HorizontalAlignment="Left">
            <ContentPresenter.ContentTemplate>
                <DataTemplate>

                </DataTemplate>
            </ContentPresenter.ContentTemplate>
        </ContentPresenter>
    </StackPanel>
</ControlTemplate>

and I link to it like this:

    <TextBox Grid.Row="3" Grid.Column="1" MaxLength="200" Template="{StaticResource FormTextBox}"
             Text="{Binding Email, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />

Unfortunately, it doesn't perform any validation so the binding must be broken somehow...

Please advise...

Thanks.

Body:
You won't need the Grid.Row and Grid.Column bindings in the Template StackPanel since the StackPanel won't be the direct child of a Grid anyway,

TemplateBinding is always a OneWay binding so the Text property for the Templated TextBox will never get updated. Change it to a regular Binding with RelativeSource and TwoWay

Change ElementName=validableText to RelativeSource={RelativeSource TemplatedParent} in the bindings for ContentPresenter since we want to perform the validation check on the Templated TextBox and not the TextBox inside the Template.

<ControlTemplate x:Key="FormTextBox" TargetType="{x:Type TextBox}">
    <StackPanel>
        <TextBox x:Name="validableText"
                 MaxLength="{TemplateBinding MaxLength}"
                 Style="{StaticResource SectionEditPropertyTextBox}"
                 Text="{Binding RelativeSource={RelativeSource TemplatedParent},
                                Path=Text,
                                Mode=TwoWay,
                                UpdateSourceTrigger=PropertyChanged}" />
        <ContentPresenter Visibility="{Binding RelativeSource={RelativeSource TemplatedParent},
                                               Path=(Validation.HasError),
                                               Converter={StaticResource BooleanToVisibilityConverter}
                                               ConverterParameter=True}"
                            Content="{Binding RelativeSource={RelativeSource TemplatedParent},
                                              Path=(Validation.Errors).CurrentItem}"
                            HorizontalAlignment="Left">
            <ContentPresenter.ContentTemplate>
                <DataTemplate>
                    <Label Style="{StaticResource SectionEditErrorLabel}" Content="{Binding Path=ErrorContent}"/>
                </DataTemplate>
            </ContentPresenter.ContentTemplate>
        </ContentPresenter>
    </StackPanel>
</ControlTemplate>

On a side note, another alternative that you have here is to create a UserControl with the original piece of Xaml that you had. You could introduce the Dependency Properties needed for your scenario (Text etc.). It would only require small changes.


问:
Getting a TypError saying that my exported function is not a function with nodejs
My goal is to create a discord bot that plays Spotify music, but when I run the function that plays music it gives me the error:

TypeError: playSong is not a function

Here is what is in my api.js:

```<code>const playSong = (songName) => {
    spotifyApi.searchTracks(songName)
        .then(data => {
            const track = data.body.tracks.items[0];
            const trackId = track.id;
            spotifyApi.play({
                device_id: '',
                uris: [`spotify:track:${trackId}`]
            });
        })
        .catch(err => {
            console.error(err);

        });
};

module.exports = { playSong };
</code>```

And here is in my play.js:

```<code>const { playSong } = require('../spotify_api/api.js');

let msg = message.content
        let song = msg.replace('!play ', '');

        //creates the audio player
        if (message.content === `!play ${song}`) {
            //VoiceChannel IDs

            //Audio Player
            const player = createAudioPlayer()
            player.on(AudioPlayerStatus.Playing, () => {
                client.message.reply(`Now playing: ${song}`)
                console.log(`Now playing: ${song}`)
            })

            player.on('error', err => {
                console.log(`Error: ${err.message} with resource`)
            })

            //creat and play audio
            player.play(playSong(song)); //This is where I call the function

            //Subscribe the connection to the audio player
            const subscription = connection.subscribe(player)

            if (subscription) {
                //Unsubscribe the subscription
                setTimeout(() => subscription.unsubscribe(), 120000)
            }

        }
</code>```

I have tried to use other methods I know of but it all comes down to the same TypeError. T_T

答:
Instead of

```<code>module.exports = { playSong };
</code>```

Use

```<code>module.exports.playSong = playSong;
</code>```

Body:
My goal is to create a discord bot that plays Spotify music, but when I run the function that plays music it gives me the error:

TypeError: playSong is not a function

Here is what is in my api.js:

const playSong = (songName) => {
    spotifyApi.searchTracks(songName)
        .then(data => {
            const track = data.body.tracks.items[0];
            const trackId = track.id;
            spotifyApi.play({
                device_id: '',
                uris: [`spotify:track:${trackId}`]
            });
        })
        .catch(err => {
            console.error(err);

        });
};

module.exports = { playSong };

And here is in my play.js:

const { playSong } = require('../spotify_api/api.js');

let msg = message.content
        let song = msg.replace('!play ', '');

        //creates the audio player
        if (message.content === `!play ${song}`) {
            //VoiceChannel IDs

            //Audio Player
            const player = createAudioPlayer()
            player.on(AudioPlayerStatus.Playing, () => {
                client.message.reply(`Now playing: ${song}`)
                console.log(`Now playing: ${song}`)
            })

            player.on('error', err => {
                console.log(`Error: ${err.message} with resource`)
            })

            //creat and play audio
            player.play(playSong(song)); //This is where I call the function

            //Subscribe the connection to the audio player
            const subscription = connection.subscribe(player)

            if (subscription) {
                //Unsubscribe the subscription
                setTimeout(() => subscription.unsubscribe(), 120000)
            }

        }

I have tried to use other methods I know of but it all comes down to the same TypeError. T_T

Body:
Instead of

module.exports = { playSong };

Use

module.exports.playSong = playSong;


问:
Metal Core Image Kernel Sampling
I wrote the following test kernel to understand sampling in Metal Core Image Shaders. What I want to achieve is the following. Any pixel outside the bounds(extent) of the inputImage should be black, other pixels should be pixels of inputImage as usual. But I don't see the desired output so something is wrong in my understanding of how samplers work in shaders. There is no easy way to grab the world coordinates of inputImage, only destination supports world coordinates. Here is my code.

```<code>extern "C" float4 testKernel(coreimage::sampler inputImage, coreimage::destination dest)
 {
  float2 inputCoordinate = inputImage.coord();
  float4 color = inputImage.sample(inputCoordinate);
  float2 inputOrigin = inputImage.origin();
  float2 inputSize = inputImage.size();
  float2 destCoord = dest.coord();

   if (inputCoordinate.x * inputSize.x < destCoord.x || inputCoordinate.y * inputSize.y > destCoord.y) {
       return float4(0.0, 0.0, 0.0, 1.0);
   }

   return color;
}
</code>```

And here is Swift code for the filter:

```<code> class CIMetalTestRenderer: CIFilter {
    var inputImage:CIImage?

    static var kernel:CIKernel = { () -> CIKernel in

    let bundle = Bundle.main
    let url = bundle.url(forResource: "Kernels", withExtension: "ci.metallib")!
    let data = try! Data(contentsOf: url)
    return try! CIKernel(functionName: "testKernel", fromMetalLibraryData: data)

  }()

override var outputImage: CIImage? {
    guard let inputImage = inputImage else {
        return nil
    }

    let dod = inputImage.extent.insetBy(dx: -10, dy: -10)
    return CIMetalTestRenderer.kernel.apply(extent: dod, roiCallback: { index, rect in
        return rect
    }, arguments: [inputImage])
 }
}
</code>```

Update: Here is my full code of ViewController. I just have UIImageView in storyboard (which can be created in viewDidLoad as well):

```<code>class ViewController: UIViewController {

@IBOutlet weak var imageView:UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    generateSolidImage()
}

private func generateSolidImage() {
    let renderSize = imageView.bounds.size

    let solidSize = CGSize(width: renderSize.width * 0.5, height: renderSize.height * 0.5)

    var solidImage = CIImage(color: CIColor(red: 0.3, green: 0.6, blue: 0.754, alpha: 1))

    var cropRect = CGRect.zero
    cropRect.size = solidSize
    solidImage = solidImage.cropped(to: cropRect)
    solidImage = solidImage.transformed(by: CGAffineTransform.init(translationX: -10, y: -10))

    let metalRenderer = CIMetalTestRenderer()
    metalRenderer.inputImage = solidImage

    var outputImage = metalRenderer.outputImage

    outputImage = outputImage?.transformed(by: CGAffineTransform.init(translationX: 20, y: 20))
    let cyanImage = CIImage(color: CIColor.cyan).cropped(to: CGRect(x: 0, y: 0, width: renderSize.width, height: renderSize.height))

    outputImage = outputImage?.composited(over: cyanImage)

    let ciContext = CIContext()

    let cgImage = ciContext.createCGImage(outputImage!, from: outputImage!.extent)

    imageView.image = UIImage(cgImage: cgImage!)

}

}
</code>```

And here are the outputs (by commenting and uncommenting black pixel line respectively).

答:
I think the problem is the comparison with dest.coord() because this also changes depending on the pixel that is currently being processed.

If you just want to check whether you are currently sampling outside the bounds of inputImage, you can simply do the following:

```<code>if (inputCoordinate.x < 0.0 || inputCoordinate.x > 1.0 ||
    inputCoordinate.y < 0.0 || inputCoordinate.y > 1.0) {
    return float4(0.0, 0.0, 0.0, 1.0);
}
</code>```

However, there would be a simpler way to achieve a "clamp-to-black" effect:

```<code>let clapedToBlack = solidImage.composited(over: CIImage.black)
</code>```

Title: Metal Core Image Kernel Sampling

Body:
I wrote the following test kernel to understand sampling in Metal Core Image Shaders. What I want to achieve is the following. Any pixel outside the bounds(extent) of the inputImage should be black, other pixels should be pixels of inputImage as usual. But I don't see the desired output so something is wrong in my understanding of how samplers work in shaders. There is no easy way to grab the world coordinates of inputImage, only destination supports world coordinates. Here is my code.

extern "C" float4 testKernel(coreimage::sampler inputImage, coreimage::destination dest)
 {
  float2 inputCoordinate = inputImage.coord();
  float4 color = inputImage.sample(inputCoordinate);
  float2 inputOrigin = inputImage.origin();
  float2 inputSize = inputImage.size();
  float2 destCoord = dest.coord();

   if (inputCoordinate.x * inputSize.x < destCoord.x || inputCoordinate.y * inputSize.y > destCoord.y) {
       return float4(0.0, 0.0, 0.0, 1.0);
   }

   return color;
}

And here is Swift code for the filter:

 class CIMetalTestRenderer: CIFilter {
    var inputImage:CIImage?

    static var kernel:CIKernel = { () -> CIKernel in

    let bundle = Bundle.main
    let url = bundle.url(forResource: "Kernels", withExtension: "ci.metallib")!
    let data = try! Data(contentsOf: url)
    return try! CIKernel(functionName: "testKernel", fromMetalLibraryData: data)

  }()

override var outputImage: CIImage? {
    guard let inputImage = inputImage else {
        return nil
    }

    let dod = inputImage.extent.insetBy(dx: -10, dy: -10)
    return CIMetalTestRenderer.kernel.apply(extent: dod, roiCallback: { index, rect in
        return rect
    }, arguments: [inputImage])
 }
}

Update: Here is my full code of ViewController. I just have UIImageView in storyboard (which can be created in viewDidLoad as well):

class ViewController: UIViewController {

@IBOutlet weak var imageView:UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    generateSolidImage()
}

private func generateSolidImage() {
    let renderSize = imageView.bounds.size

    let solidSize = CGSize(width: renderSize.width * 0.5, height: renderSize.height * 0.5)

    var solidImage = CIImage(color: CIColor(red: 0.3, green: 0.6, blue: 0.754, alpha: 1))

    var cropRect = CGRect.zero
    cropRect.size = solidSize
    solidImage = solidImage.cropped(to: cropRect)
    solidImage = solidImage.transformed(by: CGAffineTransform.init(translationX: -10, y: -10))

    let metalRenderer = CIMetalTestRenderer()
    metalRenderer.inputImage = solidImage

    var outputImage = metalRenderer.outputImage

    outputImage = outputImage?.transformed(by: CGAffineTransform.init(translationX: 20, y: 20))
    let cyanImage = CIImage(color: CIColor.cyan).cropped(to: CGRect(x: 0, y: 0, width: renderSize.width, height: renderSize.height))

    outputImage = outputImage?.composited(over: cyanImage)

    let ciContext = CIContext()

    let cgImage = ciContext.createCGImage(outputImage!, from: outputImage!.extent)

    imageView.image = UIImage(cgImage: cgImage!)

}

}

And here are the outputs (by commenting and uncommenting black pixel line respectively).

Body:
I think the problem is the comparison with dest.coord() because this also changes depending on the pixel that is currently being processed.

If you just want to check whether you are currently sampling outside the bounds of inputImage, you can simply do the following:

if (inputCoordinate.x < 0.0 || inputCoordinate.x > 1.0 ||
    inputCoordinate.y < 0.0 || inputCoordinate.y > 1.0) {
    return float4(0.0, 0.0, 0.0, 1.0);
}

However, there would be a simpler way to achieve a "clamp-to-black" effect:

let clapedToBlack = solidImage.composited(over: CIImage.black)


问:
SCSS the value of the variable depends on the resolution
i have 3 SCSS variables

```<code>$angle-px: 120px;
$sections-gap: 30px;
$sections-calculated-gap: -($angle-px - $sections-gap);
</code>```

and then im using it that way

```<code> margin-top: $sections-calculated-gap;
</code>```

I need to set by default $angle-px: 40px and if resolution is big, for example

```<code>@media (min-width: 1200px) {}
</code>```

need to set it to 120px, any idea? Thanks

答: Already figured it out. Used css variables instead</p>

Body:
i have 3 SCSS variables

$angle-px: 120px;
$sections-gap: 30px;
$sections-calculated-gap: -($angle-px - $sections-gap);

and then im using it that way

 margin-top: $sections-calculated-gap;

I need to set by default $angle-px: 40px and if resolution is big, for example

@media (min-width: 1200px) {}

need to set it to 120px, any idea? Thanks


问:
In AWS, why am I giving up existing permissions when assuming a role
When you assume a role (user, application or service), you give up your
original permissions and take the permissions assigned to the role. Why can't new permissions from the assumed role be added to the existing ones? Is this to avoid potential security issues when existing and new policies are mixed up?</p>

答:
It would be against least privilege rule. A permissions in a single role should be just enough for a given task to be completed.

Since a role can assume other role, and the other role can assume yet new role, and so on, the cumulative permissions after a chain of assumptions is against the least privilege rule.


答:
If you allocate an array of any kind using operator new[], such as int array[5] = new int[5];, then you will always be able to delete it using operator delete[] (note: not delete), such as delete[] array;.

The compiler achieves this by hiding some extra information regarding the length of the array, often just before its start. Using this information, operator delete[] can tell exactly how much memory to delete.

Note also that NUL terminators have nothing to do with this - the process works in exactly the same way for char arrays as any other type of array.

In summary - you don't need a terminator for an array (of any kind, int, char or otherwise). If you allocate it with new[], you can deallocate it with delete[].

Title: Null terminating int arrays