问:
CVXPY variance minimization problem solver error
I am trying to solve a MIP with cvxpy to optimize a grouping problem (partition a set of students in classes while minimizing the variance of age among the students in a class.) but I can get it to work as long as I don't add a variance calculation to the objective function.

So far I have set up the problem with following version of cvxpy (I also use pandas for input and ouput of problem data from and to file and numpy for matrix/vector manipulation)

```<code>cvxopt==1.3.0
cvxpy==1.2.2
numpy==1.22.0
pandas==1.5.2
</code>```

This is my import block, with the alias given to different modules

import pandas as pd import numpy as np import cvxpy as cp

I then defined mean and variance functions, as found in a blog post for cvxpy

```<code>def mean(x):
    return cp.sum(x) / x.size

def variance(X:cp.Variable, mode='unbiased'):
    if mode == 'unbiased':
        scale = X.size - 1
    elif mode == 'mle':
        scale = X.size
    else:
        raise ValueError('unknown mode: ' + str(mode))
    return cp.sum_squares(X - mean(X)) / scale
</code>```

And based on the above an "age_cost" function to define a component of the objective function that should be minimized, where X is a cvxpy binary variable defined as a matrix with dimensions (number_of_students,available_lessons_number)

```<code>def age_cost(df:pd.DataFrame,X:cp.Variable):
    cost=0
    for i,age in df.Age.items():
        cost+=variance(X[:][i]*age)
    return cost
</code>```

I then defined the other component of the objective function to assign to classes the highest possible number of students

```<code>objective_component1=students_num-assigned @ np.ones(DAYS*SLOTS) @ np.ones(students_num)
</code>```

And defined the objective as :

```<code>objective_component2=age_cost(my_data,assigned)
objective=cp.Minimize(objective_component1+objective_component2)
</code>```

If I then set the problem (I don't think constraints are part of the issue, so I didn't put them in this question) and try to solve it:

```<code>problem1=cp.Problem(objective,constraints)
problem1.solve(verbose=True)
</code>```

This is what I get on terminal:

```<code>===============================================================================
                                     CVXPY
                                     v1.2.2
===============================================================================
(CVXPY) Jan 04 03:09:59 PM: Your problem has 4550 variables, 3382 constraints, and 0 parameters.
(CVXPY) Jan 04 03:10:01 PM: It is compliant with the following grammars: DCP, DQCP
(CVXPY) Jan 04 03:10:01 PM: (If you need to solve this problem multiple times, but with different data, consider using parameters.)
(CVXPY) Jan 04 03:10:01 PM: CVXPY will first compile your problem; then, it will invoke a numerical solver to obtain a solution.
...
<error stack omitted>
...

Either candidate conic solvers (['GLPK_MI']) do not support the cones output by the problem (SOC, NonNeg, Zero), or there are not enough constraints in the problem.
</code>```

If I remove the "age_cost" constraint and redefine the objective as:

objective=cp.Minimize(objective_component1)

Then I obtain a correct solution (with regard to my contraints) and the following output:

```<code>===============================================================================
                                     CVXPY
                                     v1.2.2
===============================================================================
(CVXPY) Jan 04 03:15:24 PM: Your problem has 4550 variables, 3382 constraints, and 0 parameters.
(CVXPY) Jan 04 03:15:26 PM: It is compliant with the following grammars: DCP, DQCP
(CVXPY) Jan 04 03:15:26 PM: (If you need to solve this problem multiple times, but with different data, consider using parameters.)
(CVXPY) Jan 04 03:15:26 PM: CVXPY will first compile your problem; then, it will invoke a numerical solver to obtain a solution.
-------------------------------------------------------------------------------
                                  Compilation
-------------------------------------------------------------------------------
(CVXPY) Jan 04 03:15:29 PM: Compiling problem (target solver=GLPK_MI).
(CVXPY) Jan 04 03:15:29 PM: Reduction chain: Dcp2Cone -> CvxAttr2Constr -> ConeMatrixStuffing -> GLPK_MI
(CVXPY) Jan 04 03:15:29 PM: Applying reduction Dcp2Cone
(CVXPY) Jan 04 03:15:31 PM: Applying reduction CvxAttr2Constr
(CVXPY) Jan 04 03:15:31 PM: Applying reduction ConeMatrixStuffing
(CVXPY) Jan 04 03:15:39 PM: Applying reduction GLPK_MI
(CVXPY) Jan 04 03:15:47 PM: Finished problem compilation (took 2.111e+01 seconds).
-------------------------------------------------------------------------------
                                Numerical solver
-------------------------------------------------------------------------------
(CVXPY) Jan 04 03:15:47 PM: Invoking solver GLPK_MI  to obtain a solution.
      0: obj =  -8.800000000e+01 inf =   7.500e+01 (46)
     68: obj =  -8.800000000e+01 inf =   0.000e+00 (0)
+    68: mip =     not found yet >=              -inf        (1; 0)
+    68: >>>>>  -8.800000000e+01 >=  -8.800000000e+01   0.0% (1; 0)
+    68: mip =  -8.800000000e+01 >=     tree is empty   0.0% (0; 1)
-------------------------------------------------------------------------------
                                    Summary
-------------------------------------------------------------------------------
(CVXPY) Jan 04 03:15:47 PM: Problem status: optimal
(CVXPY) Jan 04 03:15:47 PM: Optimal value: -3.800e+01
(CVXPY) Jan 04 03:15:47 PM: Compilation took 2.111e+01 seconds
(CVXPY) Jan 04 03:15:47 PM: Solver (including time spent in interface) took 1.334e-01 seconds
</code>```

Am I using the wrong solver? If a solver was wrong for the class of my problem how can I understand which solver is feasible for my problem definition? The "compliant with DCP grammar" message I get in the output of the problem means that the problem is well formed ?

Body:
I am trying to solve a MIP with cvxpy to optimize a grouping problem (partition a set of students in classes while minimizing the variance of age among the students in a class.) but I can get it to work as long as I don't add a variance calculation to the objective function.

So far I have set up the problem with following version of cvxpy (I also use pandas for input and ouput of problem data from and to file and numpy for matrix/vector manipulation)

cvxopt==1.3.0
cvxpy==1.2.2
numpy==1.22.0
pandas==1.5.2

This is my import block, with the alias given to different modules

import pandas as pd import numpy as np import cvxpy as cp

I then defined mean and variance functions, as found in a blog post for cvxpy

def mean(x):
    return cp.sum(x) / x.size

def variance(X:cp.Variable, mode='unbiased'):
    if mode == 'unbiased':
        scale = X.size - 1
    elif mode == 'mle':
        scale = X.size
    else:
        raise ValueError('unknown mode: ' + str(mode))
    return cp.sum_squares(X - mean(X)) / scale

And based on the above an "age_cost" function to define a component of the objective function that should be minimized, where X is a cvxpy binary variable defined as a matrix with dimensions (number_of_students,available_lessons_number)

def age_cost(df:pd.DataFrame,X:cp.Variable):
    cost=0
    for i,age in df.Age.items():
        cost+=variance(X[:][i]*age)
    return cost

I then defined the other component of the objective function to assign to classes the highest possible number of students

objective_component1=students_num-assigned @ np.ones(DAYS*SLOTS) @ np.ones(students_num)

And defined the objective as :

objective_component2=age_cost(my_data,assigned)
objective=cp.Minimize(objective_component1+objective_component2)

If I then set the problem (I don't think constraints are part of the issue, so I didn't put them in this question) and try to solve it:

problem1=cp.Problem(objective,constraints)
problem1.solve(verbose=True)

This is what I get on terminal:

===============================================================================
                                     CVXPY
                                     v1.2.2
===============================================================================
(CVXPY) Jan 04 03:09:59 PM: Your problem has 4550 variables, 3382 constraints, and 0 parameters.
(CVXPY) Jan 04 03:10:01 PM: It is compliant with the following grammars: DCP, DQCP
(CVXPY) Jan 04 03:10:01 PM: (If you need to solve this problem multiple times, but with different data, consider using parameters.)
(CVXPY) Jan 04 03:10:01 PM: CVXPY will first compile your problem; then, it will invoke a numerical solver to obtain a solution.
...
<error stack omitted>
...

Either candidate conic solvers (['GLPK_MI']) do not support the cones output by the problem (SOC, NonNeg, Zero), or there are not enough constraints in the problem.

If I remove the "age_cost" constraint and redefine the objective as:

objective=cp.Minimize(objective_component1)

Then I obtain a correct solution (with regard to my contraints) and the following output:

===============================================================================
                                     CVXPY
                                     v1.2.2
===============================================================================
(CVXPY) Jan 04 03:15:24 PM: Your problem has 4550 variables, 3382 constraints, and 0 parameters.
(CVXPY) Jan 04 03:15:26 PM: It is compliant with the following grammars: DCP, DQCP
(CVXPY) Jan 04 03:15:26 PM: (If you need to solve this problem multiple times, but with different data, consider using parameters.)
(CVXPY) Jan 04 03:15:26 PM: CVXPY will first compile your problem; then, it will invoke a numerical solver to obtain a solution.
-------------------------------------------------------------------------------
                                  Compilation
-------------------------------------------------------------------------------
(CVXPY) Jan 04 03:15:29 PM: Compiling problem (target solver=GLPK_MI).
(CVXPY) Jan 04 03:15:29 PM: Reduction chain: Dcp2Cone -> CvxAttr2Constr -> ConeMatrixStuffing -> GLPK_MI
(CVXPY) Jan 04 03:15:29 PM: Applying reduction Dcp2Cone
(CVXPY) Jan 04 03:15:31 PM: Applying reduction CvxAttr2Constr
(CVXPY) Jan 04 03:15:31 PM: Applying reduction ConeMatrixStuffing
(CVXPY) Jan 04 03:15:39 PM: Applying reduction GLPK_MI
(CVXPY) Jan 04 03:15:47 PM: Finished problem compilation (took 2.111e+01 seconds).
-------------------------------------------------------------------------------
                                Numerical solver
-------------------------------------------------------------------------------
(CVXPY) Jan 04 03:15:47 PM: Invoking solver GLPK_MI  to obtain a solution.
      0: obj =  -8.800000000e+01 inf =   7.500e+01 (46)
     68: obj =  -8.800000000e+01 inf =   0.000e+00 (0)
+    68: mip =     not found yet >=              -inf        (1; 0)
+    68: >>>>>  -8.800000000e+01 >=  -8.800000000e+01   0.0% (1; 0)
+    68: mip =  -8.800000000e+01 >=     tree is empty   0.0% (0; 1)
-------------------------------------------------------------------------------
                                    Summary
-------------------------------------------------------------------------------
(CVXPY) Jan 04 03:15:47 PM: Problem status: optimal
(CVXPY) Jan 04 03:15:47 PM: Optimal value: -3.800e+01
(CVXPY) Jan 04 03:15:47 PM: Compilation took 2.111e+01 seconds
(CVXPY) Jan 04 03:15:47 PM: Solver (including time spent in interface) took 1.334e-01 seconds

Am I using the wrong solver? If a solver was wrong for the class of my problem how can I understand which solver is feasible for my problem definition? The "compliant with DCP grammar" message I get in the output of the problem means that the problem is well formed ?


来源: stackexchange

问:
Printing to System.out as UTF-8 regardless of platform default
In Java, System.out.print takes encoding from the platform default.

Suppose you want to always print as UTF-8 regardless of the platform default, what's the most idiomatic/efficient way to do this?

The best idea I have so far is to explicitly spell out two steps, first convert string to UTF-8 bytes with s.getBytes(StandardCharsets.UTF_8), then print the bytes with System.out.write, which bypasses the question of encoding.

Is this the recommended way, or is there a more idiomatic way?

ContentLicense: CC BY-SA 4.0


Title: GMSH Python API - local mesh refinement with setsizecallback

Body:
I would like to perform local mesh refinement depending on physical results obtained with a prior simulation. I am using GMSH and the setSizeCallback(meshSizeCallBack) function to apply the desired mesh size in the refinement region. The obtained results are not the ones expected. I reproduce the issue on a simple example:

The 2 first columns of the data.csv file are the X and Y coordinates of the points that I want to modify. The 3rd column contains the desired mesh size. Note that this file has been truncated because of the text body character limit of the forum, but the issue is still repeatable with the fragment given below.

