问:
DAX language- Microsoft Power BI - SUMMARIZE inside SELECTCOLUMNS - simple syntax
I have a situation below (Power BI - DAX) in which I am trying to SUMMARIZE a table called Product with a SUM aggregation to get the total cost of all products in each Category; but then I have to change the column name of one or two columns in the summarized result set.

I have written the below code to develop a calculated table:

```<code>ProductCategoryCostCT = SELECTCOLUMNS (

                                       SUMMARIZE(

                                                 Product,

                                                 Product[Category],

                                                 "TotalCostOfAllProductsInThisCategory", SUM(Product[ProductCost])

                                                ),

                                      "CategoryName", Product[Category],

                                      "Cost",  Product[TotalCostOfAllProductsInThisCategory]

                                     )
</code>```

The above code throws an error. Can someone help me correct this ? This may be pedestrian to many of you!

(The source Product table has ProductCost column at the individual Product level, with Category as another column
in the same table)

答:
```<code>ProductCategoryCostCT =  SUMMARIZE(

                                    SELECTCOLUMNS(

                                                   Product,

                                                   "CategoryName", Product[Category],
                                                   "ProductCost", Product[ProductCost]

                                                 ),

                                    [CategoryName],

                                    "Cost", SUM(Product[ProductCost])

                                  )
</code>```

Body:
I have a situation below (Power BI - DAX) in which I am trying to SUMMARIZE a table called Product with a SUM aggregation to get the total cost of all products in each Category; but then I have to change the column name of one or two columns in the summarized result set.

I have written the below code to develop a calculated table:

ProductCategoryCostCT = SELECTCOLUMNS (

                                       SUMMARIZE(

                                                 Product,

                                                 Product[Category],

                                                 "TotalCostOfAllProductsInThisCategory", SUM(Product[ProductCost])

                                                ),

                                      "CategoryName", Product[Category],

                                      "Cost",  Product[TotalCostOfAllProductsInThisCategory]

                                     )

The above code throws an error. Can someone help me correct this ? This may be pedestrian to many of you!

(The source Product table has ProductCost column at the individual Product level, with Category as another column
in the same table)


来源: stackexchange

问:
Resolve java.lang.StackOverflowError memory problem
I'm using a recursive function, and I'm getting this error when I execute :

```<code>Exception in thread "main" java.lang.StackOverflowError
    at java.util.HashMap$Entry.<init>(Unknown Source)
    at java.util.HashMap.addEntry(Unknown Source)
    at java.util.HashMap.put(Unknown Source)
</code>```

I debeugged the method and 100% sure it ends at some point.

So I think its related to a memory problem.

Is there any solution ?

EDIT:

```<code>public static Vector<String> _toOpen;

public static void openFiles(Vector<String> files)
{
   ...

    while(actualFile.hasNext)
    {
        if(!_toOpen.contains(word))
        {
           _toOpen.add(word);
            System.out.println("word");
        }
    }

   ...

   if(_toOpen.size() > 0)
   {
       openFiles(_toOpen);
   }
}
</code>```

At the first call I pass to OpenFiles a Vector wich contains a list of files to open, each file has a list of files to open again and so on ...

What I'm doing is preventing a file to be opened if it was dopne before.

答:
I think the problem is in your logic and the test for _toOpen.size() > 0.

After you perform _toOpen.add(word); then _toOpen.size() will always be greater than 0, and thus the if condition always true, and the function will always recurse.

You say "But the _toOpen.add(word); is not triggered always" - but it has to be triggered only once in the application life cycle to make this method recurse indefinitely.

Your Vector _toOpen is static which means there is only one of it, which means that as soon as _toOpen.add(word); is triggered, the statement _toOpen.size() > 0 always holds true.

ContentLicense: CC BY-SA 3.0

Body:
I'm using a recursive function, and I'm getting this error when I execute :

Exception in thread "main" java.lang.StackOverflowError
    at java.util.HashMap$Entry.<init>(Unknown Source)
    at java.util.HashMap.addEntry(Unknown Source)
    at java.util.HashMap.put(Unknown Source)

I debeugged the method and 100% sure it ends at some point.

So I think its related to a memory problem.

Is there any solution ?

EDIT:

public static Vector<String> _toOpen;

public static void openFiles(Vector<String> files)
{
   ...

    while(actualFile.hasNext)
    {
        if(!_toOpen.contains(word))
        {
           _toOpen.add(word);
            System.out.println("word");
        }
    }

   ...

   if(_toOpen.size() > 0)
   {
       openFiles(_toOpen);
   }
}

At the first call I pass to OpenFiles a Vector wich contains a list of files to open, each file has a list of files to open again and so on ...

What I'm doing is preventing a file to be opened if it was dopne before.


问:
How do you force Haskell's cabal-install program to ignore system libraries?
I'm trying to install the accelerate library from hackage, but it keeps giving me an error saying that my version of base package (4.15.1.0) is too new. Is there a way to force it to ignore the base package that's installed as a system-wide package, and instead download the correct version of the base package?

I'm using Manjaro Linux, ghc version 9.0.2, and cabal version 3.4.0.0. I can't seem to find any documentation on how to force it to ignore a system package. I've tried searching on https://cabal.readthedocs.io/en/3.6/ , but it doesn't seem to mention it anywhere.

答:
The base package is always hard-fixed to the compiler version. The only way to switch base is to switch to a different GHC. That's easier with Stack than it is with Cabal-install – just select a snapshot that has a suitable base version (lts-18.24 would do), and Stack will automatically install the corresponding compiler.

But it could well be that you can actually use base-4.15, and just accelerate has conservative dependency bounds. Try installing it with --allow-newer=base. If that works, give the maintainers a PR that the version bounds can be relaxed.

ContentLicense: CC BY-SA 4.0


问:
How do you convert an integer into a date (format YYYY) in R
I have a big data set, filled with dates that are in integer form, and different types of integer form (YYYYMMDD, YYYYMM and YYYY)

I just want to get all of them to YYYY.

I first tried splitting up the data frame into three data frames with the different respective date (integer) forms. And then I tried to change the data form from integer to date.

Below is me splitting up the data and then all the various things i have tried and subsequently commented out.

```<code>Opera_A <- Opera_split$Date_Format_A
Opera_B <- Opera_split$Date_Format_B
Opera_C <- Opera_split$Date_Format_C

lubridate::dmy(Opera_C$Composer_Born)
#as.Date(Opera_C$Composer_Born, "%m/%d/%y")
#Composer_Born_C <- data.frame(Composer_Born)
#Opera_C <- Opera_C %>% mutate(df,dateTime=as.Date(Composer_Born, format = "%Y-%m-%d"))
#Opera_C <- transform(Opera_C,Composer_Born=as.Date(as.character(Integer),"%Y%m%d"))
# Opera_C$Composer_Born <- as.Date(Opera_C$Composer_Born, '%Y-%m-%d')
</code>```

I keep getting Error in Opera_C$Composer_Born : $ operator is invalid for atomic vectors --- do i have to turn these vectors into dfs or can i just convert them directly?

Any help much appreciated --- I'm an R beginner!

Thank you

答:
```<code>> library(anytime)
> anydate(c(20220210, 202202, 2022))
[1] "2022-02-10" "2022-02-01" "2022-01-01"
>
</code>```

However, YYYYMM is not a really date: it is indeterminate as it could be any day of that month, ditto for YYYY.  So anydate guesses for you here.

Body:
I have a big data set, filled with dates that are in integer form, and different types of integer form (YYYYMMDD, YYYYMM and YYYY)

I just want to get all of them to YYYY.

I first tried splitting up the data frame into three data frames with the different respective date (integer) forms. And then I tried to change the data form from integer to date.

Below is me splitting up the data and then all the various things i have tried and subsequently commented out.

Opera_A <- Opera_split$Date_Format_A
Opera_B <- Opera_split$Date_Format_B
Opera_C <- Opera_split$Date_Format_C

lubridate::dmy(Opera_C$Composer_Born)
#as.Date(Opera_C$Composer_Born, "%m/%d/%y")
#Composer_Born_C <- data.frame(Composer_Born)
#Opera_C <- Opera_C %>% mutate(df,dateTime=as.Date(Composer_Born, format = "%Y-%m-%d"))
#Opera_C <- transform(Opera_C,Composer_Born=as.Date(as.character(Integer),"%Y%m%d"))
# Opera_C$Composer_Born <- as.Date(Opera_C$Composer_Born, '%Y-%m-%d')

I keep getting Error in Opera_C$Composer_Born : $ operator is invalid for atomic vectors --- do i have to turn these vectors into dfs or can i just convert them directly?

Any help much appreciated --- I'm an R beginner!

Thank you

Body:
> library(anytime)
> anydate(c(20220210, 202202, 2022))
[1] "2022-02-10" "2022-02-01" "2022-01-01"
>

However, YYYYMM is not a really date: it is indeterminate as it could be any day of that month, ditto for YYYY.  So anydate guesses for you here.


答:
plt.plot() function draws lines in the order you give in. In order to draw regression line you need to input your X values and predictions in the order of min to max of X. Simplest way to do that would be:

```<code>predictions = model1.predict(X)
order = X[:,0].argsort()
predictions = predictions[order]
x = X[:,0][order]

plt.plot(x,predictions)
plt.scatter(X[:,0],y,color = 'red')
plt.show()
</code>```

Title: Scikitlearn Linear Regression with 2 features

Body:
I am new to scikit learn and trying to fit a simple linear regression model. I have a matrix X which contains 2 columns, c1 and c1^2, and I have the corresponding y values. I tried to fit a simple OLS model using scikit learn but am getting strange plot in the end. Any ideas on what I am doing wrong?

X = np.array([[ -0.016746535778021,   0.280446460564527],
  [-0.014577470749242,   0.212502653445002],
   [0.034515758657299,   1.191337595688933],
  [-0.047010075743201,   2.209947221381472],
   [0.036975119046363,   1.367159428492700],
  [-0.040686110015367,   1.655359548182586],
  [-0.004472010975766,   0.019998882167376],
  [0.026533634894789 ,  0.704033780729957],
  [-0.042797683100180,   1.831641678743394],
   [0.025374099383528,   0.643844919525139],
  [-0.031109553977308,   0.967804348667025],
   [0.027311768635213,   0.745932705983427],
  [-0.003263862013657,   0.010652795244191],
  [-0.001818276487116,   0.003306129383598],
  [-0.040719662402516,   1.658090906174888],
  [-0.050013243645495,   2.501324539943689],
  [-0.017411771548016,   0.303169788440313],
   [0.003588193696644,   0.012875134004637],
   [0.007085480261971,   0.050204030542776,],
   [0.046282369018539,   2.142057681968212],
   [0.014612289091657,   0.213518992498145]])*1e3