0.76968 0.26118 0.35535
0.78003 0.26118 0.35535
0.79047 0.26118 0.36046
0.80103 0.26118 0.36046
0.81168 0.26118 0.36286
0.82244 0.26118 0.36515
0.83332 0.26118 0.36954
0.84429 0.26118 0.36954
0.85538 0.26118 0.37177
0.86658 0.26118 0.37402
0.72933 0.26452 0.33849
0.73927 0.26452 0.33849
0.7493  0.26452 0.33584
0.75944 0.26452 0.34139
0.76968 0.26452 0.34139
0.78003 0.26452 0.34956
0.79047 0.26452 0.35461
0.80103 0.26452 0.35461
0.81168 0.26452 0.3538
0.82244 0.26452 0.3538
0.83332 0.26452 0.35864
0.84429 0.26452 0.35864
0.85538 0.26452 0.36109
0.86658 0.26452 0.36354
0.8779  0.26452 0.36845
0.88932 0.26452 0.36845
0.90086 0.26452 0.37091
0.91251 0.26452 0.37579
0.92429 0.26452 0.37579
0.93618 0.26452 0.37821
0.70009 0.26785 0.32107
0.70974 0.26785 0.32409
0.71949 0.26785 0.32708
0.72933 0.26785 0.33297
0.73927 0.26785 0.33297
0.7493  0.26785 0.33584
0.75944 0.26785 0.34139
0.76968 0.26785 0.34139
0.78003 0.26785 0.34127
0.79047 0.26785 0.34127
0.80103 0.26785 0.34375
0.81168 0.26785 0.34626
0.82244 0.26785 0.35621
0.83332 0.26785 0.35621
0.84429 0.26785 0.35864
0.85538 0.26785 0.35887
0.86658 0.26785 0.35887
0.8779  0.26785 0.36393
0.88932 0.26785 0.36393
0.90086 0.26785 0.36897
0.91251 0.26785 0.36897
0.92429 0.26785 0.37821
0.93618 0.26785 0.37821
0.94818 0.26785 0.37642
0.96031 0.26785 0.37887
0.97256 0.26785 0.3837
0.98493 0.26785 0.3837
0.99743 0.26785 0.38609
0.69054 0.27117 0.31086
0.70009 0.27117 0.31086
0.70974 0.27117 0.31391
0.71949 0.27117 0.31991
0.72933 0.27117 0.31991
0.73927 0.27117 0.32283
0.7493  0.27117 0.32845
0.75944 0.27117 0.32845
0.76968 0.27117 0.33112
0.78003 0.27117 0.33374
0.79047 0.27117 0.34375
0.80103 0.27117 0.34375
0.81168 0.27117 0.34626
0.82244 0.27117 0.34877
0.83332 0.27117 0.34934
0.84429 0.27117 0.34934
0.85538 0.27117 0.35887
0.86658 0.27117 0.35887
0.8779  0.27117 0.36393
0.88932 0.27117 0.36393
0.90086 0.27117 0.36897
0.91251 0.27117 0.36897
0.92429 0.27117 0.37395
0.93618 0.27117 0.37395
0.94818 0.27117 0.37642
0.96031 0.27117 0.37499
0.97256 0.27117 0.3837
0.98493 0.27117 0.3837
0.99743 0.27117 0.38609
1.01    0.27117 0.39081
1.0228  0.27117 0.39081
1.0357  0.27117 0.39546
0.68109 0.27446 0.30468
0.69054 0.27446 0.31086
0.70009 0.27446 0.31086
0.70974 0.27446 0.31391
0.71949 0.27446 0.31991
0.72933 0.27446 0.31991
0.73927 0.27446 0.32283
0.7493  0.27446 0.32845
0.75944 0.27446 0.32845
0.76968 0.27446 0.33112
0.78003 0.27446 0.3318
0.79047 0.27446 0.3318
0.80103 0.27446 0.33717
0.81168 0.27446 0.33717
0.82244 0.27446 0.33985
0.83332 0.27446 0.34252
0.84429 0.27446 0.34785
0.85538 0.27446 0.34785
0.86658 0.27446 0.35051
0.8779  0.27446 0.3558
0.88932 0.27446 0.3558
0.90086 0.27446 0.35843
0.91251 0.27446 0.36365
0.92429 0.27446 0.36365
0.93618 0.27446 0.3688
0.94818 0.27446 0.3688
0.96031 0.27446 0.37499
0.97256 0.27446 0.37638
0.98493 0.27446 0.37638
0.99743 0.27446 0.38134
1.01    0.27446 0.38134
1.0228  0.27446 0.38621
1.0357  0.27446 0.38621
1.0487  0.27446 0.38862
1.0618  0.27446 0.39337
1.0751  0.27446 0.39337
1.0885  0.27446 0.40121
0.67172 0.27774 0.29569
0.68109 0.27774 0.29569
0.69054 0.27774 0.2988
0.70009 0.27774 0.30188
0.70974 0.27774 0.30492
0.71949 0.27774 0.31084
0.72933 0.27774 0.31084
0.73927 0.27774 0.31652
0.7493  0.27774 0.31652
0.75944 0.27774 0.31931
0.76968 0.27774 0.32486
0.78003 0.27774 0.32486
0.79047 0.27774 0.3318
0.80103 0.27774 0.33717
0.81168 0.27774 0.33717
0.82244 0.27774 0.33985
0.83332 0.27774 0.34252
0.84429 0.27774 0.34785
0.85538 0.27774 0.34785
0.86658 0.27774 0.35051
0.8779  0.27774 0.3558
0.88932 0.27774 0.3558
0.90086 0.27774 0.35843
0.91251 0.27774 0.36365
0.92429 0.27774 0.36365
0.93618 0.27774 0.3688
0.94818 0.27774 0.3688
0.96031 0.27774 0.37387
0.97256 0.27774 0.37387
0.98493 0.27774 0.37638
0.99743 0.27774 0.38134
1.01    0.27774 0.38134
1.0228  0.27774 0.38621
1.0357  0.27774 0.38621
1.0487  0.27774 0.38788
1.0618  0.27774 0.38788
1.0751  0.27774 0.39029
1.0885  0.27774 0.39505
1.102   0.27774 0.39505
1.1157  0.27774 0.39973
1.1295  0.27774 0.39973
1.1434  0.27774 0.40435
0.67172 0.281   0.29569
0.68109 0.281   0.29569
0.69054 0.281   0.2988
0.70009 0.281   0.30188
0.70974 0.281   0.30076
0.71949 0.281   0.30372
0.72933 0.281   0.3137
0.73927 0.281   0.3137
0.7493  0.281   0.31524
0.75944 0.281   0.31524
0.76968 0.281   0.31808
0.78003 0.281   0.32373
0.79047 0.281   0.32373
0.80103 0.281   0.32654
0.81168 0.281   0.32934
0.82244 0.281   0.33491
0.83332 0.281   0.33491
0.84429 0.281   0.33767
0.85538 0.281   0.34043
0.86658 0.281   0.34591
0.8779  0.281   0.34591
0.88932 0.281   0.34864
0.90086 0.281   0.35135
0.91251 0.281   0.35404
0.92429 0.281   0.35938
0.93618 0.281   0.35938
0.94818 0.281   0.36465
0.96031 0.281   0.36465
0.97256 0.281   0.36725
0.98493 0.281   0.3724
0.99743 0.281   0.3724
1.01    0.281   0.37494
1.0228  0.281   0.38301
1.0357  0.281   0.38301
1.0487  0.281   0.38788
1.0618  0.281   0.38788
1.0751  0.281   0.39029
1.0885  0.281   0.39505
1.102   0.281   0.39505
1.1157  0.281   0.39973
1.1295  0.281   0.39973
1.1434  0.281   0.40435
1.1575  0.281   0.40435
1.1717  0.281   0.40663
1.1861  0.281   0.40623
0.67172 0.28425 0.28457
0.68109 0.28425 0.29077
0.69054 0.28425 0.29077
0.70009 0.28425 0.30076
0.70974 0.28425 0.30076
0.71949 0.28425 0.30372
0.72933 0.28425 0.30563
0.73927 0.28425 0.30563
0.7493  0.28425 0.31524
0.75944 0.28425 0.31524
0.76968 0.28425 0.31808
0.78003 0.28425 0.32373
0.79047 0.28425 0.32373
0.80103 0.28425 0.32579
0.81168 0.28425 0.32579
0.82244 0.28425 0.32862
0.83332 0.28425 0.33767
0.84429 0.28425 0.33767
0.85538 0.28425 0.34043
0.86658 0.28425 0.34591
0.8779  0.28425 0.34591
0.88932 0.28425 0.34864
0.90086 0.28425 0.34809
0.91251 0.28425 0.35404
0.92429 0.28425 0.35621
0.93618 0.28425 0.35621
0.94818 0.28425 0.36154
0.96031 0.28425 0.36154
0.97256 0.28425 0.36725
0.98493 0.28425 0.3724
0.99743 0.28425 0.3724
1.01    0.28425 0.37494
1.0228  0.28425 0.37705
1.0357  0.28425 0.37705
1.0487  0.28425 0.38206
1.0618  0.28425 0.38206
1.0751  0.28425 0.38699
1.0885  0.28425 0.38699
1.102   0.28425 0.38943
1.1157  0.28425 0.39424
1.1295  0.28425 0.39424
1.1434  0.28425 0.39662
1.1575  0.28425 0.39899
1.1717  0.28425 0.40366
1.1861  0.28425 0.40366
1.2006  0.28425 0.40852
1.2152  0.28425 0.41078
1.23    0.28425 0.41056
0.63519 0.28747 0.27185
0.64419 0.28747 0.27505
0.67172 0.28747 0.28085
0.68109 0.28747 0.28394
0.69054 0.28747 0.287
0.70009 0.28747 0.29003
0.70974 0.28747 0.29679
0.71949 0.28747 0.3027
0.72933 0.28747 0.3027
0.73927 0.28747 0.30563
0.7493  0.28747 0.3079
0.75944 0.28747 0.3079
0.76968 0.28747 0.31722
0.78003 0.28747 0.31722
0.79047 0.28747 0.31665
0.80103 0.28747 0.31955
0.81168 0.28747 0.32242
0.82244 0.28747 0.32529
0.83332 0.28747 0.33424
0.84429 0.28747 0.33424
0.85538 0.28747 0.33704
0.86658 0.28747 0.34259
0.8779  0.28747 0.34259
0.88932 0.28747 0.34534
0.90086 0.28747 0.35081
0.91251 0.28747 0.35081
0.92429 0.28747 0.35319
0.93618 0.28747 0.35589
0.94818 0.28747 0.35589
0.96031 0.28747 0.36124
0.97256 0.28747 0.36124
0.98493 0.28747 0.36388
0.99743 0.28747 0.36911
1.01    0.28747 0.36911
1.0228  0.28747 0.37426
1.0357  0.28747 0.37426
1.0487  0.28747 0.3768
1.0618  0.28747 0.38183
1.0751  0.28747 0.38183
1.0885  0.28747 0.38431
1.102   0.28747 0.38678
1.1157  0.28747 0.38923
1.1295  0.28747 0.39165
1.1434  0.28747 0.39406
1.1575  0.28747 0.39883
1.1717  0.28747 0.39883
1.1861  0.28747 0.40353
1.2006  0.28747 0.40353
1.2152  0.28747 0.40586
1.23    0.28747 0.40817
1.245   0.28747 0.41275
1.2601  0.28747 0.41275
1.2753  0.28747 0.41502
0.57465 0.29068 0.24829
0.58304 0.29068 0.24829
0.59152 0.29068 0.25117
0.60008 0.29068 0.25117
0.60872 0.29068 0.25825
0.61746 0.29068 0.25783
0.62628 0.29068 0.26443
0.63519 0.29068 0.26443
0.64419 0.29068 0.2677
0.65327 0.29068 0.2777
0.66245 0.29068 0.2777
0.67172 0.29068 0.28085
0.68109 0.29068 0.28394
0.69054 0.29068 0.287
0.70009 0.29068 0.29003
0.70974 0.29068 0.29253
0.71949 0.29068 0.29253
0.72933 0.29068 0.29555
0.73927 0.29068 0.29855
0.7493  0.29068 0.30453
0.75944 0.29068 0.30453
0.76968 0.29068 0.30749
0.78003 0.29068 0.31375
0.79047 0.29068 0.31665
0.80103 0.29068 0.31955
0.81168 0.29068 0.32242
0.82244 0.29068 0.32529
0.83332 0.29068 0.32814
0.84429 0.29068 0.32787
0.85538 0.29068 0.33662
0.86658 0.29068 0.33662
0.8779  0.29068 0.3392
0.88932 0.29068 0.3392
0.90086 0.29068 0.342
0.91251 0.29068 0.35047
0.92429 0.29068 0.35047
0.93618 0.29068 0.35589
0.94818 0.29068 0.35589
0.96031 0.29068 0.36124
0.97256 0.29068 0.36124
0.98493 0.29068 0.36388
0.99743 0.29068 0.36911
1.01    0.29068 0.36911
1.0228  0.29068 0.37426
1.0357  0.29068 0.37426
1.0487  0.29068 0.3768
1.0618  0.29068 0.38183
1.0751  0.29068 0.38183
1.0885  0.29068 0.38173
1.102   0.29068 0.3867
1.1157  0.29068 0.3867
1.1295  0.29068 0.38915
1.1434  0.29068 0.39401
1.1575  0.29068 0.39401
1.1717  0.29068 0.40119
1.1861  0.29068 0.40119
1.2006  0.29068 0.40353
1.2152  0.29068 0.40586
1.23    0.29068 0.40817
1.245   0.29068 0.41275
1.2601  0.29068 0.41275
1.2753  0.29068 0.41502
1.2907  0.29068 0.41728
1.3063  0.29068 0.41959
1.322   0.29068 0.41959
1.3378  0.29068 0.42407
0.5419  0.29386 0.22779
0.54996 0.29386 0.22779
0.55811 0.29386 0.2343
0.56634 0.29386 0.2343
0.57465 0.29386 0.24091
0.58304 0.29386 0.24091
0.59152 0.29386 0.24757
0.60008 0.29386 0.24757
0.60872 0.29386 0.25424
0.61746 0.29386 0.25424
0.62628 0.29386 0.26087
0.63519 0.29386 0.26087
0.64419 0.29386 0.26415
0.65327 0.29386 0.26739
0.66245 0.29386 0.27411
0.67172 0.29386 0.27725
0.68109 0.29386 0.27997
0.69054 0.29386 0.27997
0.70009 0.29386 0.28306
0.70974 0.29386 0.29253
0.71949 0.29386 0.29253
0.72933 0.29386 0.29555
0.73927 0.29386 0.29855
0.7493  0.29386 0.2983
0.75944 0.29386 0.30453
0.76968 0.29386 0.30749
0.78003 0.29386 0.30729
0.79047 0.29386 0.31026
0.80103 0.29386 0.31615
0.81168 0.29386 0.31615
0.82244 0.29386 0.32198
0.83332 0.29386 0.32198
0.84429 0.29386 0.32488
0.85538 0.29386 0.32776
0.86658 0.29386 0.33063
0.8779  0.29386 0.33348
0.88932 0.29386 0.342
0.90086 0.29386 0.342
0.91251 0.29386 0.34478
0.92429 0.29386 0.34472
0.93618 0.29386 0.34749
0.94818 0.29386 0.35298
0.96031 0.29386 0.35298
0.97256 0.29386 0.35569
0.98493 0.29386 0.35839
0.99743 0.29386 0.36106
1.01    0.29386 0.36372
1.0228  0.29386 0.36897
1.0357  0.29386 0.36897
1.0487  0.29386 0.37669
1.0618  0.29386 0.37669
1.0751  0.29386 0.38173
1.0885  0.29386 0.38173
1.102   0.29386 0.3867
1.1157  0.29386 0.3867
1.1295  0.29386 0.38915
1.1434  0.29386 0.39401
1.1575  0.29386 0.39401
1.1717  0.29386 0.39641
1.1861  0.29386 0.40117
1.2006  0.29386 0.40117
1.2152  0.29386 0.40352
1.23    0.29386 0.40818
1.245   0.29386 0.40818
1.2601  0.29386 0.41049
1.2753  0.29386 0.41506
1.2907  0.29386 0.41506
1.3063  0.29386 0.41959
1.322   0.29386 0.41959
1.3378  0.29386 0.42407
1.3539  0.29386 0.42407
1.3701  0.29386 0.42426
1.3864  0.29386 0.42852
0.51818 0.29703 0.21828
0.52601 0.29703 0.21828
0.53391 0.29703 0.22458
0.5419  0.29703 0.22458
0.54996 0.29703 0.22779
0.55811 0.29703 0.2343
0.56634 0.29703 0.2343
0.57465 0.29703 0.24091
0.58304 0.29703 0.24091
0.59152 0.29703 0.24757
0.60008 0.29703 0.24757
0.60872 0.29703 0.25424
0.61746 0.29703 0.25424
0.62628 0.29703 0.26087
0.63519 0.29703 0.26087
0.64419 0.29703 0.26415
0.65327 0.29703 0.26739
0.66245 0.29703 0.27374
0.67172 0.29703 0.27374
0.68109 0.29703 0.27997
0.69054 0.29703 0.27997
0.70009 0.29703 0.28306
0.70974 0.29703 0.28919
0.71949 0.29703 0.28919
0.72933 0.29703 0.29224
0.73927 0.29703 0.29528
0.7493  0.29703 0.30131
0.75944 0.29703 0.30131
0.76968 0.29703 0.30431
0.78003 0.29703 0.30424
0.79047 0.29703 0.31022
0.80103 0.29703 0.31022
0.81168 0.29703 0.31318
0.82244 0.29703 0.31907
0.83332 0.29703 0.31907
0.84429 0.29703 0.32199
0.85538 0.29703 0.32778
0.86658 0.29703 0.32778
0.8779  0.29703 0.33352
0.88932 0.29703 0.33352
0.90086 0.29703 0.33636
0.91251 0.29703 0.33919
0.92429 0.29703 0.34479
0.93618 0.29703 0.34479
0.94818 0.29703 0.35032
0.96031 0.29703 0.35032
0.97256 0.29703 0.35577
0.98493 0.29703 0.35577
0.99743 0.29703 0.36115
1.01    0.29703 0.36115
1.0228  0.29703 0.36645
1.0357  0.29703 0.36645
1.0487  0.29703 0.36907
1.0618  0.29703 0.37167
1.0751  0.29703 0.37425
1.0885  0.29703 0.37681
1.102   0.29703 0.38188
1.1157  0.29703 0.38188
1.1295  0.29703 0.38687
1.1434  0.29703 0.38687
1.1575  0.29703 0.38934
1.1717  0.29703 0.39179
1.1861  0.29703 0.39422
1.2006  0.29703 0.39887
1.2152  0.29703 0.40125
1.23    0.29703 0.40361
1.245   0.29703 0.40615
1.2601  0.29703 0.40615
1.2753  0.29703 0.41082
1.2907  0.29703 0.41082
1.3063  0.29703 0.41544
1.322   0.29703 0.41544
1.3378  0.29703 0.42001
1.3539  0.29703 0.42001
1.3701  0.29703 0.42453
1.3864  0.29703 0.42453
1.4029  0.29703 0.42903
1.4196  0.29703 0.42903
0.48763 0.30017 0.20023
0.49516 0.30017 0.20312
0.50275 0.30017 0.20316
0.51043 0.30017 0.20907
0.51818 0.30017 0.20907
0.52601 0.30017 0.21515
0.53391 0.30017 0.21515
0.5419  0.30017 0.21825
0.54996 0.30017 0.22456
0.55811 0.30017 0.22456
0.56634 0.30017 0.23099
0.57465 0.30017 0.23099
0.58304 0.30017 0.23753
0.59152 0.30017 0.23753
0.60008 0.30017 0.24082
0.60872 0.30017 0.24413
0.61746 0.30017 0.25409
0.62628 0.30017 0.25409
0.63519 0.30017 0.26068
0.64419 0.30017 0.26068
0.65327 0.30017 0.26392
0.66245 0.30017 0.26712
0.67172 0.30017 0.27032
0.68109 0.30017 0.2735
0.69054 0.30017 0.27665
0.70009 0.30017 0.27975
0.70974 0.30017 0.27975
0.71949 0.30017 0.28288
0.72933 0.30017 0.28599
0.73927 0.30017 0.28908
0.7493  0.30017 0.29216
0.75944 0.30017 0.30124
0.76968 0.30017 0.30124
0.78003 0.30017 0.30424
0.79047 0.30017 0.31022
0.80103 0.30017 0.31022
0.81168 0.30017 0.31318
0.82244 0.30017 0.31907
0.83332 0.30017 0.31907
0.84429 0.30017 0.32199
0.85538 0.30017 0.32778
0.86658 0.30017 0.32778
0.8779  0.30017 0.33352
0.88932 0.30017 0.33352
0.90086 0.30017 0.33636
0.91251 0.30017 0.33919
0.92429 0.30017 0.34479
0.93618 0.30017 0.34479
0.94818 0.30017 0.35032
0.96031 0.30017 0.35032
0.97256 0.30017 0.35577
0.98493 0.30017 0.35577
0.99743 0.30017 0.36115
1.01    0.30017 0.36115
1.0228  0.30017 0.36645
1.0357  0.30017 0.36645
1.0487  0.30017 0.36907
1.0618  0.30017 0.37167
1.0751  0.30017 0.37425
1.0885  0.30017 0.37681
1.102   0.30017 0.38188
1.1157  0.30017 0.38188
1.1295  0.30017 0.38687
1.1434  0.30017 0.38687
1.1575  0.30017 0.38934
1.1717  0.30017 0.39202
1.1861  0.30017 0.39202
1.2006  0.30017 0.39446
1.2152  0.30017 0.39929
1.23    0.30017 0.39929
1.245   0.30017 0.40168
1.2601  0.30017 0.40643
1.2753  0.30017 0.40643
1.2907  0.30017 0.40878
1.3063  0.30017 0.41343
1.322   0.30017 0.41343
1.3378  0.30017 0.42001
1.3539  0.30017 0.42001
1.3701  0.30017 0.42034
1.3864  0.30017 0.42262
1.4029  0.30017 0.42489
1.4196  0.30017 0.42715
1.4364  0.30017 0.4294
1.4534  0.30017 0.43165
1.4706  0.30017 0.43793
0.43702 0.3033  0.17856
0.44404 0.3033  0.17856
0.45112 0.3033  0.18117
0.45828 0.3033  0.1865
0.46551 0.3033  0.1865
0.47281 0.3033  0.19197
0.48019 0.3033  0.19197
0.48763 0.3033  0.19758
0.49516 0.3033  0.19758
0.50275 0.3033  0.20316
0.51043 0.3033  0.20907
0.51818 0.3033  0.20907
0.52601 0.3033  0.21515
0.53391 0.3033  0.21515
0.5419  0.3033  0.21825
0.54996 0.3033  0.22456
0.55811 0.3033  0.22456
0.56634 0.3033  0.23099
0.57465 0.3033  0.23099
0.58304 0.3033  0.23753
0.59152 0.3033  0.23753
0.60008 0.3033  0.24082
0.60872 0.3033  0.24413
0.61746 0.3033  0.24743
0.62628 0.3033  0.25073
0.63519 0.3033  0.25073
0.64419 0.3033  0.25723
0.65327 0.3033  0.25723
0.66245 0.3033  0.26048
0.67172 0.3033  0.26373
0.68109 0.3033  0.2702
0.69054 0.3033  0.2734
0.70009 0.3033  0.27975
0.70974 0.3033  0.27975
0.71949 0.3033  0.28288
0.72933 0.3033  0.28599
0.73927 0.3033  0.28908
0.7493  0.3033  0.29216
0.75944 0.3033  0.29522
0.76968 0.3033  0.29826
0.78003 0.3033  0.30431
0.79047 0.3033  0.30431
0.80103 0.3033  0.31031
0.81168 0.3033  0.31031
0.82244 0.3033  0.31624
0.83332 0.3033  0.31624
0.84429 0.3033  0.31918
0.85538 0.3033  0.32502
0.86658 0.3033  0.32502
0.8779  0.3033  0.32792
0.88932 0.3033  0.3308
0.90086 0.3033  0.33366
0.91251 0.3033  0.3339
0.92429 0.3033  0.33675
0.93618 0.3033  0.33959
0.94818 0.3033  0.3452
0.96031 0.3033  0.3452
0.97256 0.3033  0.34798
0.98493 0.3033  0.35074
0.99743 0.3033  0.35621
1.01    0.3033  0.35621
1.0228  0.3033  0.35891
1.0357  0.3033  0.36426
1.0487  0.3033  0.36426
1.0618  0.3033  0.36691
1.0751  0.3033  0.37214
1.0885  0.3033  0.37214
1.102   0.3033  0.3773
1.1157  0.3033  0.3773
1.1295  0.3033  0.38238
1.1434  0.3033  0.38238
1.1575  0.3033  0.38739
1.1717  0.3033  0.38739
1.1861  0.3033  0.39202
1.2006  0.3033  0.39446
1.2152  0.3033  0.39929
1.23    0.3033  0.39929
1.245   0.3033  0.40202
1.2601  0.3033  0.40202
1.2753  0.3033  0.40878
1.2907  0.3033  0.40878
1.3063  0.3033  0.41343
1.322   0.3033  0.41343
1.3378  0.3033  0.41613
1.3539  0.3033  0.41613
1.3701  0.3033  0.41844
1.3864  0.3033  0.42074
1.4029  0.3033  0.42531
1.4196  0.3033  0.42531
1.4364  0.3033  0.4294
1.4534  0.3033  0.43165
1.4706  0.3033  0.43211
1.488   0.3033  0.43436
1.5055  0.3033  0.43885
1.5232  0.3033  0.43885
0.37692 0.3064  0.15421
0.38333 0.3064  0.1565
0.38981 0.3064  0.15883
0.39636 0.3064  0.16119
0.40297 0.3064  0.16357
0.40964 0.3064  0.16615
0.41639 0.3064  0.16615
0.4232  0.3064  0.16862
0.43007 0.3064  0.17112
0.43702 0.3064  0.17365
0.44404 0.3064  0.17621
0.45112 0.3064  0.17881
0.45828 0.3064  0.18143
0.46551 0.3064  0.18409
0.47281 0.3064  0.18678
0.48019 0.3064  0.1895
0.48763 0.3064  0.19226
0.49516 0.3064  0.19506
0.50275 0.3064  0.20076
0.51043 0.3064  0.20076
0.51818 0.3064  0.20661
0.52601 0.3064  0.20661
0.53391 0.3064  0.20959
0.5419  0.3064  0.21566
0.54996 0.3064  0.21566
0.55811 0.3064  0.22186
0.56634 0.3064  0.22186
0.57465 0.3064  0.22819
0.58304 0.3064  0.22819
0.59152 0.3064  0.2346
0.60008 0.3064  0.2346
0.60872 0.3064  0.24106
0.61746 0.3064  0.24106
0.62628 0.3064  0.25073
0.63519 0.3064  0.25073
0.64419 0.3064  0.25081
0.65327 0.3064  0.25406
0.66245 0.3064  0.26058
0.67172 0.3064  0.26058
0.68109 0.3064  0.26709
0.69054 0.3064  0.26709
0.70009 0.3064  0.27357
0.70974 0.3064  0.27357
0.71949 0.3064  0.27999
0.72933 0.3064  0.27999
0.73927 0.3064  0.28317
0.7493  0.3064  0.28944
0.75944 0.3064  0.28944
0.76968 0.3064  0.29561
0.78003 0.3064  0.29561
0.79047 0.3064  0.30173
0.80103 0.3064  0.30173
0.81168 0.3064  0.3105
0.82244 0.3064  0.3105
0.83332 0.3064  0.31348
0.84429 0.3064  0.31644
0.85538 0.3064  0.31969
0.86658 0.3064  0.31969
0.8779  0.3064  0.32815
0.88932 0.3064  0.32815
0.90086 0.3064  0.3339
0.91251 0.3064  0.3339
0.92429 0.3064  0.33675
0.93618 0.3064  0.33959
0.94818 0.3064  0.3452
0.96031 0.3064  0.3452
0.97256 0.3064  0.34798
0.98493 0.3064  0.35074
0.99743 0.3064  0.35621
1.01    0.3064  0.35621
1.0228  0.3064  0.35891
1.0357  0.3064  0.36426
1.0487  0.3064  0.36426
1.0618  0.3064  0.3646
1.0751  0.3064  0.37214
1.0885  0.3064  0.37214
1.102   0.3064  0.37508
1.1157  0.3064  0.37508
1.1295  0.3064  0.38021
1.1434  0.3064  0.38021
1.1575  0.3064  0.38526
1.1717  0.3064  0.38526
1.1861  0.3064  0.38987
1.2006  0.3064  0.39233
1.2152  0.3064  0.39721
1.23    0.3064  0.39721
1.245   0.3064  0.40202
1.2601  0.3064  0.40202
1.2753  0.3064  0.40441
1.2907  0.3064  0.40913
1.3063  0.3064  0.40913
1.322   0.3064  0.41148
1.3378  0.3064  0.41613
1.3539  0.3064  0.41613
1.3701  0.3064  0.41844
1.3864  0.3064  0.42074
1.4029  0.3064  0.42531
1.4196  0.3064  0.42531
1.4364  0.3064  0.42808
1.4534  0.3064  0.42808
1.4706  0.3064  0.43211
1.488   0.3064  0.43263
1.5055  0.3064  0.43489
1.5232  0.3064  0.43715
1.5411  0.3064  0.44166
1.5591  0.3064  0.44166

The GMSH code run with Python API is given below:

import gmsh
import numpy as np
from scipy.interpolate import NearestNDInterpolator
import matplotlib.pyplot as plt
import numpy
import csv

def meshSizeCallback(dim, tag, x, y, z, lc):
    return min(lc, background_field(x,y))

gmsh.initialize()
lc=0.2
gmsh.option.setNumber("Mesh.CharacteristicLengthMax", lc)
# Building the geometry
gmsh.model.occ.addPoint(0,0,0,lc)
gmsh.model.occ.addPoint(0,0.5,0,lc)
gmsh.model.occ.addPoint(3,0.5,0,lc)
gmsh.model.occ.addPoint(3,0,0,lc)
gmsh.model.occ.addLine(1,2)
gmsh.model.occ.addLine(2,3)
gmsh.model.occ.addLine(3,4)
gmsh.model.occ.addLine(4,1)
gmsh.model.occ.addCurveLoop([1,2,3,4],1)
gmsh.model.occ.addPlaneSurface([1],2)
gmsh.model.occ.synchronize()

# Reading the data.csv file containing the point coordinates as well as the desired cell size
background_field = []
with open('coord_regions_int_maillage_B_threshold_14_maj_Delta_2D.csv','r',encoding="utf8", errors='ignore') as csvfile:
    points = csv.reader(csvfile, delimiter = ',')
    for [x,y,ls] in points: # for each point in the csv file
        background_field.append([float(x), float(y), float(ls)/10]) #the mesh size is divided by 10 in order to clearly separate the refinement region from the rest of the mesh