y = np.array([4.1702,
    4.0673,
   31.8731,
   10.6237,
   31.8360,
    4.9594,
    4.4516,
   22.2763,
   -0.0000,
   20.5038,
    3.8583,
   19.3651,
    4.8838,
   11.0972,
    7.4617,
    1.4769,
    2.7192,
   10.9269,
    8.3487,
   52.7819,
   13.3573])

from sklearn.linear_model import LinearRegression as LR

model1 = LR().fit(X,y)

import matplotlib.pyplot as plt

plt.plot(X[:,0],model1.predict(X))
plt.scatter(X[:,0],y,color = 'red')
plt.show()

Body:
plt.plot() function draws lines in the order you give in. In order to draw regression line you need to input your X values and predictions in the order of min to max of X. Simplest way to do that would be:

predictions = model1.predict(X)
order = X[:,0].argsort()
predictions = predictions[order]
x = X[:,0][order]

plt.plot(x,predictions)
plt.scatter(X[:,0],y,color = 'red')
plt.show()


问:
calculate arithematic mean of rows above
I have a dataset that looks like this:

```<code>Value         Type       mean
-1.975767     Weather
-0.540979     Fruits
-2.359127     Fruits
-2.815604     Corona
-0.929755     Weather
</code>```

I want to iterate through each row and calculate a mean value for each row above (only if the Type matches). I want to put this value in the mean column. Mean is calculated by:

sum of all values / number of observations

Here, number of observations will be the number of times a Type has occurred so far.

For example, in the first row, there's no "weather" row above so for weather n = 1. So the mean would be -1.975767 / 1 = -1.975767.

In the second row, there's no FRUITS row above it, so the mean will just be -0.540979/1 = -0.540979.

However, in the third row, when we scan all previous rows, we see that FRUITS has already occurred before this and hence, n = 2 for Fruits. So we should get the last's FRUIT's value and calculate a new mean. So here, the mean will be -0.540979 + (-2.359127) divided by 2.

```<code>Value         Type       mean
-1.975767     Weather   -1.975767
-0.540979     Fruits    -0.540979
-2.359127     Fruits    (-0.540979 -2.359127)  / 2
-2.815604     Corona    -2.815604
-0.929755     Weather   (-1.975767 -0.929755) / 2
</code>```

What would be an efficient way to do this?

I see two possible sols:

We somehow store the value of N for each type and then just use the last calculated mean for a particular type, update the N by incrementing it with 1 and then calculate the new mean for a particular row.

If storing the N value is not convinient, then every time we scan for the occurrence of a type, we check its corresponding value and calculate the mean of all values again.

Body:
I have a dataset that looks like this:

Value         Type       mean
-1.975767     Weather
-0.540979     Fruits
-2.359127     Fruits
-2.815604     Corona
-0.929755     Weather

I want to iterate through each row and calculate a mean value for each row above (only if the Type matches). I want to put this value in the mean column. Mean is calculated by:

sum of all values / number of observations

Here, number of observations will be the number of times a Type has occurred so far.

For example, in the first row, there's no "weather" row above so for weather n = 1. So the mean would be -1.975767 / 1 = -1.975767.

In the second row, there's no FRUITS row above it, so the mean will just be -0.540979/1 = -0.540979.

However, in the third row, when we scan all previous rows, we see that FRUITS has already occurred before this and hence, n = 2 for Fruits. So we should get the last's FRUIT's value and calculate a new mean. So here, the mean will be -0.540979 + (-2.359127) divided by 2.

Value         Type       mean
-1.975767     Weather   -1.975767
-0.540979     Fruits    -0.540979
-2.359127     Fruits    (-0.540979 -2.359127)  / 2
-2.815604     Corona    -2.815604
-0.929755     Weather   (-1.975767 -0.929755) / 2

What would be an efficient way to do this?

I see two possible sols:

We somehow store the value of N for each type and then just use the last calculated mean for a particular type, update the N by incrementing it with 1 and then calculate the new mean for a particular row.

If storing the N value is not convinient, then every time we scan for the occurrence of a type, we check its corresponding value and calculate the mean of all values again.

Body:
Try using groupby + expanding + mean:

df['mean'] = df.groupby('Type')['Value'].expanding().mean().droplevel(0)

Output:

>>> df
      Value     Type      mean
0 -1.975767  Weather -1.975767
1 -0.540979   Fruits -0.540979
2 -2.359127   Fruits -1.450053
3 -2.815604   Corona -2.815604
4 -0.929755  Weather -1.452761


问:
Inner rounded shadows inside div
I have a div which looks something like this:

.box{
 box-sizing: border-box;
 border: solid 0.01rem #2e2e2e;
 border-radius: 3px;
 width:100px;
 height:100px;
 background:red;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"/></code>```

And I'm trying to achieve this effect. How can I make this box look with such shadows from the inside of the div?

答:
Well, I edited your code. Here is the demo.

Basically, I added one more div and added some style. Hope it will give you an idea.

Also, I added a snippet down below:-

.box {
  box-sizing: border-box;
  border: solid 0.01rem #2e2e2e;
  border-radius: 15px;
  width: 100px;
  height: 100px;
  background: red;
  padding: 10px 0px 10px 0px;
}

.inner-div {
  box-sizing: border-box;
  border-radius: 15px;
  width: 78px;
  height: 78px;
  background: #ee1717;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"/>
<div class="inner-div"></div>
<div></code>```

Title: Inner rounded shadows inside div

Body:
I have a div which looks something like this:

.box{
 box-sizing: border-box;
 border: solid 0.01rem #2e2e2e;
 border-radius: 3px;
 width:100px;
 height:100px;
 background:red;
 }

And I'm trying to achieve this effect. How can I make this box look with such shadows from the inside of the div?

Body:
Well, I edited your code. Here is the demo.

Basically, I added one more div and added some style. Hope it will give you an idea.

Also, I added a snippet down below:-

.box {
  box-sizing: border-box;
  border: solid 0.01rem #2e2e2e;
  border-radius: 15px;
  width: 100px;
  height: 100px;
  background: red;
  padding: 10px 0px 10px 0px;
}

.inner-div {
  box-sizing: border-box;
  border-radius: 15px;
  width: 78px;
  height: 78px;
  background: #ee1717;
  margin: 0 auto;
}

<div class="box"/>
<div class="inner-div"></div>
<div>


问:
getting DesignTimeDbContextFactory to run migrations without executing Startup
In my ASP.Net core application, Startup class has many things that is not needed to do migrations. According to This it seems I can create a DesignTimeFactory which will prepare the specified context and use it for migration purposes.

So I have created the simple class implementing IDesignTimeDbContextFactory which will simply accept a parameter, do some work with it and then return the MigrationContext for rest of the work within CreateDbContext(string[] args).

My problem is when I run Add-Migration commands from the console, it still executes StartUp class. . I thought with DesignTimeFactory, it shouldn't try to wire-up everything but simply use the context returned by the factory and use it for migration purposes.

Is there a way to avoid executing Startup class

```<code>       public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                Debugger.Launch();
                webBuilder.UseStartup<Startup>();
            });
</code>```

and simply rely only on the DBContextFactory for migration? So Startup class is only executing at run time

答:
Since the EF cli supports command line arguments, a hack-ish work around is to pass in an arg of some kind to the Add-Migration or Update-Database command and check for its existence in the CreateHostBuilder(string[] args) method:

```<code>public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
    {
        if (!args.Contains("design"))
            webBuilder.UseStartup<Startup>();
    });
</code>```

And then you could call the following command in PackageManagerConsole to skip the Startup file:

```<code>PM> Update-Database -Context MyContext -Args "design"
</code>```

Body:
In my ASP.Net core application, Startup class has many things that is not needed to do migrations. According to This it seems I can create a DesignTimeFactory which will prepare the specified context and use it for migration purposes.

So I have created the simple class implementing IDesignTimeDbContextFactory which will simply accept a parameter, do some work with it and then return the MigrationContext for rest of the work within CreateDbContext(string[] args).

My problem is when I run Add-Migration commands from the console, it still executes StartUp class. . I thought with DesignTimeFactory, it shouldn't try to wire-up everything but simply use the context returned by the factory and use it for migration purposes.

Is there a way to avoid executing Startup class

       public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                Debugger.Launch();
                webBuilder.UseStartup<Startup>();
            });

and simply rely only on the DBContextFactory for migration? So Startup class is only executing at run time

Body:
Since the EF cli supports command line arguments, a hack-ish work around is to pass in an arg of some kind to the Add-Migration or Update-Database command and check for its existence in the CreateHostBuilder(string[] args) method:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
    {
        if (!args.Contains("design"))
            webBuilder.UseStartup<Startup>();
    });

And then you could call the following command in PackageManagerConsole to skip the Startup file:

PM> Update-Database -Context MyContext -Args "design"


问:
How to get previous day's records in MongodDB?
I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day.
So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query.
So something like this

```<code>createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},
</code>```

But like I explained this is not what I want.

答:
You can get the UNIX timestamps for start and end of previous day this way.

NOTE - start and end in UTC time

var start = new Date().setUTCHours(0,0,0,0)-1000 * 60 * 60 * 24;
var end = new Date().setUTCHours(23,59,59,999)-1000 * 60 * 60 * 24;
console.log(start)
console.log(end)

console.log(new Date(start).toUTCString())
console.log(new Date(end).toUTCString())```

Body:
I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day.
So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query.
So something like this

createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},

But like I explained this is not what I want.


问:
Capacitor Plugin for Ionic App in Kotiln Unresolved reference: Plugin
I have created a capacitor plugin and an Ionic app locally for development in two separate directories. Both the plugin and the app on Android are using Kotlin.

I am using

Ionic Framework : @ionic/react 6.0.7
Capacitor CLI      : 3.4.1

@capacitor/android : 3.4.1

@capacitor/core    : 3.4.1

I built the plugin, then linked it with npm install ../capacitor/capacitor-my-plugin

In Android studio when I go to the main activity I can register the plugin

```<code>package io.ionic.starter

import com.getcapacitor.BridgeActivity
import android.os.Bundle
import com.example.plugin.MyPlugin

class MainActivity : BridgeActivity() {
  public override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    registerPlugin(MyPlugin::class.java)
  }
}
</code>```

I can click into the MyPlugin class and see that it is linked and all my code is there but when I run the application from the command line with ionic capacitor run android I get an error Unresolved reference: MyPlugin

I check and the capacitor.settings.gradle include my plugin

```<code>include ':capacitor-my-plugin'
project(':capacitor-my-plugin').projectDir = new File('../capacitor/capacitor-my-plugin/android')
</code>```

In my javascript I've added a button to call my plugin

```<code>import { MyPlugin } from 'capacitor-my-plugin'

<IonButton onClick={(e) => MyPlugin.open({value: {value:""}})}>
  Activate
</IonButton>
</code>```

If I remove the import and the registering in the main activity the app runs fine.