background_field = np.array(background_field)
X = background_field[:,0]
Y = background_field[:,1]
# Interpolating the background field (required for the call back function)
background_field = NearestNDInterpolator(background_field[:,0:2], background_field[:,2]) # First input: point coordinates, Second input: value

gmsh.model.mesh.setSizeCallback(meshSizeCallback) # Keep the minimum cell size between the background and the intial mesh size

# Generating 2D mesh
gmsh.model.mesh.generate(2)

# Writing the mesh
gmsh.write("maillage_auto.msh")

gmsh.fltk.run()
gmsh.finalize()

# Plot the surface in Python to compare with the GMSH results
plt.scatter(X, Y, c=background_field(X,Y))
plt.xlabel("X")
plt.ylabel("Y")
plt.colorbar()
plt.show()

Unfortunately, the refined area obtained with GMSH is different from the refined area given by the background_field (see attached pictures). May someone help me to understand why the refined area obtained in GMSH does not correspond with the region described in data.csv? Moreover, the mesh size is the non refined region is smaller than the prescribed mesh size lc=0.2. What is the reason for this result ?

Thanks a lot for your answer!


问:
Render a view ignoring router template
I am creating an Admin Dashboard with vitejs, vue3 and vue-router. Exists 2 different templates for all views:

Views having a sidebar:

/buildings

/users

/companies

View with a full-width where the user can login or signup:

/login

/signup

Each component is render in the App.vue file with a sidebar:

<template>

<router-link to="/buildings">Buildings</router-link>

<router-link to="/companies">Companies</router-link>

        <router-view/>

</template>
```
<p>However, for <code>/login</code> view I need to display a different template because there is no reason to display a sidebar with links in a login form. Because both cases differ in template format, how can I use different templates for a unique router but for different views? Many thanks for considering my request.</p>
<p>I have tried Nested routes, but I am forced to changing all my routes to uses <code>children</code> key, for example:</p>
<pre class="lang-json prettyprint-override"><code>
    // Routes dashboard
    {
        path: '/admin',
        component: TemplateWithSidebar, // template 1
        children: [
            {
                path: 'companies',
                component: CompaniesView,
            }
        ]
    },

    // Routes for login
    {
        path: '/l',
        component: TemplateWithoutSidebar, // template 2
        children: [
            {
                path: 'login',
                component: LoginView,
            }
        ]
    },
</code>```

Then my App.vue was changed to:

<template>

    <router-view/>

</template>
```

I am not experienced enough to determinates if this practice is valid for a production environment o weather exists another best alternative.

Title: Render a view ignoring router template

Body:
I am creating an Admin Dashboard with vitejs, vue3 and vue-router. Exists 2 different templates for all views:

Views having a sidebar:

/buildings

/users

/companies

View with a full-width where the user can login or signup:

/login

/signup

Each component is render in the App.vue file with a sidebar:

<template>

<router-link to="/buildings">Buildings</router-link>

<router-link to="/companies">Companies</router-link>

        <router-view/>

</template>

However, for /login view I need to display a different template because there is no reason to display a sidebar with links in a login form. Because both cases differ in template format, how can I use different templates for a unique router but for different views? Many thanks for considering my request.

I have tried Nested routes, but I am forced to changing all my routes to uses children key, for example:

    // Routes dashboard
    {
        path: '/admin',
        component: TemplateWithSidebar, // template 1
        children: [
            {
                path: 'companies',
                component: CompaniesView,
            }
        ]
    },

    // Routes for login
    {
        path: '/l',
        component: TemplateWithoutSidebar, // template 2
        children: [
            {
                path: 'login',
                component: LoginView,
            }
        ]
    },

Then my App.vue was changed to:

<template>

    <router-view/>

</template>

I am not experienced enough to determinates if this practice is valid for a production environment o weather exists another best alternative.


问:
React: setState called twice even after spreading previous state
So, i have faced similar issues in the past, but could always figure out where i am missing to spread or assign a new object, while trying to update previous state. But i can't seem to figure out what i am doing wrong this time.

I have a state, in a functional component, that looks like this:

```<code>formData = {name: '', features: []}
</code>```

And trying to update the features array with the following snippet:

```<code>function handleUpdate(featureUID) {
 console.log('Called parent')

 setFormData(prev => {
   const spread = Object.assign({}, prev)
   let features = [...spread.features]
   if (features.includes(featureUID)) {
     features = features.filter(x => x !== featureUID)
   } else {
     features = [...features, featureUID]
   }
   console.log('Features:', features)
   spread.features = [...features]

   return spread
 })
}
</code>```

So as you can see, i am initially assigning a shallow-copied version of prev to spread and further down, i also create a shallow copy of the features array.

But seems like after the first invocation of this method, on all consequent calls triggers the setState twice.

What am i missing here?

Edit 1

Forgot to mention the function that holds the setFormData aka setState is only being called once, confirmed via console logging. The way i am calling it:

```<code>{otherList?.map(single => <Button key={single.uid} onClick={() => handleUpdate(single.uid)}/>)}
</code>```

Edit 2

I am aware of the fact that StrictMode causes the twice calling of setState. But i also know why it's that way. So not willing to remove StrictMode

Edit 3

Tried this and seems to work:

```<code>setFormData(prev => ({
  ...prev,
  features: prev.features.includes(featureUID)
    ? prev.features.filter(x => x !== featureUID)
    : [...prev.features, featureUID]
}))
</code>```

But what i don't understand is, Why ? What did i miss in my first approach?

Body:
So, i have faced similar issues in the past, but could always figure out where i am missing to spread or assign a new object, while trying to update previous state. But i can't seem to figure out what i am doing wrong this time.

I have a state, in a functional component, that looks like this:

formData = {name: '', features: []}

And trying to update the features array with the following snippet:

function handleUpdate(featureUID) {
 console.log('Called parent')

 setFormData(prev => {
   const spread = Object.assign({}, prev)
   let features = [...spread.features]
   if (features.includes(featureUID)) {
     features = features.filter(x => x !== featureUID)
   } else {
     features = [...features, featureUID]
   }
   console.log('Features:', features)
   spread.features = [...features]

   return spread
 })
}

So as you can see, i am initially assigning a shallow-copied version of prev to spread and further down, i also create a shallow copy of the features array.

But seems like after the first invocation of this method, on all consequent calls triggers the setState twice.

What am i missing here?

Edit 1

Forgot to mention the function that holds the setFormData aka setState is only being called once, confirmed via console logging. The way i am calling it:

{otherList?.map(single => <Button key={single.uid} onClick={() => handleUpdate(single.uid)}/>)}

Edit 2

I am aware of the fact that StrictMode causes the twice calling of setState. But i also know why it's that way. So not willing to remove StrictMode

Edit 3

Tried this and seems to work:

setFormData(prev => ({
  ...prev,
  features: prev.features.includes(featureUID)
    ? prev.features.filter(x => x !== featureUID)
    : [...prev.features, featureUID]
}))

But what i don't understand is, Why ? What did i miss in my first approach?


问:
Getting data from sql using Power Shell will return the number of rows as first entity
I have the following table inside SQL:-

```<code>/****** Script for SelectTopNRows command from SSMS  ******/
SELECT TOP (1000) [ORG_UNIT]
      ,[Rollup_Business]
      ,[Rollup_Region]
  FROM [Flavors_DevEx].[dbo].[BU_ROLLUP]
</code>```

and when i execute the following Power Shell to retrieve all the data :-

```<code>Function ProcessSQLServerDataBU_ROLLUP([string]$DBServer, [string]$DBName, [string]$Query)
{
 try
  {
      $conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=True;Initial Catalog=$DBName")
      $conn.Open();
      $query = $Query
      $dap = new-object System.Data.SqlClient.SqlDataAdapter($query,$conn);
      $dt = new-object System.Data.DataTable;
      $dap.Fill($dt);
          foreach($r in $dt.Rows)
           {
              Write-Host $r["ORG_UNIT"]
           }
$conn.Close();
   }
 catch
 {
     #Write error message on screen and to a LOG file
     write-host $_.Exception.Message
     $_.Exception.Message >> "d:\error.log"
  }
  finally
  {
       $ErrorActionPreference = "Continue"
  }
}

ProcessSQLServerDataBU_ROLLUP "(localdb)\ProjectsV13" "Flavors_DevEx" "SELECT [ORG_UNIT] FROM [BU_ROLLUP]"
</code>```

i will get this result (where 4 represents the number of rows).. so how i can eliminate this number? and only show the data itself?

```<code>4
1
11
111
1111
</code>```

Thanks

Body:
I have the following table inside SQL:-

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT TOP (1000) [ORG_UNIT]
      ,[Rollup_Business]
      ,[Rollup_Region]
  FROM [Flavors_DevEx].[dbo].[BU_ROLLUP]

and when i execute the following Power Shell to retrieve all the data :-

Function ProcessSQLServerDataBU_ROLLUP([string]$DBServer, [string]$DBName, [string]$Query)
{
 try
  {
      $conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=True;Initial Catalog=$DBName")
      $conn.Open();
      $query = $Query
      $dap = new-object System.Data.SqlClient.SqlDataAdapter($query,$conn);
      $dt = new-object System.Data.DataTable;
      $dap.Fill($dt);
          foreach($r in $dt.Rows)
           {
              Write-Host $r["ORG_UNIT"]
           }
$conn.Close();
   }
 catch
 {
     #Write error message on screen and to a LOG file
     write-host $_.Exception.Message
     $_.Exception.Message >> "d:\error.log"
  }
  finally
  {
       $ErrorActionPreference = "Continue"
  }
}

ProcessSQLServerDataBU_ROLLUP "(localdb)\ProjectsV13" "Flavors_DevEx" "SELECT [ORG_UNIT] FROM [BU_ROLLUP]"

i will get this result (where 4 represents the number of rows).. so how i can eliminate this number? and only show the data itself?

4
1
11
111
1111

Thanks


问:
How to zoom and center a PhotoViewer image in PyQt6
I am trying to instantiate a Photo using the PhotoViewer class by calling the method setPhoto of the following :

```<code>from PyQt6 import QtCore, QtWidgets, QtGui

class PhotoViewer(QtWidgets.QGraphicsView):
    photoClicked = QtCore.pyqtSignal(QtCore.QPointF)

    def __init__(self, parent):
        super(PhotoViewer, self).__init__(parent)
        self._zoom = 0
        self._empty = True
        self._scene = QtWidgets.QGraphicsScene(self)
        self._photo = QtWidgets.QGraphicsPixmapItem()
        self._scene.addItem(self._photo)
        self.setScene(self._scene)
        self.setTransformationAnchor(QtWidgets.QGraphicsView.ViewportAnchor.AnchorUnderMouse)
        self.setResizeAnchor(QtWidgets.QGraphicsView.ViewportAnchor.AnchorUnderMouse)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30)))
        self.setFrameShape(QtWidgets.QFrame.Shape.NoFrame)

    def hasPhoto(self):
        return not self._empty

    def fitInView(self, scale=True):
        rect = QtCore.QRectF(self._photo.pixmap().rect())
        if not rect.isNull():
            self.setSceneRect(rect)
            if self.hasPhoto():
                unity = self.transform().mapRect(QtCore.QRectF(0, 0, 1, 1))
                self.scale(1 / unity.width(), 1 / unity.height())
                viewrect = self.viewport().rect()
                scenerect = self.transform().mapRect(rect)
                factor = min(viewrect.width() / scenerect.width(),
                             viewrect.height() / scenerect.height())

                print(viewrect.width(), scenerect.width(), viewrect.height(), scenerect.height())
                self.scale(factor, factor)
            self._zoom = 0

    def setPhoto(self, pixmap=None):
        self._zoom = 0

        if pixmap and not pixmap.isNull():
            self._empty = False
            self.setDragMode(QtWidgets.QGraphicsView.DragMode.ScrollHandDrag)
            self._photo.setPixmap(pixmap)
        else:
            self._empty = True
            self.setDragMode(QtWidgets.QGraphicsView.DragMode.NoDrag)
            self._photo.setPixmap(QtGui.QPixmap())
        self.fitInView()

        # I want to set here a given zoom and set view to the center of the image

    def wheelEvent(self, event):
        if self.hasPhoto():
            if event.angleDelta().y() > 0:
                factor = 1.25
                self._zoom += 1
            else:
                factor = 0.8
                self._zoom -= 1
            if self._zoom > 0:
                self.scale(factor, factor)
            elif self._zoom == 0:
                self.fitInView()
            else:
                self._zoom = 0

    def toggleDragMode(self):
        if self.dragMode() == QtWidgets.QGraphicsView.DragMode.ScrollHandDrag:
            self.setDragMode(QtWidgets.QGraphicsView.DragMode.NoDrag)
        elif not self._photo.pixmap().isNull():
            self.setDragMode(QtWidgets.QGraphicsView.DragMode.ScrollHandDrag)

    def mousePressEvent(self, event):
        if self._photo.isUnderMouse():
            print(event.position())
            self.photoClicked.emit(self.mapToScene(event.position().toPoint()))

        super(PhotoViewer, self).mousePressEvent(event)
</code>```

I am working with python 3.9 and PyQt6.

I would like to have a given starting zoom (i.e. 20%) and have the image centered into the viewrect (which is the size of the rectangle in which the image is displayed). I have tried setting the self.scale but I could not find a working solution to move the image to its center.

Body:
I am trying to instantiate a Photo using the PhotoViewer class by calling the method setPhoto of the following :

from PyQt6 import QtCore, QtWidgets, QtGui

class PhotoViewer(QtWidgets.QGraphicsView):
    photoClicked = QtCore.pyqtSignal(QtCore.QPointF)

    def __init__(self, parent):
        super(PhotoViewer, self).__init__(parent)
        self._zoom = 0
        self._empty = True
        self._scene = QtWidgets.QGraphicsScene(self)
        self._photo = QtWidgets.QGraphicsPixmapItem()
        self._scene.addItem(self._photo)
        self.setScene(self._scene)
        self.setTransformationAnchor(QtWidgets.QGraphicsView.ViewportAnchor.AnchorUnderMouse)
        self.setResizeAnchor(QtWidgets.QGraphicsView.ViewportAnchor.AnchorUnderMouse)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30)))
        self.setFrameShape(QtWidgets.QFrame.Shape.NoFrame)

    def hasPhoto(self):
        return not self._empty

    def fitInView(self, scale=True):
        rect = QtCore.QRectF(self._photo.pixmap().rect())
        if not rect.isNull():
            self.setSceneRect(rect)
            if self.hasPhoto():
                unity = self.transform().mapRect(QtCore.QRectF(0, 0, 1, 1))
                self.scale(1 / unity.width(), 1 / unity.height())
                viewrect = self.viewport().rect()
                scenerect = self.transform().mapRect(rect)
                factor = min(viewrect.width() / scenerect.width(),
                             viewrect.height() / scenerect.height())

                print(viewrect.width(), scenerect.width(), viewrect.height(), scenerect.height())
                self.scale(factor, factor)
            self._zoom = 0

    def setPhoto(self, pixmap=None):
        self._zoom = 0

        if pixmap and not pixmap.isNull():
            self._empty = False
            self.setDragMode(QtWidgets.QGraphicsView.DragMode.ScrollHandDrag)
            self._photo.setPixmap(pixmap)
        else:
            self._empty = True
            self.setDragMode(QtWidgets.QGraphicsView.DragMode.NoDrag)
            self._photo.setPixmap(QtGui.QPixmap())
        self.fitInView()

        # I want to set here a given zoom and set view to the center of the image

    def wheelEvent(self, event):
        if self.hasPhoto():
            if event.angleDelta().y() > 0:
                factor = 1.25
                self._zoom += 1
            else:
                factor = 0.8
                self._zoom -= 1
            if self._zoom > 0:
                self.scale(factor, factor)
            elif self._zoom == 0:
                self.fitInView()
            else:
                self._zoom = 0

    def toggleDragMode(self):
        if self.dragMode() == QtWidgets.QGraphicsView.DragMode.ScrollHandDrag:
            self.setDragMode(QtWidgets.QGraphicsView.DragMode.NoDrag)
        elif not self._photo.pixmap().isNull():
            self.setDragMode(QtWidgets.QGraphicsView.DragMode.ScrollHandDrag)

    def mousePressEvent(self, event):
        if self._photo.isUnderMouse():
            print(event.position())
            self.photoClicked.emit(self.mapToScene(event.position().toPoint()))

        super(PhotoViewer, self).mousePressEvent(event)

I am working with python 3.9 and PyQt6.

I would like to have a given starting zoom (i.e. 20%) and have the image centered into the viewrect (which is the size of the rectangle in which the image is displayed). I have tried setting the self.scale but I could not find a working solution to move the image to its center.


问:
How to compare a picture sent by a bot with a picture from my file
Please tell me if there are analogs of the operation:

```<code>if(message.text == "text"):
</code>```

for pictures. I want a certain image to be executed for a certain image.

I tried like this:

```<code>if(message.photo == "img/1(1).jpg"):
</code>```
```<code>p = open('img/1 (1).jpg', 'rb')
if(p == "img/1 (1).jpg"):
</code>```

but the result is the same, nothing works

in general, I need to compare the picture sent by the bot with the picture from my file

Body:
Please tell me if there are analogs of the operation:

if(message.text == "text"):

for pictures. I want a certain image to be executed for a certain image.

I tried like this:

if(message.photo == "img/1(1).jpg"):

p = open('img/1 (1).jpg', 'rb')
if(p == "img/1 (1).jpg"):

but the result is the same, nothing works

in general, I need to compare the picture sent by the bot with the picture from my file


问:
Blazor server side upload file to Azure Blob Storage
I am using a file upload component that posts the file to an API controller and this works ok but i need to get the progres of the upload.

```<code>[HttpPost("upload/single")]
        public async Task SingleAsync(IFormFile file)

        {
            try
            {

                    // Azure connection string and container name passed as an argument to get the Blob reference of the container.
                    var container = new BlobContainerClient(azureConnectionString, "upload-container");

                    // Method to create our container if it doesn’t exist.
                    var createResponse = await container.CreateIfNotExistsAsync();

                    // If container successfully created, then set public access type to Blob.
                    if (createResponse != null && createResponse.GetRawResponse().Status == 201)
                        await container.SetAccessPolicyAsync(Azure.Storage.Blobs.Models.PublicAccessType.Blob);

                    // Method to create a new Blob client.
                    var blob = container.GetBlobClient(file.FileName);

                    // If a blob with the same name exists, then we delete the Blob and its snapshots.
                    await blob.DeleteIfExistsAsync(Azure.Storage.Blobs.Models.DeleteSnapshotsOption.IncludeSnapshots);

                // Create a file stream and use the UploadSync method to upload the Blob.

                uploadFileSize = file.Length;

                var progressHandler = new Progress<long>();
                progressHandler.ProgressChanged += UploadProgressChanged;

                    using (var fileStream = file.OpenReadStream())
                    {
                        await blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType = file.ContentType },progressHandler:progressHandler);
                    }

                Response.StatusCode = 400;

            }
            catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 204;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
        }

        private double GetProgressPercentage(double totalSize, double currentSize)
        {
            return (currentSize / totalSize) * 100;
        }

        private void UploadProgressChanged(object sender, long bytesUploaded)
        {
            uploadPercentage = GetProgressPercentage(uploadFileSize, bytesUploaded);
        }