答: When I converted the plugin to kotlin, Android Studio did not automatically add apply plugin: 'kotlin-android' to the plugin's build.gradle file.

Body:
I have created a capacitor plugin and an Ionic app locally for development in two separate directories. Both the plugin and the app on Android are using Kotlin.

I am using

Ionic Framework : @ionic/react 6.0.7
Capacitor CLI      : 3.4.1

@capacitor/android : 3.4.1

@capacitor/core    : 3.4.1

I built the plugin, then linked it with npm install ../capacitor/capacitor-my-plugin

In Android studio when I go to the main activity I can register the plugin

package io.ionic.starter

import com.getcapacitor.BridgeActivity
import android.os.Bundle
import com.example.plugin.MyPlugin

class MainActivity : BridgeActivity() {
  public override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    registerPlugin(MyPlugin::class.java)
  }
}

I can click into the MyPlugin class and see that it is linked and all my code is there but when I run the application from the command line with ionic capacitor run android I get an error Unresolved reference: MyPlugin

I check and the capacitor.settings.gradle include my plugin

include ':capacitor-my-plugin'
project(':capacitor-my-plugin').projectDir = new File('../capacitor/capacitor-my-plugin/android')

In my javascript I've added a button to call my plugin

import { MyPlugin } from 'capacitor-my-plugin'

<IonButton onClick={(e) => MyPlugin.open({value: {value:""}})}>
  Activate
</IonButton>

If I remove the import and the registering in the main activity the app runs fine.


问:
how to caculate in GF(2^8) in Python?
```<code>x=Symbol('x')

M=Matrix([[1,x],[x^2,x^3]])

s=M.det()

f=lambdify(x,s)
</code>```

I need to know f(2)=? in GF(2^8),the caculate rules obey the GF(2^8)

答:
It's not exactly clear what you're asking to do, but here are some tools to assist. I created a Python package galois that extends NumPy arrays over Galois fields. All finite fields GF(p^m) are supported. Linear algebra and polynomials, among much more, are also supported.

Here is an example computing the matrix determinant and polynomial evaluation you alluded to.

In [1]: import numpy as np

In [2]: import galois

# Create a Galois field class
In [3]: GF = galois.GF(2**8)

# The irreducible polynomial is the one you specified in your comment
In [4]: print(GF.properties)
GF(2^8):
  characteristic: 2
  degree: 8
  order: 256
  irreducible_poly: x^8 + x^4 + x^3 + x^2 + 1
  is_primitive_poly: True
  primitive_element: x

# Create an array from its polynomials over GF(2) with degree < 8
In [5]: M = GF([[1, "x"], ["x^2", "x^3"]]); M
Out[5]:
GF([[1, 2],
    [4, 8]], order=2^8)

# Compute the determinant of the matrix
In [6]: np.linalg.det(M)
Out[6]: GF(0, order=2^8)

# Construct the polynomial x^2 + x as you mentioned in your comment
In [7]: f = galois.Poly([1, 1, 0], field=GF); f
Out[7]: Poly(x^2 + x, GF(2^8))

# Evaluate the polynomial at x = 2
In [8]: f(2)
Out[8]: GF(6, order=2^8)
```

Title: how to caculate in GF(2^8) in Python?

Body:
x=Symbol('x')

M=Matrix([[1,x],[x^2,x^3]])

s=M.det()

f=lambdify(x,s)

I need to know f(2)=? in GF(2^8),the caculate rules obey the GF(2^8)


问:
StringBuilder.Append Vs StringBuilder.AppendFormat
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);
</code>```

StringBuilder.AppendFormat:

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);
</code>```

答:
StringBuilder also has cascaded appends: Append() returns the StringBuilder itself, so you can write your code like this:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1)
  .Append("----")
  .Append(string2);
</code>```

Clean, and it generates less IL-code (although that's really a micro-optimization).

OwnerDisplayName: Sergio

ContentLicense: CC BY-SA 2.5

Body:
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);

StringBuilder.AppendFormat:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);

LastEditorDisplayName: Samuel

Body:
StringBuilder also has cascaded appends: Append() returns the StringBuilder itself, so you can write your code like this:

StringBuilder sb = new StringBuilder();
sb.Append(string1)
  .Append("----")
  .Append(string2);