</code>```

I am posting this file and it does upload but the file upload progress event is inaccurate it says the file upload is complete after a few seconds when in reality the file takes ~90 secs on my connection to appear in the Azure Blob Storage container.

So in the code above i have the progress handler which works (I can put a break point on it and see it increasing) but how do I return this value to the UI?

I found one solution that used Microsoft.AspNetCore.SignalR but I can't manage to integrate this into my own code and I'm not even sure if I'm on the right track.

```<code>using BlazorReportProgress.Server.Hubs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System.Threading;

namespace BlazorReportProgress.Server.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SlowProcessController : ControllerBase
    {
        private readonly ILogger<SlowProcessController> _logger;
        private readonly IHubContext<ProgressHub> _hubController;

        public SlowProcessController(
            ILogger<SlowProcessController> logger,
            IHubContext<ProgressHub> hubContext)
        {
            _logger = logger;
            _hubController = hubContext;
        }

        [HttpGet("{ClientID}")]
        public IEnumerable<int> Get(string ClientID)
        {
            List<int> retVal = new();

            _logger.LogInformation("Incoming call from ClientID : {ClientID}", ClientID);

            _hubController.Clients.Client(ClientID).SendAsync("ProgressReport", "Starting...");
            Thread.Sleep(1000);

            for (int loop = 0; loop < 10; loop++)
            {
                _hubController.Clients.Client(ClientID).SendAsync("ProgressReport", loop.ToString());

                retVal.Add(loop);
                Thread.Sleep(500);
            }

            _hubController.Clients.Client(ClientID).SendAsync("ProgressReport", "Done!");

            return retVal;
        }
    }
}
</code>```

I read the Steve Sandersen blog but this says not to use the code as its been superceded by inbuilt blazor functionality.

My application is only for a few users and so i'm not too worried about backend APIs etc, If the upload component used a service not a controller I could more easily get the progress, but the compoents all seem to post to controllers.

Can anyone please enlighten me as to the best way to solve this?

Body:
I am using a file upload component that posts the file to an API controller and this works ok but i need to get the progres of the upload.

[HttpPost("upload/single")]
        public async Task SingleAsync(IFormFile file)

        {
            try
            {

                    // Azure connection string and container name passed as an argument to get the Blob reference of the container.
                    var container = new BlobContainerClient(azureConnectionString, "upload-container");

                    // Method to create our container if it doesn’t exist.
                    var createResponse = await container.CreateIfNotExistsAsync();

                    // If container successfully created, then set public access type to Blob.
                    if (createResponse != null && createResponse.GetRawResponse().Status == 201)
                        await container.SetAccessPolicyAsync(Azure.Storage.Blobs.Models.PublicAccessType.Blob);

                    // Method to create a new Blob client.
                    var blob = container.GetBlobClient(file.FileName);

                    // If a blob with the same name exists, then we delete the Blob and its snapshots.
                    await blob.DeleteIfExistsAsync(Azure.Storage.Blobs.Models.DeleteSnapshotsOption.IncludeSnapshots);

                // Create a file stream and use the UploadSync method to upload the Blob.

                uploadFileSize = file.Length;

                var progressHandler = new Progress<long>();
                progressHandler.ProgressChanged += UploadProgressChanged;

                    using (var fileStream = file.OpenReadStream())
                    {
                        await blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType = file.ContentType },progressHandler:progressHandler);
                    }

                Response.StatusCode = 400;

            }
            catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 204;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
        }

        private double GetProgressPercentage(double totalSize, double currentSize)
        {
            return (currentSize / totalSize) * 100;
        }

        private void UploadProgressChanged(object sender, long bytesUploaded)
        {
            uploadPercentage = GetProgressPercentage(uploadFileSize, bytesUploaded);
        }

I am posting this file and it does upload but the file upload progress event is inaccurate it says the file upload is complete after a few seconds when in reality the file takes ~90 secs on my connection to appear in the Azure Blob Storage container.

So in the code above i have the progress handler which works (I can put a break point on it and see it increasing) but how do I return this value to the UI?

I found one solution that used Microsoft.AspNetCore.SignalR but I can't manage to integrate this into my own code and I'm not even sure if I'm on the right track.

using BlazorReportProgress.Server.Hubs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System.Threading;

namespace BlazorReportProgress.Server.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SlowProcessController : ControllerBase
    {
        private readonly ILogger<SlowProcessController> _logger;
        private readonly IHubContext<ProgressHub> _hubController;

        public SlowProcessController(
            ILogger<SlowProcessController> logger,
            IHubContext<ProgressHub> hubContext)
        {
            _logger = logger;
            _hubController = hubContext;
        }

        [HttpGet("{ClientID}")]
        public IEnumerable<int> Get(string ClientID)
        {
            List<int> retVal = new();

            _logger.LogInformation("Incoming call from ClientID : {ClientID}", ClientID);

            _hubController.Clients.Client(ClientID).SendAsync("ProgressReport", "Starting...");
            Thread.Sleep(1000);

            for (int loop = 0; loop < 10; loop++)
            {
                _hubController.Clients.Client(ClientID).SendAsync("ProgressReport", loop.ToString());

                retVal.Add(loop);
                Thread.Sleep(500);
            }

            _hubController.Clients.Client(ClientID).SendAsync("ProgressReport", "Done!");

            return retVal;
        }
    }
}

I read the Steve Sandersen blog but this says not to use the code as its been superceded by inbuilt blazor functionality.

My application is only for a few users and so i'm not too worried about backend APIs etc, If the upload component used a service not a controller I could more easily get the progress, but the compoents all seem to post to controllers.

Can anyone please enlighten me as to the best way to solve this?


问:
Error exporting Python Coverage to XML "no such table: tracer"
After run coverage with unittest i got this error:

Command:
coverage xml -i -o coverage.xml

Give me this error:

```<code>Couldn't use data file 'project/coverage.xml': no such table: tracer
</code>```
```<code>Python: 3.6.9
Coverage: 6.2
</code>```

Body:
After run coverage with unittest i got this error:

Command:
coverage xml -i -o coverage.xml

Give me this error:

Couldn't use data file 'project/coverage.xml': no such table: tracer

Python: 3.6.9
Coverage: 6.2


问:
How can I install firebase to my flutter-project with Firebase-CLI?
How can I install firebase to my flutter-project with Firebase-CLI?

https://firebase.google.com/docs/flutter/setup?platform=android

->

I installed Firebase CLI.

When i try:

```<code>firebase login
</code>```

I'm able to login, but after the next step:

```<code>dart pub global activate flutterfire_cli
</code>```

it says:

Quote: "Warning: Pub installs executables into
C:\Users\mynick\AppData\Local\Pub\Cache\bin, which is not on your
path.

You can fix that by adding that directory to your system's "Path"
environment variable.

A web search for "configure windows path" will show you how.

Activated flutterfire_cli 0.2.7."

-> Unfortunatelly, I don't get it. How can I fix this? thx! :)

Body:
How can I install firebase to my flutter-project with Firebase-CLI?

https://firebase.google.com/docs/flutter/setup?platform=android

->

I installed Firebase CLI.

When i try:

firebase login

I'm able to login, but after the next step:

dart pub global activate flutterfire_cli

it says:

Quote: "Warning: Pub installs executables into
C:\Users\mynick\AppData\Local\Pub\Cache\bin, which is not on your
path.

You can fix that by adding that directory to your system's "Path"
environment variable.

A web search for "configure windows path" will show you how.

Activated flutterfire_cli 0.2.7."

-> Unfortunatelly, I don't get it. How can I fix this? thx! :)


问:
How hide title? Vanpra datepicker in compose
I use a calendar from vanpra. I managed to hide the title. But I still have a huge headline. imageThat's what I have at the moment.

That's what I'd like to get. And can I somehow not use the new view with darkening around? I want to use date selection to view the schedule.image

```<code>       Box(
                modifier = Modifier
                    .fillMaxSize(0.5f)
            ) {

                dateDialogState.show()
                // настройки сценария/поведения (отклонение и т.д.)
                MaterialDialog(
                    dialogState = dateDialogState,
                    backgroundColor = subviewsBackground,

                ) {
                    // сам выбор даты
                    datepicker(
                        // текущая дата
                        initialDate = LocalDate.now(),
                        colors = DatePickerDefaults.colors(
                            dateActiveBackgroundColor = Color.Red,
                            dateActiveTextColor = Color.White,
                            dateInactiveTextColor = Color.White,
                            calendarHeaderTextColor = Color.White,
                            headerBackgroundColor = subviewsBackground
                        ),
                        waitForPositiveButton = false,

                        // разрешенная дата
                        allowedDateValidator = {
                            it.dayOfMonth % 2 == 1
                        }
                    ) {
                        pickedDate = it
                    }
                }
            }
</code>```

Body:
I use a calendar from vanpra. I managed to hide the title. But I still have a huge headline. imageThat's what I have at the moment.

That's what I'd like to get. And can I somehow not use the new view with darkening around? I want to use date selection to view the schedule.image

       Box(
                modifier = Modifier
                    .fillMaxSize(0.5f)
            ) {

                dateDialogState.show()
                // настройки сценария/поведения (отклонение и т.д.)
                MaterialDialog(
                    dialogState = dateDialogState,
                    backgroundColor = subviewsBackground,

                ) {
                    // сам выбор даты
                    datepicker(
                        // текущая дата
                        initialDate = LocalDate.now(),
                        colors = DatePickerDefaults.colors(
                            dateActiveBackgroundColor = Color.Red,
                            dateActiveTextColor = Color.White,
                            dateInactiveTextColor = Color.White,
                            calendarHeaderTextColor = Color.White,
                            headerBackgroundColor = subviewsBackground
                        ),
                        waitForPositiveButton = false,

                        // разрешенная дата
                        allowedDateValidator = {
                            it.dayOfMonth % 2 == 1
                        }
                    ) {
                        pickedDate = it
                    }
                }
            }


问:
Vuelidate - passes validation, but the function does not work after it
I have a form where the user has to enter a field value:

```<code><template>

<div class="authentication-template">
    <div class="authentication-template__inner">
        <div class="authentication-template__content">
            <div class="authentication-template__form-stage">
                Этап 1 из 3
            </div>
            <h2>{{ title }}</h2>
            <form @submit.prevent="submitHandler" class="authentication-template__form" action="">

                <div class="authentication-template__form-item">
                    <p>Номер телефона</p>
                    <input
                        type="text"
                        placeholder="+7(921)123-45-67"
                        maxlength="16"
                        :class="$v.phone.$error ? 'invalid' : ''"
                        v-model.trim="phone"
                        v-imask="phoneNumberMask"
                        @accept="onAccept"
                        @complete="onComplete"
                        @keypress="isNumber"
                    >
                    <p v-if="$v.phone.$dirty && !$v.phone.required" class="invalid-feedback">Обязательное поле для заполнения</p>
                    <p v-if="$v.phone.$dirty && !$v.phone.minLength" class="invalid-feedback">Данное поле должно содержать номер телефона</p>
                    <p v-if="phone_status == 'error'" class="invalid-feedback">Данный номер телефона уже существует</p>
                </div>

                <div class="authentication-template__enter">
                    Еще нет аккаунта? <router-link tag="a" :to="url"><a href="#">Войти</a></router-link>
                </div>
                <div class="authentication-template__button">
                    <button class="button" type="submit">
                        {{buttonText}}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
</code>```

This is my validations:

```<code>validations: {
    phone: {required, minLength: minLength(16)},

},
</code>```

This is my function where does this validation work:

```<code>submitHandler(){
        this.$v.$touch()
        if(!this.$v.$error){

            axios.post('http://127.0.0.1:8000/api/v1/check-number/',
                {
                    phone_number: this.phone
                }
            ).then((response) => {
                this.phone_status = response.data.status
                if(this.phone_status == 'success'){
                    localStorage.setItem('phone', this.phone)
                    this.$router.push('/register/2')
                }
            })
        }
    }