Clean, and it generates less IL-code (although that's really a micro-optimization).

OwnerDisplayName: Tommy Carlier


问:
Vue radio button, just two of three are clickable
I have a quiz with three different answers (2 wrong and 1 correct). I can set the radio buttons properly, and I see the three answers, but just two of the three are clickable.

Are radio buttons thought just for two clickable elements? It seems strange to me. The

```<code><template>
<div class="quizForm" :key="componentKey">
        <div class="quizQuestContainer">
            <div v-for="(question, index) in quiz.questions"
                :key = index
            >
                <!-- Hide all questions, show only the one with index === to current question index -->
                <div class="quizQuestion" v-if="index === questionIndex">
                    <h2> Domanda {{ questionIndex+1 }}</h2>
                    <p class="question"> {{ question.text }} </p>
                    <ol>
                        <li v-for="(response, index) in question.responses"
                            :key = index
                        >
                        <label>
                            <input type="radio"
                                :value="[response.res_value === true]"
                                :name="response.res_number"
                                v-model="userResponse"
                            > {{response.res_text}}
                        </label>
                        </li>
                    </ol>
            <div class="quizQuestion" v-if="questionIndex === quiz.questions.length">
</template>

<script>
import sourceData from '@/data.json'

export default {
data(){
        return {
            componentKey: 0,
            questionIndex: 0,
            userResponse: null, //this is the present radio selection
            correctAnswers: [] //this is the array of selected answers
        }
    },

    computed:{
        quiz(){
            return sourceData.quizzes.find(quiz =>quiz.id === parseInt(this.id))
            },
        }
</script>
</code>```

In the data.json I have this structure:

```<code>"questions": [
            {
              "text": "Questoin?",
              "responses": [
                {"res_text": "Answer",
                  "res_number": 0,
                  "res_value": false
                },
                {"res_text": "Answer",
                  "res_number": 0,
                  "res_value": true
                },
                {"res_text": "Answer",
                  "res_number": 0,
                  "res_value": false
                }
              ]
            },
{
              "text": "Question?",
              "responses": [
                {"res_text": "Answer",
                  "res_number": 1,
                  "res_value": true
                },
                {"res_text": "Answer",
                  "res_number": 1,
                  "res_value": false
                },
                {"res_text": "Answer",
                  "res_number": 1,
                  "res_value": false
                }
              ]
          }
</code>```

etc.

答:
I found the problem: it was here

```<code>:value="[response.res_value === true]"
</code>```

I was binding everything to the true value.

Body:
I have a quiz with three different answers (2 wrong and 1 correct). I can set the radio buttons properly, and I see the three answers, but just two of the three are clickable.

Are radio buttons thought just for two clickable elements? It seems strange to me. The

<template>

 Domanda {{ questionIndex+1 }}

 {{ question.text }}

                            <input type="radio"
                                :value="[response.res_value === true]"
                                :name="response.res_number"
                                v-model="userResponse"
                            > {{response.res_text}}

</template>

In the data.json I have this structure:

"questions": [
            {
              "text": "Questoin?",
              "responses": [
                {"res_text": "Answer",
                  "res_number": 0,
                  "res_value": false
                },
                {"res_text": "Answer",
                  "res_number": 0,
                  "res_value": true
                },
                {"res_text": "Answer",
                  "res_number": 0,
                  "res_value": false
                }
              ]
            },
{
              "text": "Question?",
              "responses": [
                {"res_text": "Answer",
                  "res_number": 1,
                  "res_value": true
                },
                {"res_text": "Answer",
                  "res_number": 1,
                  "res_value": false
                },
                {"res_text": "Answer",
                  "res_number": 1,
                  "res_value": false
                }
              ]
          }

etc.

Body:
I found the problem: it was here

:value="[response.res_value === true]"

I was binding everything to the true value.


问:
Add tags to an existing S3 object using the ruby AWS SDK
AWS does let you add tags to an existing S3 bucket, using the console, or this http api for instance: https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectTagging.html

But rather than use the HTTP API directly, is there any way to use the ruby AWS SDK v3 to add (or remove?) tags to an existing S3 object?

I haven't been able to figure it out.

答:
OK, answering my question, I eventually found a method on Aws::S3::Client

https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Client.html#put_object_tagging-instance_method

s3_client = Aws::S3::Client.new
s3_client.put_object_tagging({
                bucket: "bucket_name",
                key: "some/key.jpg",
                tagging: {
                  tag_set: [
                    {
                      key: "tag-name",
                      value: "tag value",
                    }
                  ]
                }
})
```

i was expecting there to be a method on Aws::S3::Bucket or Aws::S3::Object, but if there is I can't figure it out! But I have verified this one on Aws::S3::Client as working for me.

Body:
OK, answering my question, I eventually found a method on Aws::S3::Client

https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Client.html#put_object_tagging-instance_method

s3_client = Aws::S3::Client.new
s3_client.put_object_tagging({
                bucket: "bucket_name",
                key: "some/key.jpg",
                tagging: {
                  tag_set: [
                    {
                      key: "tag-name",
                      value: "tag value",
                    }
                  ]
                }
})

i was expecting there to be a method on Aws::S3::Bucket or Aws::S3::Object, but if there is I can't figure it out! But I have verified this one on Aws::S3::Client as working for me.


问:
SQL Script for Employee/manager Mismatch
We have a Employee table, and I read the contents of it to build a treeview control for employee hierarchy.
The table structure is
1.FirstName
2.lastName
3.EmpNumber
4.Begindate
5.LastDateOfEmployement
6.ManagerId

Each employee reports to a managerId. When an Employee leaves the org the "lastdateofEmployement" is updated.
We have a script to populate the treeview control of all employees , who has LastDateOfemployement as NUll. That works fine.
However HR sometimes forgets to update the ManagerId of an employee, whose manager leaves the organization.
So when our script runs, the treeview fails to populate.

Can someone PLEASE help me write a script where , if an employee A leaves an organization, anyone reporting to him/her, should have their managerID updated to A's Managerid.

Emp A
Emp B
Emp C

C Reports to B , and B reports to A.
If B leaves the org (LastDateofEmployement is Not Null), the manager ID of C should be updated to A's Empnumber.

Please help!

答:
On the assumption that the data in your table is currently consistent (i.e. all employees report to a currently active employee), this should work:

/* TODO: replace with actual EmpNumber the departing manager */
declare @DepartingEmployee int = 123;

declare @NewManager int = (
   select ManagerID
   from dbo.Employee
   where EmpNumber = @DepartingEmployee
);

begin transaction;

   update dbo.Employee
   set ManagerID = @NewManager
   where ManagerID = @DepartingEmployee ;

   update dbo.Employee
   set LastDateOfEmployement = getdate()
   where EmpNumber = @DepartingEmployee;

commit transaction;
```
<p>Given your question though, it might be a pretty big assumption to make that the table is currently consistent! To find situations where employees report to an inactive employee, you'll have to do a one-time fix-up. This should identify the inconsistent data:</p>
<pre class="lang-sql prettyprint-override"><code>select e.EmpNumber, m.EmpNumber, m.ManagerID, m.LastDateOfEmployement
from dbo.Employee as e
join dbo.Employee as m
    on e.ManagerID = m.EmpNumber
where m.LastDateOfEmployement is not null;
</code>```

You can use the result set generated by that to drive updates. I leave that as an exercise for the reader.

Note - depending on how long you've gone without reparenting "orphaned" employees, you may have to go through the identify/update cycle multiple times. An example would be that if the org chart looked like A → B → C → D at some point (where "A → B" is read as "A reports to B") and both B and C have since left the org, the first pass would update A's manager to C (since C is B's manager) and a second pass would identify A as still reporting to a no longer active employee. Assuming that your tree is shallow, a multi pass approach is probably fine.

Body:
On the assumption that the data in your table is currently consistent (i.e. all employees report to a currently active employee), this should work:

/* TODO: replace with actual EmpNumber the departing manager */
declare @DepartingEmployee int = 123;

declare @NewManager int = (
   select ManagerID
   from dbo.Employee
   where EmpNumber = @DepartingEmployee
);

begin transaction;

   update dbo.Employee
   set ManagerID = @NewManager
   where ManagerID = @DepartingEmployee ;

   update dbo.Employee
   set LastDateOfEmployement = getdate()
   where EmpNumber = @DepartingEmployee;

commit transaction;

Given your question though, it might be a pretty big assumption to make that the table is currently consistent! To find situations where employees report to an inactive employee, you'll have to do a one-time fix-up. This should identify the inconsistent data:

select e.EmpNumber, m.EmpNumber, m.ManagerID, m.LastDateOfEmployement
from dbo.Employee as e
join dbo.Employee as m
    on e.ManagerID = m.EmpNumber
where m.LastDateOfEmployement is not null;

You can use the result set generated by that to drive updates. I leave that as an exercise for the reader.

Note - depending on how long you've gone without reparenting "orphaned" employees, you may have to go through the identify/update cycle multiple times. An example would be that if the org chart looked like A → B → C → D at some point (where "A → B" is read as "A reports to B") and both B and C have since left the org, the first pass would update A's manager to C (since C is B's manager) and a second pass would identify A as still reporting to a no longer active employee. Assuming that your tree is shallow, a multi pass approach is probably fine.


问:
defining the value for template in helm
I have created a new helm project and directory structure looks like this as follows:

```<code>my-app-helm
   /my-app-helm
      /charts
         /payment
            /templates
              _helpers.tpl
              secrets.yaml
              deployment.yaml
              ingress.yaml
              service.yaml
        Chart.yaml
        values.yaml
    Chart.yaml
</code>```

I refer to template in many placed like in ingress.yaml:

```<code>  - host: {{ .Values.payment.apphost }}
    http:
      paths:
      - path: /sft/v1/payment/
        backend:
          serviceName: {{ template "payment.fullname" . }}
          servicePort: 80
</code>```

I have a requirement that my service name, ingress name etc is prefixed with "ccg-helm", therefore I would like to ask how can I ensure value is "ccg-helm" where ever I reference "template":

for example:

serviceName: {{ template "payment.fullname" . }}

resolves to ccg-helm-payment

答:
You can modify the payment.fullname template in _helpers.tpl like so:

```<code>{{/*
Create a default fully qualified app name prefixed with "ccg-helm"
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "payment.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- printf "%s-%s" "ccg-helm" .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s-%s" "ccg-helm" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
</code>```

Title: defining the value for template in helm

Body:
I have created a new helm project and directory structure looks like this as follows:

my-app-helm
   /my-app-helm
      /charts
         /payment
            /templates
              _helpers.tpl
              secrets.yaml
              deployment.yaml
              ingress.yaml
              service.yaml
        Chart.yaml
        values.yaml
    Chart.yaml

I refer to template in many placed like in ingress.yaml:

  - host: {{ .Values.payment.apphost }}
    http:
      paths:
      - path: /sft/v1/payment/
        backend:
          serviceName: {{ template "payment.fullname" . }}
          servicePort: 80

I have a requirement that my service name, ingress name etc is prefixed with "ccg-helm", therefore I would like to ask how can I ensure value is "ccg-helm" where ever I reference "template":

for example:

serviceName: {{ template "payment.fullname" . }}

resolves to ccg-helm-payment

Body:
You can modify the payment.fullname template in _helpers.tpl like so:

{{/*
Create a default fully qualified app name prefixed with "ccg-helm"
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "payment.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- printf "%s-%s" "ccg-helm" .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s-%s" "ccg-helm" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}


问:
Run on server option not appearing in Eclipse
I'm learning SpringMVC framework and checked out a copy of their code:
https://src.springframework.org/svn/spring-samples/mvc-basic/trunk/
I can do maven build, install and everything. But on Eclipse, run on server option never appeared. I have tomcat server up and running, also got plugin for eclipse. Why run on server option is missing? This is a Ubuntu machine.
When I tried the exact same thing on my Windows machine, everything was fine. It has the same version of eclipse and all sorts of plugins installed as the Ubuntu machine. I was able to launch it from Eclipse "run on server" option there.

Can someone help me to figure out why? Thanks.

答: Right click on the project, go to "Run as", select "Run configurations" and create a run configuration.</p>


问:
T-SQL split response header from SP
Within a T-SQL script I am calling a stored procedure, this stored procedure handles HTTP requests and is returning stuff like HTTP status code, status text and response headers.

The stored procedure is an 3rd party managed/created SP which I cannot edit (because when the vendor is updating their application the SP will be overwritten). So I have to deal with the output of the SP.

The response header which I am receiving after the HTTP call is made is a full string of all the headers (seperated by two spaces '  ').

This is the response header:

```<code>Cache-Control: no-cache,no-store,max-age=0  Connection: keep-alive  Date: Thu, 10 Feb 2022 07:46:23 GMT  Transfer-Encoding: chunked  Via: 1.1 <snip>.cloudfront.net (CloudFront)  Content-Type: application/json  Notification-Box-Id: 627ac06d-snip-snip-snip-7ae2cda3f8ae  Notification-Message-Id: c6ef44cd-snip-snip-snip-be196a48751b  X-Envoy-Upstream-Service-Time: 105  Strict-Transport-Security: max-age=31536000;  Content-Security-Policy: default-src 'self'  Strict-Transport-Security: max-age=31536000; includeSubDomains; preload  X-Cache: Miss from cloudfront  X-Amz-Cf-Pop: FRA6-C1  X-Amz-Cf-Id: 61b-snip-snipsnipsnip-vpg==
</code>```

I need to have the value of two response headers (Notification-Box-Id & Notification-Message-Id) from this string. I've tried to use STRING_SPLIT but it does not accept two spaces (because of nchar(1)).

My assumption is that the format is always the same, so with LEFT(), RIGHT() and LEN() I can probably manage it to work. But is this the way to go? Is there any other option which is less messy?

答:
This is quite easy. Grab a copy of delimitedSplit8k. It returns the item and it's ordinal position in the string. And it's fast.

```<code>DECLARE @x VARCHAR(1000) = 'Cache-Control: no-cache,no-store,max-age=0  Connection: keep-alive  Date: Thu, 10 Feb 2022 07:46:23 GMT  Transfer-Encoding: chunked  Via: 1.1 <snip>.cloudfront.net (CloudFront)  Content-Type: application/json  Notification-Box-Id: 627ac06d-snip-snip-snip-7ae2cda3f8ae  Notification-Message-Id: c6ef44cd-snip-snip-snip-be196a48751b  X-Envoy-Upstream-Service-Time: 105  Strict-Transport-Security: max-age=31536000;  Content-Security-Policy: default-src ''self''  Strict-Transport-Security: max-age=31536000; includeSubDomains; preload  X-Cache: Miss from cloudfront  X-Amz-Cf-Pop: FRA6-C1  X-Amz-Cf-Id: 61b-snip-snipsnipsnip-vpg==    ';

SELECT split.*
FROM
(
  SELECT split.Item, Val = LEAD(split.Item,1) OVER (ORDER BY split.ItemNumber)
  FROM DW.dbo.DelimitedSplit8K(@x, '') AS split
) AS split(Item,ItemValue)
WHERE split.Item LIKE '%Notification-Box-Id%'
 OR   split.Item LIKE '%Notification-Message-Id%';
</code>```

Returns:

```<code>Item                      ItemValue
------------------------- -----------------------------------------
Notification-Box-Id:      627ac06d-snip-snip-snip-7ae2cda3f8ae
Notification-Message-Id:  c6ef44cd-snip-snip-snip-be196a48751b
</code>```

Title: T-SQL split response header from SP

Body:
Within a T-SQL script I am calling a stored procedure, this stored procedure handles HTTP requests and is returning stuff like HTTP status code, status text and response headers.

The stored procedure is an 3rd party managed/created SP which I cannot edit (because when the vendor is updating their application the SP will be overwritten). So I have to deal with the output of the SP.

The response header which I am receiving after the HTTP call is made is a full string of all the headers (seperated by two spaces '  ').

This is the response header:

Cache-Control: no-cache,no-store,max-age=0  Connection: keep-alive  Date: Thu, 10 Feb 2022 07:46:23 GMT  Transfer-Encoding: chunked  Via: 1.1 <snip>.cloudfront.net (CloudFront)  Content-Type: application/json  Notification-Box-Id: 627ac06d-snip-snip-snip-7ae2cda3f8ae  Notification-Message-Id: c6ef44cd-snip-snip-snip-be196a48751b  X-Envoy-Upstream-Service-Time: 105  Strict-Transport-Security: max-age=31536000;  Content-Security-Policy: default-src 'self'  Strict-Transport-Security: max-age=31536000; includeSubDomains; preload  X-Cache: Miss from cloudfront  X-Amz-Cf-Pop: FRA6-C1  X-Amz-Cf-Id: 61b-snip-snipsnipsnip-vpg==

I need to have the value of two response headers (Notification-Box-Id & Notification-Message-Id) from this string. I've tried to use STRING_SPLIT but it does not accept two spaces (because of nchar(1)).

My assumption is that the format is always the same, so with LEFT(), RIGHT() and LEN() I can probably manage it to work. But is this the way to go? Is there any other option which is less messy?

Body:
This is quite easy. Grab a copy of delimitedSplit8k. It returns the item and it's ordinal position in the string. And it's fast.

DECLARE @x VARCHAR(1000) = 'Cache-Control: no-cache,no-store,max-age=0  Connection: keep-alive  Date: Thu, 10 Feb 2022 07:46:23 GMT  Transfer-Encoding: chunked  Via: 1.1 <snip>.cloudfront.net (CloudFront)  Content-Type: application/json  Notification-Box-Id: 627ac06d-snip-snip-snip-7ae2cda3f8ae  Notification-Message-Id: c6ef44cd-snip-snip-snip-be196a48751b  X-Envoy-Upstream-Service-Time: 105  Strict-Transport-Security: max-age=31536000;  Content-Security-Policy: default-src ''self''  Strict-Transport-Security: max-age=31536000; includeSubDomains; preload  X-Cache: Miss from cloudfront  X-Amz-Cf-Pop: FRA6-C1  X-Amz-Cf-Id: 61b-snip-snipsnipsnip-vpg==    ';

SELECT split.*
FROM
(
  SELECT split.Item, Val = LEAD(split.Item,1) OVER (ORDER BY split.ItemNumber)
  FROM DW.dbo.DelimitedSplit8K(@x, '') AS split
) AS split(Item,ItemValue)
WHERE split.Item LIKE '%Notification-Box-Id%'
 OR   split.Item LIKE '%Notification-Message-Id%';

Returns:

Item                      ItemValue
------------------------- -----------------------------------------
Notification-Box-Id:      627ac06d-snip-snip-snip-7ae2cda3f8ae
Notification-Message-Id:  c6ef44cd-snip-snip-snip-be196a48751b


问:
Unrecognized field during deserialization despite @SerializedName annotation
I am fetching some data via a REST service, but I am getting this error when deserializing the response :

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ResultSet Output" (class com.HolderCollectionWrapper), not marked as ignorable (one known property: "holders"]) at [Source: java.io.ByteArrayInputStream@74efa7bd; line: 1, column: 22] (through reference chain: com.HolderCollectionWrapper["ResultSet Output"])

This is my code :

```<code>response = restTemplate.exchange(requestUrl, HttpMethod.GET, request, HolderCollectionWrapper.class);

public class HolderCollectionWrapper {

    @SerializedName("ResultSet Output")
    private List<Holder> holders;

    public List<Holder> getHolders() {
        return holders;
    }

    public void setHolders(List<Holder> holders) {
        this.holders = holders;
    }
}
</code>```

This is the JSON I am getting :

```<code>{
    "ResultSet Output": [
        {...}, {...}, {...}
    ]
}
</code>```

Despite the @SerializedName("ResultSet Output"), it's not working, why ?

答:
This happens because the SerializedName("ResultSet Output") gson annotation indicates that the holders will be serialized with the ResultSet Output name like the json example you post; to deserialize it with jackson you have to use the JsonProperty annotation, specifying the ResultSet Output name applied on the setter to avoid possible conflicts with the gson library used for serialization:

```<code>public class HolderCollectionWrapper {

    @SerializedName("ResultSet Output")
    private List<Holder> holders;

    public List<Holder> getHolders() {
        return holders;
    }

    @JsonProperty("ResultSet Output")
    public void setHolders(List<Holder> holders) {
        this.holders = holders;
    }
}
</code>```

Body:
I am fetching some data via a REST service, but I am getting this error when deserializing the response :

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "ResultSet Output" (class com.HolderCollectionWrapper), not marked as ignorable (one known property: "holders"]) at [Source: java.io.ByteArrayInputStream@74efa7bd; line: 1, column: 22] (through reference chain: com.HolderCollectionWrapper["ResultSet Output"])

This is my code :

response = restTemplate.exchange(requestUrl, HttpMethod.GET, request, HolderCollectionWrapper.class);

public class HolderCollectionWrapper {

    @SerializedName("ResultSet Output")
    private List<Holder> holders;

    public List<Holder> getHolders() {
        return holders;
    }

    public void setHolders(List<Holder> holders) {
        this.holders = holders;
    }
}

This is the JSON I am getting :

{
    "ResultSet Output": [
        {...}, {...}, {...}
    ]
}

Despite the @SerializedName("ResultSet Output"), it's not working, why ?

Body:
This happens because the SerializedName("ResultSet Output") gson annotation indicates that the holders will be serialized with the ResultSet Output name like the json example you post; to deserialize it with jackson you have to use the JsonProperty annotation, specifying the ResultSet Output name applied on the setter to avoid possible conflicts with the gson library used for serialization:

public class HolderCollectionWrapper {

    @SerializedName("ResultSet Output")
    private List<Holder> holders;

    public List<Holder> getHolders() {
        return holders;
    }

    @JsonProperty("ResultSet Output")
    public void setHolders(List<Holder> holders) {
        this.holders = holders;
    }
}


问:
Scroll page to the nested React component on a button click
I've got a React Component with several nested components. For page navigation I have a few buttons on the top.
The question is, how to scroll the page to the nested react component when a certain button is clicked, is it possible to do so without using jquery libs?</p>

```<code>  render() {
    return (
      <div>
        <button onClick={(e) => { console.log('Scrolling to Item 1');}}>Button0</button>
        <button onClick={(e) => { console.log('Scrolling to Item 2');}}>Button1</button>
          <Layout>
            <Item>
              <Content>
            ...
              </Content>
            </Item>

            <Item>
              <Content>
            ...
              </Content>
            </Item>

          </Layout>
        }
      </div>
    );
  }
</code>```

答:
Using React hooks and no 3rd party packages:

Create a reference using the React hook useRef

import { useRef } from 'react'
const firstItemRef = useRef(null);
```
<ol start="2">
<li>Assign the reference to the component you want to scroll to</li>
</ol>
<pre class="lang-js prettyprint-override"><code><Item ref={firstItemRef}>
</code>```

Use the scrollIntoView method to scroll to the specific Element/Component

<button onClick={() => firstItemRef.current.scrollIntoView()}

```

Body:
I've got a React Component with several nested components. For page navigation I have a few buttons on the top.
The question is, how to scroll the page to the nested react component when a certain button is clicked, is it possible to do so without using jquery libs?

  render() {
    return (

        <button onClick={(e) => { console.log('Scrolling to Item 1');}}>Button0</button>
        <button onClick={(e) => { console.log('Scrolling to Item 2');}}>Button1</button>
          <Layout>
            <Item>
              <Content>
            ...
              </Content>
            </Item>

            <Item>
              <Content>
            ...
              </Content>
            </Item>

          </Layout>
        }

    );
  }

Body:
Using React hooks and no 3rd party packages:

Create a reference using the React hook useRef

import { useRef } from 'react'
const firstItemRef = useRef(null);

Assign the reference to the component you want to scroll to

<Item ref={firstItemRef}>

Use the scrollIntoView method to scroll to the specific Element/Component

<button onClick={() => firstItemRef.current.scrollIntoView()}


问:
Remove all posible spaces in JSON message with Mule 4 dataweave
I have a JSON message where I need to remove all format spaces keeping values untouched. This is required before running a hash function over the full payload so it needs to be precise.

I started with the indent=false in the Dataweave writer configuration but I got a space after each colon like this:

```<code>{"text": "number\": 1 | array\": [ | number\": 1","number": 1,"array": [1,"as",[],{}]}
</code>```

Any suggested elegant solution to remove the spaces left before entering in the RegEx world? If not, any RegEx solution?

答:
I tried to remove all space from a json using below dw scripts.
The below one will give json in a stream with no indent, but there will be
space after each colon.

```<code>%dw 2.0
output application/json indent=false
---
{
    name: "somename",
    city: "sg",
    profession: "tenchdigger"
}

</code>```

The output of above script is converted to string and all spaces are removed using below script

```<code>%dw 2.0
var someSpaceJson = write(payload, "application/json", {"indent":false})
output application/java
---
someSpaceJson replace " " with ""
</code>```

The end result is a json string with no space

```<code>"{"name":"somename","city":"sg","profession":"tenchdigger"}"
</code>```

Body:
I have a JSON message where I need to remove all format spaces keeping values untouched. This is required before running a hash function over the full payload so it needs to be precise.

I started with the indent=false in the Dataweave writer configuration but I got a space after each colon like this:

{"text": "number\": 1 | array\": [ | number\": 1","number": 1,"array": [1,"as",[],{}]}

Any suggested elegant solution to remove the spaces left before entering in the RegEx world? If not, any RegEx solution?

Body:
I tried to remove all space from a json using below dw scripts.
The below one will give json in a stream with no indent, but there will be
space after each colon.

%dw 2.0
output application/json indent=false
---
{
    name: "somename",
    city: "sg",
    profession: "tenchdigger"
}

The output of above script is converted to string and all spaces are removed using below script

%dw 2.0
var someSpaceJson = write(payload, "application/json", {"indent":false})
output application/java
---
someSpaceJson replace " " with ""

The end result is a json string with no space

"{"name":"somename","city":"sg","profession":"tenchdigger"}"


问:
Readthedocs / Sphinx not rendering bullet list from rst file
I have a set of rst files that I am building in readthedocs with sphinx. The files have multiple bullet lists, but they are not being rendered correctly.

The text appears, but there are no bullet symbols or nesting / indentation.

To make sure it was not my files, I did a direct copy-paste from the sphinx_rtd_theme page (https://github.com/readthedocs/sphinx_rtd_theme/blob/b07560bf97dad3a4266f6145bd4b662ac708ab00/docs/demo/lists_tables.rst)

This is what the rst is supposed to render as (with ::marker for each list item in the html file)

This is what I am getting when I build the same rst using my local sphinx / rtd setup

Is there something I need to fix in my conf.py or other files?

答:
Other answers here point to docutils as the having the bug. But, the bug is actually in sphinx-rtd-theme. So, even though downgrading docutils seems to work, the solution that worked for us, that I think is better, is to
upgrade sphinx and sphinx-rtd-theme past the bugfix. For us, that looked like requiring sphinx>=4.3.0 and sphinx-rtd-theme>=0.5.1 (see our PR)


问:
Resolve "Property does not exist on type 'Vue'" error
I am using Typescript with Vuejs to build an application.  I have several stand alone components (.vue) files that I am importing into a Typescript (.ts) file.  In the Typescript file, I am importing Vue from the npm Vue library and then creating a new Vue to display my components.  The error that I am seeing is:

Property x does not exist on type 'Vue'

My build system is Webpack with tsc.  Why am I getting this error and how can I resolve it?

main.ts

```<code>import Vue from 'vue';
import Competency from '../components/competency.vue';

new Vue({
  el: "#app",
  components: {
    'competency': Competency
  },
  data:{
    count: 0
  },
  methods:{
    initialize: function(){
      this.count = count + 1; // Errors here with Property count does not exist on type vue
    }
  }
})
</code>```

tsconfig

```<code>{
  "compilerOptions": {
    // "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom",
      "es2015.promise"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    //"outDir": "./build/",
    "removeComments": false,
    "sourceMap": true,
    "target": "es5"

  },
  "exclude": [
    "./node_modules",
    "wwwroot",
    "./Model"
  ],
  "include": [
    "./CCSEQ",
    "./WebResources"
  ]
}
</code>```

webpack.config.js

```<code>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    entry: {
        Evaluations: './WebResources/js/main.ts'
    },
    devServer: {
        contentBase: './dist'
    },
    module: {
        rules: [{
                test: /\.ts$/,
                exclude: /node_modules|vue\/src/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: {
                    appendTsSuffixTo: [/\.vue$/]
                }
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    esModule: true
                }
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    'file-loader'
                ]
            },
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"],
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            filename: 'Evaluations.html',
            template: './WebResources/html/Evaluations.html'
        }), new HtmlWebpackPlugin({
            filename: 'ExpenseUpload.html',
            template: './WebResources/html/ExpenseUpload.html'
        }), new webpack.optimize.CommonsChunkPlugin({
            name: 'WebAPI'
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}
</code>```

答:
Have the same issue.
solution is to add a return type on each computed variable.

Issue from this code, without return type.

```<code>      computed: {
containerClass() {
    return this.isLastChild
  }
</code>```

add return type String.

```<code>  computed: {
containerClass(): String {
    return this.isLastChild
  }
</code>```

Body:
I am using Typescript with Vuejs to build an application.  I have several stand alone components (.vue) files that I am importing into a Typescript (.ts) file.  In the Typescript file, I am importing Vue from the npm Vue library and then creating a new Vue to display my components.  The error that I am seeing is:

Property x does not exist on type 'Vue'

My build system is Webpack with tsc.  Why am I getting this error and how can I resolve it?

main.ts

import Vue from 'vue';
import Competency from '../components/competency.vue';

new Vue({
  el: "#app",
  components: {
    'competency': Competency
  },
  data:{
    count: 0
  },
  methods:{
    initialize: function(){
      this.count = count + 1; // Errors here with Property count does not exist on type vue
    }
  }
})

tsconfig

{
  "compilerOptions": {
    // "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom",
      "es2015.promise"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    //"outDir": "./build/",
    "removeComments": false,
    "sourceMap": true,
    "target": "es5"

  },
  "exclude": [
    "./node_modules",
    "wwwroot",
    "./Model"
  ],
  "include": [
    "./CCSEQ",
    "./WebResources"
  ]
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    entry: {
        Evaluations: './WebResources/js/main.ts'
    },
    devServer: {
        contentBase: './dist'
    },
    module: {
        rules: [{
                test: /\.ts$/,
                exclude: /node_modules|vue\/src/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: {
                    appendTsSuffixTo: [/\.vue$/]
                }
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                options: {
                    esModule: true
                }
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    'file-loader'
                ]
            },
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"],
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            filename: 'Evaluations.html',
            template: './WebResources/html/Evaluations.html'
        }), new HtmlWebpackPlugin({
            filename: 'ExpenseUpload.html',
            template: './WebResources/html/ExpenseUpload.html'
        }), new webpack.optimize.CommonsChunkPlugin({
            name: 'WebAPI'
        })
    ],
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}

Body:
Have the same issue.
solution is to add a return type on each computed variable.

Issue from this code, without return type.

      computed: {
containerClass() {
    return this.isLastChild
  }

add return type String.

  computed: {
containerClass(): String {
    return this.isLastChild
  }


问:
Is it safer to use OpenCL rather than SYCL when the objective is to have the most hardware-compatible program?
My objective is to obtain the ability of parallelizing a code in order to be able to run it on GPU, and the Graal would be to have a software that can run in parallel on any GPU or even CPU (Intel, NVIDIA, AMD, and so...).

From what I understood, the best solution would be to use OpenCL. But shortly after that, I also read about SYCL, that is supposed to simplify the codes that run on GPU.

But is it just that ? Isn't better to use a lower level language in order to be sure that it will be possible to be used in the most hardware possible ?

I know that all the compatibilities are listed on The Khronos Group website, but I am reading everything and its opposite on the Internet (like if a NVIDIA card supports CUDA, then it supports OpenCL, or NVIDIA cards will never work with OpenCL, even though OpenCL is supposed to work with everything)...

This is a new topic to me and there are lots of informations on the Internet... It would be great if someone could give me a simple answer to this question.

答:
Probably yes.

OpenCL is supported on all AMD/Nvidia/Intel GPUs and on all Intel CPUs since around 2009. For best compatibility with almost any device, use OpenCL 1.2. The nice thing is that the OpenCL Runtime is included in the graphics drivers, so you don't have to install anything extra to work with it or to get it working on another machine.

SYCL on the other hand is newer and not yet established that well. For example, it is not officially supported (yet) on Nvidia GPUs: https://forums.developer.nvidia.com/t/is-sycl-available-on-cuda/37717/7
But there are already SYCL implememtations that are compatible with Nvidia/AMD GPUs, essentially built on top of CUDA or OpenCL 1.2, see here: https://stackoverflow.com/a/63468372/9178992


问:
HOW TO USE CASE WHEN STATEMENT IN R
INPUT:-

```<code>ID   NAME    DATE     ATTENDENCE
1   murali  2021-08-20  present
1   murali  2021-08-21  absent
1   murali  2021-08-22  present
1   murali  2021-08-23  absent
1   murali  2021-08-24  present
1   murali  2021-08-25  absent
1   murali  2021-08-26  present
1   murali  2021-08-27  absent
1   murali  2021-08-28  absent
1   murali  2021-08-29  absent
1   murali  2021-08-30  absent
2   krishna 2021-08-20  absent
2   krishna 2021-08-21  absent
2   krishna 2021-08-22  absent
2   krishna 2021-08-23  absent
2   krishna 2021-08-24  absent
2   krishna 2021-08-25  absent
2   krishna 2021-08-26  present
2   krishna 2021-08-27  absent
2   krishna 2021-08-28  present
2   krishna 2021-08-29  present
2   krishna 2021-08-30  absent
</code>```

OUTPUT:-

ID NAME DATE ATTENDENCE PRESENT absent

1 murali 2021-08-20 present 1 0

1 murali 2021-08-21 absent 0 1

1 murali 2021-08-22 present 1 0

1 murali 2021-08-23 absent 0 1

1 murali 2021-08-24 present 1 0

1 murali 2021-08-25 absent 0 1

1 murali 2021-08-26 present 1 0

1 murali 2021-08-27 absent 0 1

1 murali 2021-08-28 absent 0 1

1 murali 2021-08-29 absent 0 1

1 murali 2021-08-30 absent 0 1

2 krishna 2021-08-20 absent 0 1

2 krishna 2021-08-21 absent 0 1

2 krishna 2021-08-22 absent 0 1

2 krishna 2021-08-23 absent 0 1

2 krishna 2021-08-24 absent 0 1

2 krishna 2021-08-25 absent 0 1

2 krishna 2021-08-26 present 1 0

2 krishna 2021-08-27 absent 0 1

2 krishna 2021-08-28 present 1 0

2 krishna 2021-08-29 present 1 1

2 krishna 2021-08-30 absent 0 0

答:
not case_when but it is a tidyverse alternative

```<code>library(dplyr)

df %>%
  group_by(NAME) %>%
  count(ATTENDENCE) %>%
  ungroup() %>%
  pivot_wider(names_from = ATTENDENCE,
              values_from = n)
</code>```

Title: HOW TO USE CASE WHEN STATEMENT IN R

Body:
INPUT:-

ID   NAME    DATE     ATTENDENCE
1   murali  2021-08-20  present
1   murali  2021-08-21  absent
1   murali  2021-08-22  present
1   murali  2021-08-23  absent
1   murali  2021-08-24  present
1   murali  2021-08-25  absent
1   murali  2021-08-26  present
1   murali  2021-08-27  absent
1   murali  2021-08-28  absent
1   murali  2021-08-29  absent
1   murali  2021-08-30  absent
2   krishna 2021-08-20  absent
2   krishna 2021-08-21  absent
2   krishna 2021-08-22  absent
2   krishna 2021-08-23  absent
2   krishna 2021-08-24  absent
2   krishna 2021-08-25  absent
2   krishna 2021-08-26  present
2   krishna 2021-08-27  absent
2   krishna 2021-08-28  present
2   krishna 2021-08-29  present
2   krishna 2021-08-30  absent

OUTPUT:-

ID NAME DATE ATTENDENCE PRESENT absent

1 murali 2021-08-20 present 1 0

1 murali 2021-08-21 absent 0 1

1 murali 2021-08-22 present 1 0

1 murali 2021-08-23 absent 0 1

1 murali 2021-08-24 present 1 0

1 murali 2021-08-25 absent 0 1

1 murali 2021-08-26 present 1 0

1 murali 2021-08-27 absent 0 1

1 murali 2021-08-28 absent 0 1

1 murali 2021-08-29 absent 0 1

1 murali 2021-08-30 absent 0 1

2 krishna 2021-08-20 absent 0 1

2 krishna 2021-08-21 absent 0 1

2 krishna 2021-08-22 absent 0 1

2 krishna 2021-08-23 absent 0 1

2 krishna 2021-08-24 absent 0 1

2 krishna 2021-08-25 absent 0 1

2 krishna 2021-08-26 present 1 0

2 krishna 2021-08-27 absent 0 1

2 krishna 2021-08-28 present 1 0

2 krishna 2021-08-29 present 1 1

2 krishna 2021-08-30 absent 0 0

Body:
not case_when but it is a tidyverse alternative

library(dplyr)

df %>%
  group_by(NAME) %>%
  count(ATTENDENCE) %>%
  ungroup() %>%
  pivot_wider(names_from = ATTENDENCE,
              values_from = n)


问:
ASP.NET Core IHostedService + IIS autostart feature doesn't work
I have a .NET 6 IHostedService hosted on IIS 10 Windows Server 2019.

I am aiming for

startup the application after server reboot

startup the application after iisreset

startup the application after iisreset /start

I followed the SO post here and this blog post

Regarding SO post's answer:

I did a reboot of server

followed all steps

Regarding the blog post:

I tried setting the CLR to both "No Managed Code" and "v4.0"

I have found some mention on other sites that I have to have anonymous auth enabled - this was also tested (see below in applicationhost.config)

However I can't have this basic feature of IIS up and running. According to SO post and blog post, it seems that it helped most of the people.

web.config:

```<code><?xml version="1.0" encoding="utf-8"?>
   <configuration>
       <location path="." inheritInChildApplications="false">
           <system.webServer>
               <handlers>
                   <remove name="aspNetCore" />
                   <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
               </handlers>
               <aspNetCore processPath="dotnet" arguments=".\<obfuscated>.dll"
                           stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout"
                           hostingModel="inprocess">
                   <environmentVariables>
                       <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
                   </environmentVariables>
               </aspNetCore>
            </system.webServer>
        </location>
    </configuration>
</code>```

applicationhost.config:

```<code><?xml version="1.0" encoding="UTF-8"?>
< ... />
<configuration>
    <system.applicationHost>
        <applicationPools>
            <add name="obfuscated" autoStart="true" managedRuntimeVersion="v4.0" startMode="AlwaysRunning">
                <processModel identityType="SpecificUser" userName="obfuscated" password="obfuscated" idleTimeout="00:00:00" />
            </add>
            <applicationPoolDefaults managedRuntimeVersion="v4.0">
                <processModel identityType="ApplicationPoolIdentity" />
                <recycling logEventOnRecycle="Time, Requests, Schedule, Memory, IsapiUnhealthy, OnDemand, ConfigChange, PrivateMemory">
                    <periodicRestart time="00:00:00" />
                </recycling>
            </applicationPoolDefaults>
        </applicationPools>

        < ... />

        <sites>
            <site name="obfuscated" id="1">
                <application path="/" applicationPool="obfuscated" preloadEnabled="true">
                    <virtualDirectory path="/" physicalPath="obfuscated" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="obfuscated" />
                </bindings>
            </site>
            <siteDefaults>
                <logFile logExtFileFlags="Date, Time, ClientIP, UserName, SiteName, ComputerName, ServerIP, Method, UriStem, UriQuery, HttpStatus, Win32Status, TimeTaken, ServerPort, UserAgent, Referer, Host, HttpSubStatus" logFormat="W3C" directory="obfuscated">
                </logFile>
                <traceFailedRequestsLogging directory="obfuscated" />
            </siteDefaults>
            <applicationDefaults applicationPool="DefaultAppPool" />
            <virtualDirectoryDefaults allowSubDirConfig="true" />
        </sites>

        <webLimits />
    </system.applicationHost>

    <system.webServer>

        <asp />

        <caching enabled="true" enableKernelCache="true">
        </caching>

        <cgi />

        <defaultDocument enabled="true">
            <files>
                <add value="Default.htm" />
                <add value="Default.asp" />
                <add value="index.htm" />
                <add value="index.html" />
                <add value="iisstart.htm" />
                <add value="default.aspx" />
            </files>
        </defaultDocument>

        <directoryBrowse enabled="false" />

        <fastCgi />
        <!--
          The <globalModules> section defines all native-code modules.
          To enable a module, specify it in the <modules> section.
        -->
        <globalModules>
            <add name="HttpLoggingModule" image="%windir%\System32\inetsrv\loghttp.dll" />
            <add name="UriCacheModule" image="%windir%\System32\inetsrv\cachuri.dll" />
            <add name="FileCacheModule" image="%windir%\System32\inetsrv\cachfile.dll" />
            <add name="TokenCacheModule" image="%windir%\System32\inetsrv\cachtokn.dll" />
            <add name="HttpCacheModule" image="%windir%\System32\inetsrv\cachhttp.dll" />
            <add name="DynamicCompressionModule" image="%windir%\System32\inetsrv\compdyn.dll" />
            <add name="StaticCompressionModule" image="%windir%\System32\inetsrv\compstat.dll" />
            <add name="DefaultDocumentModule" image="%windir%\System32\inetsrv\defdoc.dll" />
            <add name="DirectoryListingModule" image="%windir%\System32\inetsrv\dirlist.dll" />
            <add name="ProtocolSupportModule" image="%windir%\System32\inetsrv\protsup.dll" />
            <add name="HttpRedirectionModule" image="%windir%\System32\inetsrv\redirect.dll" />
            <add name="StaticFileModule" image="%windir%\System32\inetsrv\static.dll" />
            <add name="AnonymousAuthenticationModule" image="%windir%\System32\inetsrv\authanon.dll" />
            <add name="UrlAuthorizationModule" image="%windir%\System32\inetsrv\urlauthz.dll" />
            <add name="WindowsAuthenticationModule" image="%windir%\System32\inetsrv\authsspi.dll" />
            <add name="IpRestrictionModule" image="%windir%\System32\inetsrv\iprestr.dll" />
            <add name="DynamicIpRestrictionModule" image="%windir%\System32\inetsrv\diprestr.dll" />
            <add name="RequestFilteringModule" image="%windir%\System32\inetsrv\modrqflt.dll" />
            <add name="CustomErrorModule" image="%windir%\System32\inetsrv\custerr.dll" />
            <add name="RequestMonitorModule" image="%windir%\System32\inetsrv\iisreqs.dll" />
            <add name="IsapiModule" image="%windir%\System32\inetsrv\isapi.dll" />
            <add name="IsapiFilterModule" image="%windir%\System32\inetsrv\filter.dll" />
            <add name="ManagedEngine64" image="%windir%\Microsoft.NET\Framework64\v2.0.50727\webengine.dll" preCondition="integratedMode,runtimeVersionv2.0,bitness64" />
            <add name="ManagedEngine" image="%windir%\Microsoft.NET\Framework\v2.0.50727\webengine.dll" preCondition="integratedMode,runtimeVersionv2.0,bitness32" />
            <add name="ManagedEngineV4.0_32bit" image="%windir%\Microsoft.NET\Framework\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness32" />
            <add name="ManagedEngineV4.0_64bit" image="%windir%\Microsoft.NET\Framework64\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness64" />
            <add name="ConfigurationValidationModule" image="%windir%\System32\inetsrv\validcfg.dll" />
            <add name="WebSocketModule" image="%windir%\System32\inetsrv\iiswsock.dll" />
            <add name="RewriteModule" image="%SystemRoot%\system32\inetsrv\rewrite.dll" />
            <add name="AspNetCoreModuleV2" image="%ProgramFiles%\IIS\Asp.Net Core Module\V2\aspnetcorev2.dll" />
        </globalModules>

        < ... />

        <security>

            <access sslFlags="None" />

            <applicationDependencies />

            <authentication>

                <anonymousAuthentication enabled="true" userName="IUSR" />

                <basicAuthentication />

                <clientCertificateMappingAuthentication />

                <digestAuthentication />

                <iisClientCertificateMappingAuthentication />

                <windowsAuthentication enabled="false" authPersistNonNTLM="true">
                    <providers>
                        <add value="Negotiate" />
                        <add value="NTLM" />
                    </providers>
                </windowsAuthentication>

            </authentication>

            <authorization>
                <add accessType="Allow" users="*" />
            </authorization>

            <ipSecurity allowUnlisted="true" />

            <isapiCgiRestriction>
                <add path="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v2.0.50727" description="ASP.NET v2.0.50727" />
                <add path="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v2.0.50727" description="ASP.NET v2.0.50727" />
                <add path="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v4.0.30319" description="ASP.NET v4.0.30319" />
                <add path="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v4.0.30319" description="ASP.NET v4.0.30319" />
            </isapiCgiRestriction>

            < ... />

        </security>

        < ... />

    </system.webServer>
    <location path="" overrideMode="Allow">
        <system.webServer>

        <modules>
          < ... />
        </modules>

        <handlers accessPolicy="Read, Script">
              < ... />
        </handlers>
        </system.webServer>
    </location>

</configuration>
</code>```

答:
You should enable Application Initialization module on the server to restart the application automatically.

By default in IIS, if no request is sent to the application for 20 minutes, the application will be suspended.

This PowerShell script can help you to keep your application always live

```<code>## IIS WebAdmin Module
    Import-Module WebAdministration

    $AppPoolInstance = Get-Item IIS:\AppPools\$AppPool

    Write-Output "Set Site PreLoadEnabled to true"
    Set-ItemProperty IIS:\Sites\$Site -name applicationDefaults.preloadEnabled -value True

    Write-Output "Set Recycling.periodicRestart.time  = 0"
    $AppPoolInstance.Recycling.periodicRestart.time = [TimeSpan]::Parse("0");
    $AppPoolInstance | Set-Item

    Write-Output "Set App Pool start up mode to AlwaysRunning"
    $AppPoolInstance.startMode = "alwaysrunning"

    Write-Output "Disable App Pool Idle Timeout"
    $AppPoolInstance.processModel.idleTimeout = [TimeSpan]::FromMinutes(0)
    $AppPoolInstance | Set-Item

    if ($appPoolStatus -ne "Started") {
        Write-Output "Starting App Pool"
        Start-WebAppPool $AppPool
    } else {
        Write-Output "Restarting App Pool"
        Restart-WebAppPool $AppPool
    }
</code>```

Note: you should change the $AppPool and $Site names to your application

This link maybe helpful for you

Body:
I have a .NET 6 IHostedService hosted on IIS 10 Windows Server 2019.

I am aiming for

startup the application after server reboot

startup the application after iisreset

startup the application after iisreset /start

I followed the SO post here and this blog post

Regarding SO post's answer:

I did a reboot of server

followed all steps

Regarding the blog post:

I tried setting the CLR to both "No Managed Code" and "v4.0"

I have found some mention on other sites that I have to have anonymous auth enabled - this was also tested (see below in applicationhost.config)

However I can't have this basic feature of IIS up and running. According to SO post and blog post, it seems that it helped most of the people.

web.config:

<?xml version="1.0" encoding="utf-8"?>
   <configuration>
       <location path="." inheritInChildApplications="false">
           <system.webServer>
               <handlers>
                   <remove name="aspNetCore" />
                   <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
               </handlers>
               <aspNetCore processPath="dotnet" arguments=".\<obfuscated>.dll"
                           stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout"
                           hostingModel="inprocess">
                   <environmentVariables>
                       <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
                   </environmentVariables>
               </aspNetCore>
            </system.webServer>
        </location>
    </configuration>

applicationhost.config:

<?xml version="1.0" encoding="UTF-8"?>
< ... />
<configuration>
    <system.applicationHost>
        <applicationPools>
            <add name="obfuscated" autoStart="true" managedRuntimeVersion="v4.0" startMode="AlwaysRunning">
                <processModel identityType="SpecificUser" userName="obfuscated" password="obfuscated" idleTimeout="00:00:00" />
            </add>
            <applicationPoolDefaults managedRuntimeVersion="v4.0">
                <processModel identityType="ApplicationPoolIdentity" />
                <recycling logEventOnRecycle="Time, Requests, Schedule, Memory, IsapiUnhealthy, OnDemand, ConfigChange, PrivateMemory">
                    <periodicRestart time="00:00:00" />
                </recycling>
            </applicationPoolDefaults>
        </applicationPools>

        < ... />

        <sites>
            <site name="obfuscated" id="1">
                <application path="/" applicationPool="obfuscated" preloadEnabled="true">
                    <virtualDirectory path="/" physicalPath="obfuscated" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="obfuscated" />
                </bindings>
            </site>
            <siteDefaults>
                <logFile logExtFileFlags="Date, Time, ClientIP, UserName, SiteName, ComputerName, ServerIP, Method, UriStem, UriQuery, HttpStatus, Win32Status, TimeTaken, ServerPort, UserAgent, Referer, Host, HttpSubStatus" logFormat="W3C" directory="obfuscated">
                </logFile>
                <traceFailedRequestsLogging directory="obfuscated" />
            </siteDefaults>
            <applicationDefaults applicationPool="DefaultAppPool" />
            <virtualDirectoryDefaults allowSubDirConfig="true" />
        </sites>

        <webLimits />
    </system.applicationHost>

    <system.webServer>

        <asp />

        <caching enabled="true" enableKernelCache="true">
        </caching>

        <cgi />

        <defaultDocument enabled="true">
            <files>
                <add value="Default.htm" />
                <add value="Default.asp" />
                <add value="index.htm" />
                <add value="index.html" />
                <add value="iisstart.htm" />
                <add value="default.aspx" />
            </files>
        </defaultDocument>

        <directoryBrowse enabled="false" />

        <fastCgi />

        <globalModules>
            <add name="HttpLoggingModule" image="%windir%\System32\inetsrv\loghttp.dll" />
            <add name="UriCacheModule" image="%windir%\System32\inetsrv\cachuri.dll" />
            <add name="FileCacheModule" image="%windir%\System32\inetsrv\cachfile.dll" />
            <add name="TokenCacheModule" image="%windir%\System32\inetsrv\cachtokn.dll" />
            <add name="HttpCacheModule" image="%windir%\System32\inetsrv\cachhttp.dll" />
            <add name="DynamicCompressionModule" image="%windir%\System32\inetsrv\compdyn.dll" />
            <add name="StaticCompressionModule" image="%windir%\System32\inetsrv\compstat.dll" />
            <add name="DefaultDocumentModule" image="%windir%\System32\inetsrv\defdoc.dll" />
            <add name="DirectoryListingModule" image="%windir%\System32\inetsrv\dirlist.dll" />
            <add name="ProtocolSupportModule" image="%windir%\System32\inetsrv\protsup.dll" />
            <add name="HttpRedirectionModule" image="%windir%\System32\inetsrv\redirect.dll" />
            <add name="StaticFileModule" image="%windir%\System32\inetsrv\static.dll" />
            <add name="AnonymousAuthenticationModule" image="%windir%\System32\inetsrv\authanon.dll" />
            <add name="UrlAuthorizationModule" image="%windir%\System32\inetsrv\urlauthz.dll" />
            <add name="WindowsAuthenticationModule" image="%windir%\System32\inetsrv\authsspi.dll" />
            <add name="IpRestrictionModule" image="%windir%\System32\inetsrv\iprestr.dll" />
            <add name="DynamicIpRestrictionModule" image="%windir%\System32\inetsrv\diprestr.dll" />
            <add name="RequestFilteringModule" image="%windir%\System32\inetsrv\modrqflt.dll" />
            <add name="CustomErrorModule" image="%windir%\System32\inetsrv\custerr.dll" />
            <add name="RequestMonitorModule" image="%windir%\System32\inetsrv\iisreqs.dll" />
            <add name="IsapiModule" image="%windir%\System32\inetsrv\isapi.dll" />
            <add name="IsapiFilterModule" image="%windir%\System32\inetsrv\filter.dll" />
            <add name="ManagedEngine64" image="%windir%\Microsoft.NET\Framework64\v2.0.50727\webengine.dll" preCondition="integratedMode,runtimeVersionv2.0,bitness64" />
            <add name="ManagedEngine" image="%windir%\Microsoft.NET\Framework\v2.0.50727\webengine.dll" preCondition="integratedMode,runtimeVersionv2.0,bitness32" />
            <add name="ManagedEngineV4.0_32bit" image="%windir%\Microsoft.NET\Framework\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness32" />
            <add name="ManagedEngineV4.0_64bit" image="%windir%\Microsoft.NET\Framework64\v4.0.30319\webengine4.dll" preCondition="integratedMode,runtimeVersionv4.0,bitness64" />
            <add name="ConfigurationValidationModule" image="%windir%\System32\inetsrv\validcfg.dll" />
            <add name="WebSocketModule" image="%windir%\System32\inetsrv\iiswsock.dll" />
            <add name="RewriteModule" image="%SystemRoot%\system32\inetsrv\rewrite.dll" />
            <add name="AspNetCoreModuleV2" image="%ProgramFiles%\IIS\Asp.Net Core Module\V2\aspnetcorev2.dll" />
        </globalModules>

        < ... />

        <security>

            <access sslFlags="None" />

            <applicationDependencies />

            <authentication>

                <anonymousAuthentication enabled="true" userName="IUSR" />

                <basicAuthentication />

                <clientCertificateMappingAuthentication />

                <digestAuthentication />

                <iisClientCertificateMappingAuthentication />

                <windowsAuthentication enabled="false" authPersistNonNTLM="true">
                    <providers>
                        <add value="Negotiate" />
                        <add value="NTLM" />
                    </providers>
                </windowsAuthentication>

            </authentication>

            <authorization>
                <add accessType="Allow" users="*" />
            </authorization>

            <ipSecurity allowUnlisted="true" />

            <isapiCgiRestriction>
                <add path="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v2.0.50727" description="ASP.NET v2.0.50727" />
                <add path="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v2.0.50727" description="ASP.NET v2.0.50727" />
                <add path="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v4.0.30319" description="ASP.NET v4.0.30319" />
                <add path="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" allowed="true" groupId="ASP.NET v4.0.30319" description="ASP.NET v4.0.30319" />
            </isapiCgiRestriction>

            < ... />

        </security>

        < ... />

    </system.webServer>
    <location path="" overrideMode="Allow">
        <system.webServer>

        <modules>
          < ... />
        </modules>

        <handlers accessPolicy="Read, Script">
              < ... />
        </handlers>
        </system.webServer>
    </location>

</configuration>

Body:
You should enable Application Initialization module on the server to restart the application automatically.

By default in IIS, if no request is sent to the application for 20 minutes, the application will be suspended.

This PowerShell script can help you to keep your application always live

## IIS WebAdmin Module
    Import-Module WebAdministration

    $AppPoolInstance = Get-Item IIS:\AppPools\$AppPool

    Write-Output "Set Site PreLoadEnabled to true"
    Set-ItemProperty IIS:\Sites\$Site -name applicationDefaults.preloadEnabled -value True

    Write-Output "Set Recycling.periodicRestart.time  = 0"
    $AppPoolInstance.Recycling.periodicRestart.time = [TimeSpan]::Parse("0");
    $AppPoolInstance | Set-Item

    Write-Output "Set App Pool start up mode to AlwaysRunning"
    $AppPoolInstance.startMode = "alwaysrunning"

    Write-Output "Disable App Pool Idle Timeout"
    $AppPoolInstance.processModel.idleTimeout = [TimeSpan]::FromMinutes(0)
    $AppPoolInstance | Set-Item

    if ($appPoolStatus -ne "Started") {
        Write-Output "Starting App Pool"
        Start-WebAppPool $AppPool
    } else {
        Write-Output "Restarting App Pool"
        Restart-WebAppPool $AppPool
    }

Note: you should change the $AppPool and $Site names to your application

This link maybe helpful for you


问:
How to load transformers pipeline from folder?
According to here pipeline provides an interface to save a pretrained pipeline locally with a save_pretrained method. When I use it, I see a folder created with a bunch of json and bin files presumably for the tokenizer and the model.

But the documentation does not specify a load method. How does one initialize a pipeline using a locally saved pipeline?

答:
Apparently the default initialization works with local folders as well. So one can download a model like this:

```<code>pipe = pipeline("text-classification")
pipe.save_pretrained("my_local_path")
</code>```

And later load it like

```<code>pipe = pipeline("text-classification", model = "my_local_path")
</code>```

Body:
Apparently the default initialization works with local folders as well. So one can download a model like this:

pipe = pipeline("text-classification")
pipe.save_pretrained("my_local_path")

And later load it like

pipe = pipeline("text-classification", model = "my_local_path")


问:
How can I mock a function which is in other file and that return a promise?
I'm writing a Jest test. I need to test a function that calls a function in another .js file. This called function returns a promise that resolves to a string. When I start the test I get the error "file.function is not a function", where instead of "file" I have the name of the imported js file and instead of "function" I have the name of the function that return the promise.

Below my test:

```<code>test('test', () => {

     jest.mock('../file', () => {
         function: jest.fn().mockReturnValue('Returned String')
     });

     myFunction();
     expect().toBe();

});
</code>```

Explanation: first of all I mocked the module which contains the function that return a promise. With second parameter (of jest.mock) I mocked the function contained in mocked module. Next I call the function that I want to test (this function will call mocked function). Finally, I test the expectations. Someone can help me, please. I don't know how I can resolve, thanks to all.

答:
jest.mock should be at the same level as imports. If you need to test multiple cases just mock the returned/resolved value each time.</p>
```<code>import { myFunction } from './fn';
import { function } from '../file';
jest.mock('../file', () => {
    function: jest.fn(),
});

describe('myFunction tests', () => {
  describe('With returned string', () => {
    beforeEach(() => {
      function.mockReturnValue('Returned String');
    });

    it('should do sth', () => {
      myFunction();
      // expect(...).toBe(...);
    });
  });

  describe('With returned number', () => {
    beforeEach(() => {
      function.mockReturnValue(7);
    });

    it('should do other thing', () => {
      myFunction();
      // expect(...).toBe(...);
    });
  });
});
</code>```

Body:
I'm writing a Jest test. I need to test a function that calls a function in another .js file. This called function returns a promise that resolves to a string. When I start the test I get the error "file.function is not a function", where instead of "file" I have the name of the imported js file and instead of "function" I have the name of the function that return the promise.

Below my test:

test('test', () => {

     jest.mock('../file', () => {
         function: jest.fn().mockReturnValue('Returned String')
     });

     myFunction();
     expect().toBe();

});

Explanation: first of all I mocked the module which contains the function that return a promise. With second parameter (of jest.mock) I mocked the function contained in mocked module. Next I call the function that I want to test (this function will call mocked function). Finally, I test the expectations. Someone can help me, please. I don't know how I can resolve, thanks to all.

Body:
jest.mock should be at the same level as imports. If you need to test multiple cases just mock the returned/resolved value each time.

import { myFunction } from './fn';
import { function } from '../file';
jest.mock('../file', () => {
    function: jest.fn(),
});

describe('myFunction tests', () => {
  describe('With returned string', () => {
    beforeEach(() => {
      function.mockReturnValue('Returned String');
    });

    it('should do sth', () => {
      myFunction();
      // expect(...).toBe(...);
    });
  });

  describe('With returned number', () => {
    beforeEach(() => {
      function.mockReturnValue(7);
    });

    it('should do other thing', () => {
      myFunction();
      // expect(...).toBe(...);
    });
  });
});