</code>```

I enter a value in the field that matches the validation, but after if(!this.$v.$error), my axios request doesn't work, I suspect my if condition is wrong, I'm sitting with this problem for a long time, please can anyone help me?

UPD: if i comment this.$v.$touch() my axios request is work, as I understand it, my form still does not pass validation?

Body:
I have a form where the user has to enter a field value:

<template>

                Этап 1 из 3

{{ title }}

            <form @submit.prevent="submitHandler" class="authentication-template__form" action="">

Номер телефона

                    <input
                        type="text"
                        placeholder="+7(921)123-45-67"
                        maxlength="16"
                        :class="$v.phone.$error ? 'invalid' : ''"
                        v-model.trim="phone"
                        v-imask="phoneNumberMask"
                        @accept="onAccept"
                        @complete="onComplete"
                        @keypress="isNumber"
                    >

Обязательное поле для заполнения

Данное поле должно содержать номер телефона

Данный номер телефона уже существует

                    Еще нет аккаунта? <router-link tag="a" :to="url">Войти</router-link>

                    <button class="button" type="submit">
                        {{buttonText}}
                    </button>

            </form>

This is my validations:

validations: {
    phone: {required, minLength: minLength(16)},

},

This is my function where does this validation work:

submitHandler(){
        this.$v.$touch()
        if(!this.$v.$error){

            axios.post('http://127.0.0.1:8000/api/v1/check-number/',
                {
                    phone_number: this.phone
                }
            ).then((response) => {
                this.phone_status = response.data.status
                if(this.phone_status == 'success'){
                    localStorage.setItem('phone', this.phone)
                    this.$router.push('/register/2')
                }
            })
        }
    }

I enter a value in the field that matches the validation, but after if(!this.$v.$error), my axios request doesn't work, I suspect my if condition is wrong, I'm sitting with this problem for a long time, please can anyone help me?

UPD: if i comment this.$v.$touch() my axios request is work, as I understand it, my form still does not pass validation?


问:
RuntimeError: running_mean should contain 1876 elements not 938
```<code># encoder <- 과거의 데이터를 바탕으로 미래를 예측 (t-1의 인과성 학습)
# decoder <- 미래의 데이터를 바탕으로 과거를 예측 (t+1의 인과성 학습)
class TimeAutoEncoder(nn.Module):
    def __init__(self):
        super(TimeAutoEncoder, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv1d(in_channels = 48, out_channels = 1876, kernel_size = 3, stride = 1, padding = 0, dilation = 1),
            nn.BatchNorm1d(1876),
            nn.ReLU(),
        )

        self.conv2 = nn.Sequential(
            nn.Conv1d(in_channels = 1876, out_channels = 938, kernel_size = 3, stride = 1, padding = 0, dilation = 2),
            nn.BatchNorm1d(938),
            nn.ReLU(),
        )

        self.conv3 = nn.Sequential(
            nn.Conv1d(in_channels = 938, out_channels = 512, kernel_size = 3, stride = 1, padding = 0, dilation = 4),
            nn.BatchNorm1d(512),
            nn.ReLU(),
        )

        self.conv4 = nn.Sequential(
            nn.Conv1d(in_channels = 512, out_channels = 256, kernel_size = 3, stride = 1, padding = 0, dilation = 8),
            nn.BatchNorm1d(256),
            nn.ReLU(),
        )

        self.conv5 = nn.Sequential(
            nn.Conv1d(in_channels = 256, out_channels = 128, kernel_size = 3, stride = 1, padding = 0, dilation = 16),
            nn.BatchNorm1d(128),
            nn.ReLU(),
        )

        self.conv6 = nn.Sequential(
            nn.Conv1d(in_channels = 128, out_channels = 64, kernel_size = 3, stride = 1, padding = 0, dilation = 32),
            nn.BatchNorm1d(64),
            nn.ReLU(),
        )

        self.conv7 = nn.Sequential(
            nn.Conv1d(in_channels = 64, out_channels = 32, kernel_size = 3, stride = 1, padding = 0, dilation = 64),
            nn.BatchNorm1d(32),
            nn.ReLU(),
        )

        self.conv8 = nn.Sequential(
            nn.Conv1d(in_channels = 32, out_channels = 16, kernel_size = 3, stride = 1, padding = 0, dilation = 128),
            nn.BatchNorm1d(16),
            nn.ReLU(),
        )

        self.conv9 = nn.Sequential(
            nn.Conv1d(in_channels = 16, out_channels = 8, kernel_size = 3, stride = 1, padding = 0, dilation = 256),
            nn.BatchNorm1d(8),
            nn.ReLU(),
        )

        self.encoder_fc = nn.Sequential(
            nn.Linear(8 * 1876, 128),
            nn.BatchNorm1d(128),
            nn.Tanh(),
        )

        self.decoder_fc = nn.Sequential(
            nn.Linear(128, 8 * 1876),
            nn.ReLU(),
        )

        self.t_conv1 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 8, out_channels = 16, kernel_size  = 3, stride = 1, dilation=62),
            nn.Conv1d(in_channels = 8, out_channels = 16, kernel_size = 3, stride = 1, padding = 0, dilation = 256),
            nn.BatchNorm1d(16),
            nn.ReLU(),
        )

        self.t_conv2 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 16, out_channels = 32, kernel_size  = 3, stride = 1, dilation = 30),
            nn.Conv1d(in_channels = 16, out_channels = 32, kernel_size = 3, stride = 1, padding = 0, dilation = 128),
            nn.BatchNorm1d(32),
            nn.ReLU(),
        )

        self.t_conv3 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 32, out_channels = 64, kernel_size  = 3, stride = 1, dilation=14),
            nn.Conv1d(in_channels = 32, out_channels = 64, kernel_size = 3, stride = 1, padding = 0, dilation = 64),
            nn.BatchNorm1d(64),
            nn.ReLU(),
        )

        self.t_conv4 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 64, out_channels = 128, kernel_size  = 3, stride = 1, dilation = 6),
            nn.Conv1d(in_channels = 64, out_channels = 128, kernel_size = 3, stride = 1, padding = 0, dilation = 32),
            nn.BatchNorm1d(128),
            nn.ReLU(),
        )

        self.t_conv5 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 128, out_channels = 256, kernel_size  = 3, stride = 1, dilation=2),
            nn.Conv1d(in_channels = 128, out_channels = 256, kernel_size = 3, stride = 1, padding = 0, dilation = 16),
            nn.BatchNorm1d(256),
            nn.ReLU(),
        )

        self.t_conv6 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 256, out_channels = 512, kernel_size  = 3, stride = 1, dilation = 1),
            nn.Conv1d(in_channels = 256, out_channels = 512, kernel_size = 3, stride = 1, padding = 0, dilation = 8),
            nn.BatchNorm1d(512),
            nn.ReLU(),
        )

        self.t_conv7 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 256, out_channels = 512, kernel_size  = 3, stride = 1, dilation = 1),
            nn.Conv1d(in_channels = 512, out_channels = 938, kernel_size = 3, stride = 1, padding = 0, dilation = 4),
            nn.BatchNorm1d(938),
            nn.ReLU(),
        )

        self.t_conv8 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 256, out_channels = 512, kernel_size  = 3, stride = 1, dilation = 1),
            nn.Conv1d(in_channels = 938, out_channels = 1876, kernel_size = 3, stride = 1, padding = 0, dilation = 2),
            nn.BatchNorm1d(1876),
            nn.ReLU(),
        )

        self.t_conv9 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 512, out_channels = 48, kernel_size  = 3, stride = 1, dilation= 1),
            nn.Conv1d(in_channels = 1876, out_channels = 48, kernel_size = 3, stride = 1, padding = 0, dilation = 1)
        )

    def forward(self, mel_spec):
        x = F.pad(mel_spec, pad = (2, 0, 0, 0))
        x = self.conv1(x)
        # print(x.shape)
        x = F.pad(x, pad = (4, 0, 0, 0))
        x = self.conv2(x)
        # print(x.shape)
        x = F.pad(x, pad = (8, 0, 0, 0))
        x = self.conv3(x)
        # print(x.shape)
        x = F.pad(x, pad = (16, 0, 0, 0))
        x = self.conv4(x)
        # print(x.shape)
        x = F.pad(x, pad = (32, 0, 0, 0))
        x = self.conv5(x)
        # print(x.shape)
        x = F.pad(x, pad = (64, 0, 0, 0))
        x = self.conv6(x)
        # print(x.shape)
        x = F.pad(x, pad = (128, 0, 0, 0))
        x = self.conv7(x)
        x = F.pad(x, pad = (256, 0, 0, 0))
        x = self.conv8(x)
        x = F.pad(x, pad = (512, 0, 0, 0))
        x = self.conv9(x)
        # print(x.shape)
        encode = self.encoder_fc(x.view(-1, 8 * 1876))

        # print('decode')
        x = self.decoder_fc(encode)
        x = x.view(-1, 8, 1876)
        x = torch.swapaxes(torch.fliplr(torch.swapaxes(x, 1, 2)), 1, 2)
        x = F.pad(x, pad = (512, 0, 0, 0))
        x = self.t_conv1(x)
        x = F.pad(x, pad = (256, 0, 0, 0))
        x = self.t_conv2(x)
        x = F.pad(x, pad = (128, 0, 0, 0))
        x = self.t_conv3(x)
        # print(x.shape)
        x = F.pad(x, pad = (64, 0, 0, 0))
        x = self.t_conv4(x)
        # print(x.shape)
        x = F.pad(x, pad = (32, 0, 0, 0))
        x = self.t_conv5(x)
        # print(x.shape)
        x = F.pad(x, pad = (16, 0, 0, 0))
        x = self.t_conv6(x)
        # print(x.shape)
        x = F.pad(x, pad = (8, 0, 0, 0))
        x = self.t_conv7(x)
        # print(x.shape)
        x = F.pad(x, pad = (4, 0, 0, 0))
        x = self.t_conv8(x)
        # print(x.shape)
        x = F.pad(x, pad = (2, 0, 0, 0))
        x = self.t_conv9(x)
        # print(x.shape)
        x = torch.swapaxes(torch.fliplr(torch.swapaxes(x, 1, 2)), 1, 2)

        return encode, x

import time

min_loss = 987654321

for epoch in range(1, epochs + 1):
    start = time.time()
    train_loss = train(model = model, train_loader = train_batch_li)
    val_loss = val(model = model, train_loader = val_batch_li)
    end = time.time()

    print(f'EPOCH:{epoch}, Train Loss:{train_loss}, Val Loss:{val_loss}, 학습 시간: {end - start}')
    if val_loss < min_loss:
        min_loss = val_loss
        torch.save(model.state_dict(), model_dir + f'TimeAutoEncoder_val.pt')
        print('모델 저장')
</code>```

After running the above code, the error is like the following

```<code>---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/var/folders/br/5b5sgky977xdm4cgcc_mvds00000gn/T/ipykernel_19816/1986897196.py in <module>
      5 for epoch in range(1, epochs + 1):
      6     start = time.time()
----> 7     train_loss = train(model = model, train_loader = train_batch_li)
      8     val_loss = val(model = model, train_loader = val_batch_li)
      9     end = time.time()

/var/folders/br/5b5sgky977xdm4cgcc_mvds00000gn/T/ipykernel_19816/1176484610.py in train(model, train_loader)
     20       optimizer.zero_grad()
     21
---> 22       encode, output = model(mel)
     23
     24       loss = criterion(output, mel)

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1192         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194             return forward_call(*input, **kwargs)
   1195         # Do not call functions when jit is used
   1196         full_backward_hooks, non_full_backward_hooks = [], []

/var/folders/br/5b5sgky977xdm4cgcc_mvds00000gn/T/ipykernel_19816/2004772610.py in forward(self, mel_spec)
    135         # print(x.shape)
    136         x = F.pad(x, pad = (4, 0, 0, 0))
--> 137         x = self.conv2(x)
    138         # print(x.shape)
    139         x = F.pad(x, pad = (8, 0, 0, 0))

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1192         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194             return forward_call(*input, **kwargs)
   1195         # Do not call functions when jit is used
   1196         full_backward_hooks, non_full_backward_hooks = [], []

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/container.py in forward(self, input)
    202     def forward(self, input):
    203         for module in self:
--> 204             input = module(input)
    205         return input
    206

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1192         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194             return forward_call(*input, **kwargs)
   1195         # Do not call functions when jit is used
   1196         full_backward_hooks, non_full_backward_hooks = [], []

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/batchnorm.py in forward(self, input)
    169         used for normalization (i.e. in eval mode when buffers are not None).
    170         """
--> 171         return F.batch_norm(
    172             input,
    173             # If buffers are not to be tracked, ensure that they won't be updated

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/functional.py in batch_norm(input, running_mean, running_var, weight, bias, training, momentum, eps)
   2448         _verify_batch_size(input.size())
   2449
-> 2450     return torch.batch_norm(
   2451         input, weight, bias, running_mean, running_var, training, momentum, eps, torch.backends.cudnn.enabled
   2452     )

RuntimeError: running_mean should contain 1876 elements not 938
</code>```

What would be the problem? I tried to make a change to the code related to the error message. But it doesn't work.

The error says that running_mean should contain 1876 elements not 938. As I searched on the other questions on stack overflow, I've found out that the I've to change number 1876 to 938. But I still don't know understand what this means.

Body:
# encoder <- 과거의 데이터를 바탕으로 미래를 예측 (t-1의 인과성 학습)
# decoder <- 미래의 데이터를 바탕으로 과거를 예측 (t+1의 인과성 학습)
class TimeAutoEncoder(nn.Module):
    def __init__(self):
        super(TimeAutoEncoder, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv1d(in_channels = 48, out_channels = 1876, kernel_size = 3, stride = 1, padding = 0, dilation = 1),
            nn.BatchNorm1d(1876),
            nn.ReLU(),
        )

        self.conv2 = nn.Sequential(
            nn.Conv1d(in_channels = 1876, out_channels = 938, kernel_size = 3, stride = 1, padding = 0, dilation = 2),
            nn.BatchNorm1d(938),
            nn.ReLU(),
        )

        self.conv3 = nn.Sequential(
            nn.Conv1d(in_channels = 938, out_channels = 512, kernel_size = 3, stride = 1, padding = 0, dilation = 4),
            nn.BatchNorm1d(512),
            nn.ReLU(),
        )

        self.conv4 = nn.Sequential(
            nn.Conv1d(in_channels = 512, out_channels = 256, kernel_size = 3, stride = 1, padding = 0, dilation = 8),
            nn.BatchNorm1d(256),
            nn.ReLU(),
        )

        self.conv5 = nn.Sequential(
            nn.Conv1d(in_channels = 256, out_channels = 128, kernel_size = 3, stride = 1, padding = 0, dilation = 16),
            nn.BatchNorm1d(128),
            nn.ReLU(),
        )

        self.conv6 = nn.Sequential(
            nn.Conv1d(in_channels = 128, out_channels = 64, kernel_size = 3, stride = 1, padding = 0, dilation = 32),
            nn.BatchNorm1d(64),
            nn.ReLU(),
        )

        self.conv7 = nn.Sequential(
            nn.Conv1d(in_channels = 64, out_channels = 32, kernel_size = 3, stride = 1, padding = 0, dilation = 64),
            nn.BatchNorm1d(32),
            nn.ReLU(),
        )

        self.conv8 = nn.Sequential(
            nn.Conv1d(in_channels = 32, out_channels = 16, kernel_size = 3, stride = 1, padding = 0, dilation = 128),
            nn.BatchNorm1d(16),
            nn.ReLU(),
        )

        self.conv9 = nn.Sequential(
            nn.Conv1d(in_channels = 16, out_channels = 8, kernel_size = 3, stride = 1, padding = 0, dilation = 256),
            nn.BatchNorm1d(8),
            nn.ReLU(),
        )

        self.encoder_fc = nn.Sequential(
            nn.Linear(8 * 1876, 128),
            nn.BatchNorm1d(128),
            nn.Tanh(),
        )

        self.decoder_fc = nn.Sequential(
            nn.Linear(128, 8 * 1876),
            nn.ReLU(),
        )

        self.t_conv1 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 8, out_channels = 16, kernel_size  = 3, stride = 1, dilation=62),
            nn.Conv1d(in_channels = 8, out_channels = 16, kernel_size = 3, stride = 1, padding = 0, dilation = 256),
            nn.BatchNorm1d(16),
            nn.ReLU(),
        )

        self.t_conv2 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 16, out_channels = 32, kernel_size  = 3, stride = 1, dilation = 30),
            nn.Conv1d(in_channels = 16, out_channels = 32, kernel_size = 3, stride = 1, padding = 0, dilation = 128),
            nn.BatchNorm1d(32),
            nn.ReLU(),
        )

        self.t_conv3 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 32, out_channels = 64, kernel_size  = 3, stride = 1, dilation=14),
            nn.Conv1d(in_channels = 32, out_channels = 64, kernel_size = 3, stride = 1, padding = 0, dilation = 64),
            nn.BatchNorm1d(64),
            nn.ReLU(),
        )

        self.t_conv4 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 64, out_channels = 128, kernel_size  = 3, stride = 1, dilation = 6),
            nn.Conv1d(in_channels = 64, out_channels = 128, kernel_size = 3, stride = 1, padding = 0, dilation = 32),
            nn.BatchNorm1d(128),
            nn.ReLU(),
        )

        self.t_conv5 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 128, out_channels = 256, kernel_size  = 3, stride = 1, dilation=2),
            nn.Conv1d(in_channels = 128, out_channels = 256, kernel_size = 3, stride = 1, padding = 0, dilation = 16),
            nn.BatchNorm1d(256),
            nn.ReLU(),
        )

        self.t_conv6 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 256, out_channels = 512, kernel_size  = 3, stride = 1, dilation = 1),
            nn.Conv1d(in_channels = 256, out_channels = 512, kernel_size = 3, stride = 1, padding = 0, dilation = 8),
            nn.BatchNorm1d(512),
            nn.ReLU(),
        )

        self.t_conv7 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 256, out_channels = 512, kernel_size  = 3, stride = 1, dilation = 1),
            nn.Conv1d(in_channels = 512, out_channels = 938, kernel_size = 3, stride = 1, padding = 0, dilation = 4),
            nn.BatchNorm1d(938),
            nn.ReLU(),
        )

        self.t_conv8 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 256, out_channels = 512, kernel_size  = 3, stride = 1, dilation = 1),
            nn.Conv1d(in_channels = 938, out_channels = 1876, kernel_size = 3, stride = 1, padding = 0, dilation = 2),
            nn.BatchNorm1d(1876),
            nn.ReLU(),
        )

        self.t_conv9 = nn.Sequential(
            # nn.ConvTranspose1d(in_channels = 512, out_channels = 48, kernel_size  = 3, stride = 1, dilation= 1),
            nn.Conv1d(in_channels = 1876, out_channels = 48, kernel_size = 3, stride = 1, padding = 0, dilation = 1)
        )

    def forward(self, mel_spec):
        x = F.pad(mel_spec, pad = (2, 0, 0, 0))
        x = self.conv1(x)
        # print(x.shape)
        x = F.pad(x, pad = (4, 0, 0, 0))
        x = self.conv2(x)
        # print(x.shape)
        x = F.pad(x, pad = (8, 0, 0, 0))
        x = self.conv3(x)
        # print(x.shape)
        x = F.pad(x, pad = (16, 0, 0, 0))
        x = self.conv4(x)
        # print(x.shape)
        x = F.pad(x, pad = (32, 0, 0, 0))
        x = self.conv5(x)
        # print(x.shape)
        x = F.pad(x, pad = (64, 0, 0, 0))
        x = self.conv6(x)
        # print(x.shape)
        x = F.pad(x, pad = (128, 0, 0, 0))
        x = self.conv7(x)
        x = F.pad(x, pad = (256, 0, 0, 0))
        x = self.conv8(x)
        x = F.pad(x, pad = (512, 0, 0, 0))
        x = self.conv9(x)
        # print(x.shape)
        encode = self.encoder_fc(x.view(-1, 8 * 1876))

        # print('decode')
        x = self.decoder_fc(encode)
        x = x.view(-1, 8, 1876)
        x = torch.swapaxes(torch.fliplr(torch.swapaxes(x, 1, 2)), 1, 2)
        x = F.pad(x, pad = (512, 0, 0, 0))
        x = self.t_conv1(x)
        x = F.pad(x, pad = (256, 0, 0, 0))
        x = self.t_conv2(x)
        x = F.pad(x, pad = (128, 0, 0, 0))
        x = self.t_conv3(x)
        # print(x.shape)
        x = F.pad(x, pad = (64, 0, 0, 0))
        x = self.t_conv4(x)
        # print(x.shape)
        x = F.pad(x, pad = (32, 0, 0, 0))
        x = self.t_conv5(x)
        # print(x.shape)
        x = F.pad(x, pad = (16, 0, 0, 0))
        x = self.t_conv6(x)
        # print(x.shape)
        x = F.pad(x, pad = (8, 0, 0, 0))
        x = self.t_conv7(x)
        # print(x.shape)
        x = F.pad(x, pad = (4, 0, 0, 0))
        x = self.t_conv8(x)
        # print(x.shape)
        x = F.pad(x, pad = (2, 0, 0, 0))
        x = self.t_conv9(x)
        # print(x.shape)
        x = torch.swapaxes(torch.fliplr(torch.swapaxes(x, 1, 2)), 1, 2)

        return encode, x

import time

min_loss = 987654321

for epoch in range(1, epochs + 1):
    start = time.time()
    train_loss = train(model = model, train_loader = train_batch_li)
    val_loss = val(model = model, train_loader = val_batch_li)
    end = time.time()

    print(f'EPOCH:{epoch}, Train Loss:{train_loss}, Val Loss:{val_loss}, 학습 시간: {end - start}')
    if val_loss < min_loss:
        min_loss = val_loss
        torch.save(model.state_dict(), model_dir + f'TimeAutoEncoder_val.pt')
        print('모델 저장')

After running the above code, the error is like the following

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/var/folders/br/5b5sgky977xdm4cgcc_mvds00000gn/T/ipykernel_19816/1986897196.py in <module>
      5 for epoch in range(1, epochs + 1):
      6     start = time.time()
----> 7     train_loss = train(model = model, train_loader = train_batch_li)
      8     val_loss = val(model = model, train_loader = val_batch_li)
      9     end = time.time()

/var/folders/br/5b5sgky977xdm4cgcc_mvds00000gn/T/ipykernel_19816/1176484610.py in train(model, train_loader)
     20       optimizer.zero_grad()
     21
---> 22       encode, output = model(mel)
     23
     24       loss = criterion(output, mel)

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1192         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194             return forward_call(*input, **kwargs)
   1195         # Do not call functions when jit is used
   1196         full_backward_hooks, non_full_backward_hooks = [], []

/var/folders/br/5b5sgky977xdm4cgcc_mvds00000gn/T/ipykernel_19816/2004772610.py in forward(self, mel_spec)
    135         # print(x.shape)
    136         x = F.pad(x, pad = (4, 0, 0, 0))
--> 137         x = self.conv2(x)
    138         # print(x.shape)
    139         x = F.pad(x, pad = (8, 0, 0, 0))

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1192         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194             return forward_call(*input, **kwargs)
   1195         # Do not call functions when jit is used
   1196         full_backward_hooks, non_full_backward_hooks = [], []

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/container.py in forward(self, input)
    202     def forward(self, input):
    203         for module in self:
--> 204             input = module(input)
    205         return input
    206

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1192         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194             return forward_call(*input, **kwargs)
   1195         # Do not call functions when jit is used
   1196         full_backward_hooks, non_full_backward_hooks = [], []

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/modules/batchnorm.py in forward(self, input)
    169         used for normalization (i.e. in eval mode when buffers are not None).
    170         """
--> 171         return F.batch_norm(
    172             input,
    173             # If buffers are not to be tracked, ensure that they won't be updated

/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/torch/nn/functional.py in batch_norm(input, running_mean, running_var, weight, bias, training, momentum, eps)
   2448         _verify_batch_size(input.size())
   2449
-> 2450     return torch.batch_norm(
   2451         input, weight, bias, running_mean, running_var, training, momentum, eps, torch.backends.cudnn.enabled
   2452     )

RuntimeError: running_mean should contain 1876 elements not 938

What would be the problem? I tried to make a change to the code related to the error message. But it doesn't work.

The error says that running_mean should contain 1876 elements not 938. As I searched on the other questions on stack overflow, I've found out that the I've to change number 1876 to 938. But I still don't know understand what this means.