问:
how to exclude fields that are in one depth level with DRF?
how to exclude fields that are in one depth level in django rest framework?

I want to remove id field in testPieces and resultTestsList.

this is my API:

my serializer:

```<code>class Test_Serializer(serializers.ModelSerializer):
    class Meta:
        model = Test_1
        exclude = ["id"]
        depth = 3
</code>```

my models:

```<code>class Test_pieces_1_question(models.Model):
    question = models.CharField(max_length=3000)
    yesScore = models.IntegerField()
    noScore = models.IntegerField()

class Result_tests_list_1(models.Model):
    text = models.CharField(max_length=3000)
    score = models.IntegerField()
    unicode = models.CharField(max_length=500)

class Test_1(models.Model):
    name = models.TextField(max_length=3000)
    category = models.CharField(max_length=500)
    time = models.CharField(max_length=500)
    testPieces = models.ManyToManyField(Test_pieces_1_question)
    resultTestsList = models.ManyToManyField(Result_tests_list_1)

</code>```

my view:

```<code>class Whole_test(mixins.ListModelMixin, generics.GenericAPIView):
    queryset = Test_1.objects.all()
    serializer_class = Test_Serializer
    filter_backends = [DjangoFilterBackend]

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)
</code>```

thanks!

答:
The best way to do this is to use custom nested serializers. And expose the fields that you really want to expose to the frontend app. It is called the zero-trust approach. I personally prefer it over the exclude approach.

Let's rewrite your serializer in a way to achieve the same result as depth =3

```<code>class Test_Serializer(serializers.ModelSerializer):
    testPieces = TimePiecesSerializer(many=True, read_only=True)
    resultTestsList = TimeResultSerializer(many=True, read_only=True)
    class Meta:
        model = Test_1
        fields = ["name", "category", "time", "testPieces", "resultTestsList"]
</code>```

As you see I have added to nested serializer instead of depth=3

So here is the code for those custom serializers

```<code>class TimePiecesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test_pieces_1_question
        fields = ["question", "yesScore", "noScore"]

class TimeResultSerializer(serializers.ModelSerializer):

    class Meta:
        model = Result_tests_list_1
        fields = ["text", "score", "unicode"]
</code>```

Using the above nesting serializer approach will give you the same results as depth and will also exclude the key id as it seems you are not interested in it.

You may need a little tunning according to your fields but it is a more promising approach over others.

Body:
how to exclude fields that are in one depth level in django rest framework?

I want to remove id field in testPieces and resultTestsList.

this is my API:

my serializer:

class Test_Serializer(serializers.ModelSerializer):
    class Meta:
        model = Test_1
        exclude = ["id"]
        depth = 3

my models:

class Test_pieces_1_question(models.Model):
    question = models.CharField(max_length=3000)
    yesScore = models.IntegerField()
    noScore = models.IntegerField()

class Result_tests_list_1(models.Model):
    text = models.CharField(max_length=3000)
    score = models.IntegerField()
    unicode = models.CharField(max_length=500)

class Test_1(models.Model):
    name = models.TextField(max_length=3000)
    category = models.CharField(max_length=500)
    time = models.CharField(max_length=500)
    testPieces = models.ManyToManyField(Test_pieces_1_question)
    resultTestsList = models.ManyToManyField(Result_tests_list_1)

my view:

class Whole_test(mixins.ListModelMixin, generics.GenericAPIView):
    queryset = Test_1.objects.all()
    serializer_class = Test_Serializer
    filter_backends = [DjangoFilterBackend]

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

thanks!

Body:
The best way to do this is to use custom nested serializers. And expose the fields that you really want to expose to the frontend app. It is called the zero-trust approach. I personally prefer it over the exclude approach.

Let's rewrite your serializer in a way to achieve the same result as depth =3

class Test_Serializer(serializers.ModelSerializer):
    testPieces = TimePiecesSerializer(many=True, read_only=True)
    resultTestsList = TimeResultSerializer(many=True, read_only=True)
    class Meta:
        model = Test_1
        fields = ["name", "category", "time", "testPieces", "resultTestsList"]

As you see I have added to nested serializer instead of depth=3

So here is the code for those custom serializers

class TimePiecesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test_pieces_1_question
        fields = ["question", "yesScore", "noScore"]

class TimeResultSerializer(serializers.ModelSerializer):

    class Meta:
        model = Result_tests_list_1
        fields = ["text", "score", "unicode"]

Using the above nesting serializer approach will give you the same results as depth and will also exclude the key id as it seems you are not interested in it.

You may need a little tunning according to your fields but it is a more promising approach over others.


来源: stackexchange

问:
sql oracle Old Join Syntax vs. New
I ask if any one can help me to write my query below use modern join syntax sql oracle :

```<code> SELECT /*+ USE_NL_WITH_INDEX(D) */ N.MARCHE,N.NLBIX,D.NUORD,D.NUCON, 0 NUBI2, N.COINF, D.COINL, D.COINA, D.COINV, N.COINN, D.COINC, D.NUCPT, D.COINI, N.COINK, N.CNACT, N.NUCAR
    FROM VBANET N, VBADET D
    WHERE N.MARCHE IN ('DDL')
    AND D.MARCHE(+)= N.MARCHE
    AND D.NUBIX(+)= N.NUBIX AND N.CTFNE NOT IN ('T','R')
    AND
    D.CTFRE(+) != 'R' AND (N.NLBIX IN (SELECT /*+ UNNEST NO_USE_HASH_AGGREGATION */ DISTINCT FN.NLBIX
    FROM DICCRN FN, RICCRD FD
    WHERE
    FN.MARCHE IN ('OCC') AND
    FD.NLBIX(+)= FN.NLBIX AND
    FD.MARCHE(+)= FN.MARCHE AND
    ( FN.NUSEQ IS NOT NULL OR FD.NUSEQ IS NOT NULL )) );
</code>```

help plz

答:
You appear to want:

SELECT /*+ USE_NL_WITH_INDEX(D) */
       N.MARCHE,
       N.NLBIX,
       D.NUORD,
       D.NUCON,
       0 NUBI2,
       N.COINF,
       D.COINL,
       D.COINA,
       D.COINV,
       N.COINN,
       D.COINC,
       D.NUCPT,
       D.COINI,
       N.COINK,
       N.CNACT,
       N.NUCAR
FROM   VBANET N
       LEFT OUTER JOIN VBADET D
       ON (   D.MARCHE = N.MARCHE
          AND D.NUBIX  = N.NUBIX
          AND D.CTFRE != 'R'
          )
WHERE  N.MARCHE IN ('DDL')
AND    N.CTFNE NOT IN ('T','R')
AND    N.NLBIX IN (
         SELECT /*+ UNNEST NO_USE_HASH_AGGREGATION */
                DISTINCT
                FN.NLBIX
         FROM   DICCRN FN
                LEFT OUTER JOIN RICCRD FD
                ON (   FD.NLBIX  = FN.NLBIX
                   AND FD.MARCHE = FN.MARCHE
                   )
         WHERE  FN.MARCHE IN ('OCC')
         AND    ( FN.NUSEQ IS NOT NULL OR FD.NUSEQ IS NOT NULL )
       )
```
<p><em>You also probably do not need the <code>DISTINCT</code> clause in the sub-query.</em></p>
<hr />
<p>You can rewrite the sub-query to:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT N.MARCHE,
       N.NLBIX,
       D.NUORD,
       D.NUCON,
       0 NUBI2,
       N.COINF,
       D.COINL,
       D.COINA,
       D.COINV,
       N.COINN,
       D.COINC,
       D.NUCPT,
       D.COINI,
       N.COINK,
       N.CNACT,
       N.NUCAR
FROM   VBANET N
       LEFT OUTER JOIN VBADET D
       ON (   D.MARCHE = N.MARCHE
          AND D.NUBIX  = N.NUBIX
          AND D.CTFRE != 'R'
          )
WHERE  N.MARCHE IN ('DDL')
AND    N.CTFNE NOT IN ('T','R')
AND    EXISTS (
         SELECT 1
         FROM   DICCRN FN
         WHERE  FN.MARCHE IN ('OCC')
         AND    N.NLBIX = FN.NLBIX
         AND    ( FN.NUSEQ IS NOT NULL
                OR EXISTS (
                     SELECT 1
                     FROM   RICCRD FD
                     WHERE  FD.NLBIX  = FN.NLBIX
                     AND    FD.MARCHE = FN.MARCHE
                     AND    FD.NUSEQ IS NOT NULL
                   )
                )
       )
</code>```

(You can use IN rather than EXISTS if you prefer.)

db<>fiddle here

ContentLicense: CC BY-SA 4.0

Title: sql oracle Old Join Syntax vs. New

Body:
I ask if any one can help me to write my query below use modern join syntax sql oracle :

 SELECT /*+ USE_NL_WITH_INDEX(D) */ N.MARCHE,N.NLBIX,D.NUORD,D.NUCON, 0 NUBI2, N.COINF, D.COINL, D.COINA, D.COINV, N.COINN, D.COINC, D.NUCPT, D.COINI, N.COINK, N.CNACT, N.NUCAR
    FROM VBANET N, VBADET D
    WHERE N.MARCHE IN ('DDL')
    AND D.MARCHE(+)= N.MARCHE
    AND D.NUBIX(+)= N.NUBIX AND N.CTFNE NOT IN ('T','R')
    AND
    D.CTFRE(+) != 'R' AND (N.NLBIX IN (SELECT /*+ UNNEST NO_USE_HASH_AGGREGATION */ DISTINCT FN.NLBIX
    FROM DICCRN FN, RICCRD FD
    WHERE
    FN.MARCHE IN ('OCC') AND
    FD.NLBIX(+)= FN.NLBIX AND
    FD.MARCHE(+)= FN.MARCHE AND
    ( FN.NUSEQ IS NOT NULL OR FD.NUSEQ IS NOT NULL )) );

help plz

Body:
You appear to want:

SELECT /*+ USE_NL_WITH_INDEX(D) */
       N.MARCHE,
       N.NLBIX,
       D.NUORD,
       D.NUCON,
       0 NUBI2,
       N.COINF,
       D.COINL,
       D.COINA,
       D.COINV,
       N.COINN,
       D.COINC,
       D.NUCPT,
       D.COINI,
       N.COINK,
       N.CNACT,
       N.NUCAR
FROM   VBANET N
       LEFT OUTER JOIN VBADET D
       ON (   D.MARCHE = N.MARCHE
          AND D.NUBIX  = N.NUBIX
          AND D.CTFRE != 'R'
          )
WHERE  N.MARCHE IN ('DDL')
AND    N.CTFNE NOT IN ('T','R')
AND    N.NLBIX IN (
         SELECT /*+ UNNEST NO_USE_HASH_AGGREGATION */
                DISTINCT
                FN.NLBIX
         FROM   DICCRN FN
                LEFT OUTER JOIN RICCRD FD
                ON (   FD.NLBIX  = FN.NLBIX
                   AND FD.MARCHE = FN.MARCHE
                   )
         WHERE  FN.MARCHE IN ('OCC')
         AND    ( FN.NUSEQ IS NOT NULL OR FD.NUSEQ IS NOT NULL )
       )

You also probably do not need the DISTINCT clause in the sub-query.

You can rewrite the sub-query to:

SELECT N.MARCHE,
       N.NLBIX,
       D.NUORD,
       D.NUCON,
       0 NUBI2,
       N.COINF,
       D.COINL,
       D.COINA,
       D.COINV,
       N.COINN,
       D.COINC,
       D.NUCPT,
       D.COINI,
       N.COINK,
       N.CNACT,
       N.NUCAR
FROM   VBANET N
       LEFT OUTER JOIN VBADET D
       ON (   D.MARCHE = N.MARCHE
          AND D.NUBIX  = N.NUBIX
          AND D.CTFRE != 'R'
          )
WHERE  N.MARCHE IN ('DDL')
AND    N.CTFNE NOT IN ('T','R')
AND    EXISTS (
         SELECT 1
         FROM   DICCRN FN
         WHERE  FN.MARCHE IN ('OCC')
         AND    N.NLBIX = FN.NLBIX
         AND    ( FN.NUSEQ IS NOT NULL
                OR EXISTS (
                     SELECT 1
                     FROM   RICCRD FD
                     WHERE  FD.NLBIX  = FN.NLBIX
                     AND    FD.MARCHE = FN.MARCHE
                     AND    FD.NUSEQ IS NOT NULL
                   )
                )
       )

(You can use IN rather than EXISTS if you prefer.)

db<>fiddle here


问:
Why is there an error when installing vuex?
Tell me, I understand that there is a problem in the versions, but how to solve it?

I have tried:

```<code>npm cache clean --force commands
npm install -g npm-install-peers
npm install --legacy-peer-deps
</code>```

Install with npm install --save-dev vuex@next gives me this error

My package.json file:

```<code>"name": "",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"serve:standalone": "vue-cli-service serve --mode standalone"
},
"dependencies": {
"core-js": "^3.6.5",
"devextreme": "21.2.5",
"devextreme-vue": "21.2.5",
"single-spa-vue": "^2.1.0",
"vue": "^2.6.11"
},
"devDependencies": {
"@storybook/vue": "^6.4.14",
"@vue/cli": "^4.5.15",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"node-sass": "^6.0.1",
"sass-loader": "^10",
"eslint-plugin-vue": "^6.2.2",
"vue-cli-plugin-single-spa": "~3.1.2",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
  "node": true
},
"extends": [
  "plugin:vue/essential",
  "eslint:recommended"
],
"parserOptions": {
  "parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
 "not dead"
]
</code>```

答:
That is because you're trying to install Vuex@4, which is only compatible with Vue@3. However, your project is using Vue@2 instead.

You will need to decide which Vue version you want to use. Since you mentioned that you only want to use Vue2, you need to install the Vuex@3 instead:

```<code>npm install vuex@3
</code>```

Body:
Tell me, I understand that there is a problem in the versions, but how to solve it?

I have tried:

npm cache clean --force commands
npm install -g npm-install-peers
npm install --legacy-peer-deps

Install with npm install --save-dev vuex@next gives me this error

My package.json file:

"name": "",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"serve:standalone": "vue-cli-service serve --mode standalone"
},
"dependencies": {
"core-js": "^3.6.5",
"devextreme": "21.2.5",
"devextreme-vue": "21.2.5",
"single-spa-vue": "^2.1.0",
"vue": "^2.6.11"
},
"devDependencies": {
"@storybook/vue": "^6.4.14",
"@vue/cli": "^4.5.15",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"node-sass": "^6.0.1",
"sass-loader": "^10",
"eslint-plugin-vue": "^6.2.2",
"vue-cli-plugin-single-spa": "~3.1.2",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
  "node": true
},
"extends": [
  "plugin:vue/essential",
  "eslint:recommended"
],
"parserOptions": {
  "parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
 "not dead"
]

Body:
That is because you're trying to install Vuex@4, which is only compatible with Vue@3. However, your project is using Vue@2 instead.

You will need to decide which Vue version you want to use. Since you mentioned that you only want to use Vue2, you need to install the Vuex@3 instead:

npm install vuex@3


问:
Using .text() to retrieve only text not nested in child tags
If I have html like this:

```<code><li id="listItem">
    This is some text
    <span id="firstSpan">First span text</span>
    <span id="secondSpan">Second span text</span>
</li>
</code>```

I'm trying to use .text() to retrieve just the string "This is some text", but if I were to say $('#list-item').text(), I get "This is some textFirst span textSecond span text".

Is there a way to get (and possibly remove, via something like .text("")) just the free text within a tag, and not the text within its child tags?

The HTML was not written by me, so this is what I have to work with. I know that it would be simple to just wrap the text in tags when writing the html, but again, the html is pre-written.

答:
For beginners:

I preferred @DUzun's answer because it's simple to understand and more efficient than the accepted answer. But it only partially worked for me as you can't directly pass the element with a class selector like this

```<code>$(".landing-center .articlelanding_detail").get(0).immediateText() //gives .immediateText is not a function error
</code>```

or this

```<code>$(".landing-center .articlelanding_detail")[0].immediateText() //gives .immediateText is not a function error
</code>```

because once you extract the native Element by using [index] or .get(index) out of the $() function you loose jQuery Object methods chainability as mentioned here. And most of the solutions are only in context to ids, not so elegant to use multiple times for the elements with a class selectors.

So, I wrote jQuery plugin:

```<code>$.fn.mainText = function(x=0) {
    return $.trim(this.eq(x).contents().not(this.eq(x).children()).text().replace(/[\t\n]+/g,' '));
};
</code>```

This will return the text of the element irrespective of if ids or class are used as selectors excluding child elements. Also will remove any \t or \n to get a clean string.
Use it like this:

Case 1

```<code>$("#example").mainText(); // get the text of element with example id
</code>```

Case 2

```<code>$(".example").mainText(); // get the text of first element with example class
</code>```

Case 3

```<code>$(".example").mainText(1); // get the text of second element with example class and so on..
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I have html like this:

    This is some text
    First span text
    Second span text

I'm trying to use .text() to retrieve just the string "This is some text", but if I were to say $('#list-item').text(), I get "This is some textFirst span textSecond span text".

Is there a way to get (and possibly remove, via something like .text("")) just the free text within a tag, and not the text within its child tags?

The HTML was not written by me, so this is what I have to work with. I know that it would be simple to just wrap the text in tags when writing the html, but again, the html is pre-written.

Body:
For beginners:

I preferred @DUzun's answer because it's simple to understand and more efficient than the accepted answer. But it only partially worked for me as you can't directly pass the element with a class selector like this

$(".landing-center .articlelanding_detail").get(0).immediateText() //gives .immediateText is not a function error

or this

$(".landing-center .articlelanding_detail")[0].immediateText() //gives .immediateText is not a function error

because once you extract the native Element by using [index] or .get(index) out of the $() function you loose jQuery Object methods chainability as mentioned here. And most of the solutions are only in context to ids, not so elegant to use multiple times for the elements with a class selectors.

So, I wrote jQuery plugin:

$.fn.mainText = function(x=0) {
    return $.trim(this.eq(x).contents().not(this.eq(x).children()).text().replace(/[\t\n]+/g,' '));
};

This will return the text of the element irrespective of if ids or class are used as selectors excluding child elements. Also will remove any \t or \n to get a clean string.
Use it like this:

Case 1

$("#example").mainText(); // get the text of element with example id

Case 2

$(".example").mainText(); // get the text of first element with example class

Case 3

$(".example").mainText(1); // get the text of second element with example class and so on..


问:
Can I use hotwired turbo.js offline?
I'm trying to use turbo-flask in my python flask application. It tries to download turbo.js but failes because I'm not working with an internet connection.
I thought about inserting the js file directly into my project but couldnt find it anywhere.
Is it possible to use it offline?</p>

答:
Short answer: YES.

You can install Turbo as instructed in Turbo Handbook

But that's without turbo-flask package, which uses CDN version as default.

But it seems like you can do (for example) this:

```<code>{{ turbo(url=url_for('static', filename="node_modules/@hotwired/turbo/dist/turbo.es2017-umd.js")) }}
</code>```

and then your app uses this downloaded js.

This code is from my project, using npm. If you don't you need to change the path accordingly.

Title: Can I use hotwired turbo.js offline?

Body:
Short answer: YES.

You can install Turbo as instructed in Turbo Handbook

But that's without turbo-flask package, which uses CDN version as default.

But it seems like you can do (for example) this:

{{ turbo(url=url_for('static', filename="node_modules/@hotwired/turbo/dist/turbo.es2017-umd.js")) }}

and then your app uses this downloaded js.

This code is from my project, using npm. If you don't you need to change the path accordingly.


问:
How to apply if condition for WPF Project in XAML?
I have TreeView and TreeViewItems. TreeViewItems contain Tags either "type", "class", "subclass", or a Guid in the form "0202-7252-4a4a...".

What I am currently doing is that I am displaying the Tag and Header of those TreeViewItems on the screen with the following code.

(Please do not consider how I am creating the TreeViewItems, it is not relevant for my case)

<TreeView x:Name="treeView"/>

<TextBlock>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Tag}"/>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>
```
<p>I don't want to write the <code>Tag</code> of a <code>TreeViewItem</code> whose tag is <code>Guid</code> because it doesn't seem pretty in the screen. I want to add an if condition to this code as follows:</p>
```if (TreeViewItem.Tag == "type" or "class" or "subclass")
    write tag and header to screen
else do nothing
```
<p>OR</p>
```if (TreeViewItem.Tag is Guid) then do nothing
```

答:
You could create a converter that returns a Visibility for certain keywords. In XAML you can pass a list of keywords in XAML that will return Visibility.Visible, otherwise it will be Visibility.Hidden.

```<code>public class KeywordToVisibilityConverter : IValueConverter
{
   public List<string> Keywords { get; }

   public KeywordToVisibilityConverter()
   {
      Keywords = new List<string>();
   }

   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      return value is string keyword
         ? Keywords.Contains(keyword) ? Visibility.Visible : Visibility.Hidden
         : Visibility.Hidden;
   }

   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
      throw new InvalidOperationException();
   }
}
</code>```

Create an instance of the converter in a resource dictionary in scope, e.g. TreeView.Resources.

```<code><TreeView.Resources>
   <local:KeywordToVisibilityConverter x:Key="KeywordToVisibilityConverter">
      <local:KeywordToVisibilityConverter.Keywords>
         <system:String>type</system:String>
         <system:String>class</system:String>
         <system:String>subclass</system:String>
      </local:KeywordToVisibilityConverter.Keywords>
   </local:KeywordToVisibilityConverter>
</TreeView.Resources>
</code>```

Do not forget to add the XML namespace for system.

xmlns:system="clr-namespace:System;assembly=System.Runtime" for .NET Core

xmlns:system="clr-namespace:System;assembly=mscorlib" for .NET Framework

Then, use the converter to set the visibility of the TextBlock depending on Tag.

```<code><TextBlock Visibility="{Binding SelectedItem.Tag, ElementName=treeView, Converter={StaticResource KeywordToVisibilityConverter}}">
   <Run Text="{Binding ElementName=treeView, Path=SelectedItem.Tag}"/>
   <Run Text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>
</code>```

A converter for your second case is fairly easier, as it just checks the type (no namespace or list needed).

```<code>public class IsGuidToVisibilityConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      return value is Guid ? Visibility.Hidden : Visibility.Visible;
   }

   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
      throw new InvalidOperationException();
   }
}
</code>```

As before, create an instance in XAML and use it to bind the Visibility of TextBlock.

As a note, if you wanted to bind the allowed keywords, too, the you would have to create a IMultiValueConverter used in a MultiBinding in XAML. If you want the TextBlock not only hidden, but removed leaving empty space, replace Hidden with Collapsed. Finally, to state the obvious: Be careful, the approaches are not equivalent. Depending on the possible Tag values they may lead to different results.

Body:
I have TreeView and TreeViewItems. TreeViewItems contain Tags either "type", "class", "subclass", or a Guid in the form "0202-7252-4a4a...".

What I am currently doing is that I am displaying the Tag and Header of those TreeViewItems on the screen with the following code.

(Please do not consider how I am creating the TreeViewItems, it is not relevant for my case)

<TreeView x:Name="treeView"/>

<TextBlock>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Tag}"/>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>

I don't want to write the Tag of a TreeViewItem whose tag is Guid because it doesn't seem pretty in the screen. I want to add an if condition to this code as follows:

if (TreeViewItem.Tag == "type" or "class" or "subclass")
    write tag and header to screen
else do nothing

OR

if (TreeViewItem.Tag is Guid) then do nothing

Body:
You could create a converter that returns a Visibility for certain keywords. In XAML you can pass a list of keywords in XAML that will return Visibility.Visible, otherwise it will be Visibility.Hidden.

public class KeywordToVisibilityConverter : IValueConverter
{
   public List<string> Keywords { get; }

   public KeywordToVisibilityConverter()
   {
      Keywords = new List<string>();
   }

   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      return value is string keyword
         ? Keywords.Contains(keyword) ? Visibility.Visible : Visibility.Hidden
         : Visibility.Hidden;
   }

   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
      throw new InvalidOperationException();
   }
}

Create an instance of the converter in a resource dictionary in scope, e.g. TreeView.Resources.

<TreeView.Resources>
   <local:KeywordToVisibilityConverter x:Key="KeywordToVisibilityConverter">
      <local:KeywordToVisibilityConverter.Keywords>
         <system:String>type</system:String>
         <system:String>class</system:String>
         <system:String>subclass</system:String>
      </local:KeywordToVisibilityConverter.Keywords>
   </local:KeywordToVisibilityConverter>
</TreeView.Resources>

Do not forget to add the XML namespace for system.

xmlns:system="clr-namespace:System;assembly=System.Runtime" for .NET Core

xmlns:system="clr-namespace:System;assembly=mscorlib" for .NET Framework

Then, use the converter to set the visibility of the TextBlock depending on Tag.

<TextBlock Visibility="{Binding SelectedItem.Tag, ElementName=treeView, Converter={StaticResource KeywordToVisibilityConverter}}">
   <Run Text="{Binding ElementName=treeView, Path=SelectedItem.Tag}"/>
   <Run Text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>

A converter for your second case is fairly easier, as it just checks the type (no namespace or list needed).

public class IsGuidToVisibilityConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
      return value is Guid ? Visibility.Hidden : Visibility.Visible;
   }

   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
      throw new InvalidOperationException();
   }
}

As before, create an instance in XAML and use it to bind the Visibility of TextBlock.

As a note, if you wanted to bind the allowed keywords, too, the you would have to create a IMultiValueConverter used in a MultiBinding in XAML. If you want the TextBlock not only hidden, but removed leaving empty space, replace Hidden with Collapsed. Finally, to state the obvious: Be careful, the approaches are not equivalent. Depending on the possible Tag values they may lead to different results.


问:
Missing Info.plist value - A value for the Info.plist key 'CFBundleIconName' is missing
When submitting my app to the App Store I receive this email:

TMS-90713: Missing Info.plist value - A value for the Info.plist key
'CFBundleIconName' is missing in the bundle '...'. Apps built with iOS
11 or later SDK must supply app icons in an asset catalog and must
also provide a value for this Info.plist key. For more information see
http://help.apple.com/xcode/mac/current/#/dev10510b1f7.

I've tried everything in this post: Missing CFBundleIconName in Xcode9 iOS11 app release

I have an Asset from the beginning of the project (it was a Template).

The bundle key is in the info.plist.

The value of the key is the same that the name of the catalog.

I have the asset selected in building settings.

I have the Target Membership checked.

I'm using Xcode 13.1 and MacBook Air M1 2020

答:
As matt mentioned in comments:

In Xcode 13 this is configured with a build setting, not by editing the Info.plist file directly.

I had it set in both locations due to the instructions in this post: Missing CFBundleIconName in Xcode9 iOS11 app release

I removed the info.plist key 'CFBundleIconName' and keep only the Build Settings and I could upload the archive with out any error.


问:
How to scroll table row by row at button click jQuery
I have table with fixed heihgt, and scrollable body, i add the button for scroling row one by one.

Ideas is to scroll row by row by user clicking.

For now i create func for scroll down, but it's not good for me, some how i need to create func to scroll table on click one row down.

```<code>$('#more-arrows').click(function () {
    var scrollBottom = Math.max($('.table-udt').height() - $('tbody').height() / 200 + 1000, 0);
    $('tbody').scrollTop(scrollBottom).animate({
        scrollBottom: 0
    }, 1000);
});
</code>```

JsFiddle

So i want to scroll on #more-arrows click, row one by one scrolle to the bottom.

答:
You can use jquery's .animate() method to achieve it. Try this

```<code>$('#more-arrows').on('click', function(){
    $('.scroll').stop().animate({
        scrollTop: '+=40px' // 40px can be the height of a row
    }, 200);
});
</code>```

Body:
I have table with fixed heihgt, and scrollable body, i add the button for scroling row one by one.

Ideas is to scroll row by row by user clicking.

For now i create func for scroll down, but it's not good for me, some how i need to create func to scroll table on click one row down.

$('#more-arrows').click(function () {
    var scrollBottom = Math.max($('.table-udt').height() - $('tbody').height() / 200 + 1000, 0);
    $('tbody').scrollTop(scrollBottom).animate({
        scrollBottom: 0
    }, 1000);
});

JsFiddle

So i want to scroll on #more-arrows click, row one by one scrolle to the bottom.

Body:
You can use jquery's .animate() method to achieve it. Try this

$('#more-arrows').on('click', function(){
    $('.scroll').stop().animate({
        scrollTop: '+=40px' // 40px can be the height of a row
    }, 200);
});


问:
How to link a Swift module produced by another xcode project?
I have two Xcode Projects that both have a iOS App target (they're in the same xcworkspace). If my understanding is correct, each of these iOS App targets produce a Swift Module (I'm using swift obviously). I'd like to include one of the App's storyboards in the other Xcode Project and present that storyboard when a button is clicked.

However, the storyboard's swift module doesn't seem to be included automatically. I moved the source files for some of the ViewControllers over and changed the module for them in Storyboards and that worked like a charm. Is there a way to "link against" another iOS App swift module?

答:
May be it's a hack but this may work. Add this commands to OTHER_LDFLAGS:

```<code>-Xlinker -add_ast_path -Xlinker $(BUILT_PRODUCTS_DIR)/"MyModule.swiftmodule"
</code>```

This solution mimics Xcode-generated build command.

Body:
May be it's a hack but this may work. Add this commands to OTHER_LDFLAGS:

-Xlinker -add_ast_path -Xlinker $(BUILT_PRODUCTS_DIR)/"MyModule.swiftmodule"

This solution mimics Xcode-generated build command.


问:
How query variables with part of var in SQLite python
I should query some variables in SQLite with part of them,like below code
and I need get all numbers in this column that start with 5070 and I use ?*

  Number = 5070
  point = 5
  point_s =25
  result1 = cur.execute("""SELECT * FROM C1 WHERE
                  point = ?
                  AND point_s = ?
                  AND trackNumber GLOB '5070*'
                  AND observed LIKE 'A%'
                  order by rowid""", (probeType, probe))
```
<p>with this way get all from column that start with 5070 but when I use ?* for var face with error</p>
<pre class="lang-py prettyprint-override"><code>  result1 = cur.execute("""SELECT * FROM C1 WHERE
                  point = ?
                  AND point_s = ?
                  AND trackNumber GLOB ?*
                  AND observed LIKE 'A%'
                  order by rowid""", (probeType, probe, TrackNumber))
</code>```

but when I use this face an error said "sqlite3.OperationalError: near "AND": syntax error"
Is there any way to solve this problem ?

+Also I use LIKE instead of GLOB still didn't work and Also I use % and face same error.

答:
Remove the asterisk from the SQL and append it to the argument:

```<code>result1 = cur.execute("""SELECT * FROM C1 WHERE
                  point = ?
                  AND point_s = ?
                  AND trackNumber GLOB ?
                  AND observed LIKE 'A%'
                  order by rowid""", (probeType, probe, str(TrackNumber) + "*"))
</code>```

If TrackNumber is already a string, the str(...) around it isn't necessary.

Body:
I should query some variables in SQLite with part of them,like below code
and I need get all numbers in this column that start with 5070 and I use ?*

  Number = 5070
  point = 5
  point_s =25
  result1 = cur.execute("""SELECT * FROM C1 WHERE
                  point = ?
                  AND point_s = ?
                  AND trackNumber GLOB '5070*'
                  AND observed LIKE 'A%'
                  order by rowid""", (probeType, probe))

with this way get all from column that start with 5070 but when I use ?* for var face with error

  result1 = cur.execute("""SELECT * FROM C1 WHERE
                  point = ?
                  AND point_s = ?
                  AND trackNumber GLOB ?*
                  AND observed LIKE 'A%'
                  order by rowid""", (probeType, probe, TrackNumber))

but when I use this face an error said "sqlite3.OperationalError: near "AND": syntax error"
Is there any way to solve this problem ?

+Also I use LIKE instead of GLOB still didn't work and Also I use % and face same error.

Body:
Remove the asterisk from the SQL and append it to the argument:

result1 = cur.execute("""SELECT * FROM C1 WHERE
                  point = ?
                  AND point_s = ?
                  AND trackNumber GLOB ?
                  AND observed LIKE 'A%'
                  order by rowid""", (probeType, probe, str(TrackNumber) + "*"))

If TrackNumber is already a string, the str(...) around it isn't necessary.


问:
how to choose tdengine's normal table and stable?
I used tdengine for a few weeks, i felt confused about stable and normal table.
How to choose between normal table and stable?
Does someone have expeirence on choosing between normal table and stable.</p>

答: If you have many child tables which share the same structure/schema, you can create a stable as the model of this schema which is also the parent of normal child tables.</p>


问:
Wordpress Custom URL not loading Post Category in Create New Post Page
I'm having an issue since last months. When I'm trying to use custom url in wordpress permalink setup, in create new post page, categories are not loading. In ajax call, it is saying invalid json data given.
Here is the permalink setup

Here is the Create new post page output with that settings

Here is the plain permalink setting

Category is loading easily with plain setting

I'm not sure is it wordpress setting issue or theme issue?

My server setting:

PHP version 7.4
Runs on Apache with Nginx in front.
Theme: Newspaper Theme by tagdiv

Please help me out.

答:
It was the issue of Nginx. Nginx does not support .htaccess file, thats why when you use Nginx as http server with wordpress, you need some modification in Nginx settings for custom url in wordpress.

Here is the explanation and sample code for Nginx setting for wordpress

https://wordpress.org/support/article/nginx/

Hope this might help some one in future.


问:
What is the difference between Openssl's BIO wrappers and SSL calls?
I have long been confused if using the BIO_* way would have obvious advantage over the raw SSL_* calls. </p>

<p>I always use the non-bio as I thought I have more control. </p>

答: BIO drives me up the wall but it allows you to transparently put in compression and other filters.  You do want compression since it 1) makes cryptanalysis harder, 2) uses less bandwidth and 3) takes less CPU to compress + encrypt than to encrypt the raw data stream.</p>

OwnerDisplayName: vjangus

ContentLicense: CC BY-SA 2.5

Body:
I have long been confused if using the BIO_* way would have obvious advantage over the raw SSL_* calls.

I always use the non-bio as I thought I have more control.

LastEditorDisplayName: vjangus


问:
How to 'narrow' onchange for specific id?
I found this cod on jquery web

```<code>$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();
</code>```

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this function to only select with specific id.

答:
This will only work for < select > elements. You shouldn't need it but try this:

```<code>$("select#my_id").change...
</code>```

also make sure it's wrapped in

```<code>$(document).ready(function(){

});
</code>```

To make sure the DOM is ready

Body:
I found this cod on jquery web

$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this function to only select with specific id.

Body:
This will only work for < select > elements. You shouldn't need it but try this:

$("select#my_id").change...

also make sure it's wrapped in

$(document).ready(function(){

});

To make sure the DOM is ready


问:
CSS Container margin bottom issue
Hi for mobile version I need margin bottom (white space from bottom of the screen) to the container, it was not working. I have tried position absolute still it was not working. I don't know what mistake exactly I did in here.

```<code> ****Desktop version CSS****
       #container {
       width: 70%;
       margin: 0 auto;
       display: flex;
       height: 100vh;
       align-items: center;
</code>```

}

```<code>****mobile version CSS****
 `     #container {
       display: block;
       text-align: center;
       margin-bottom:25px;
}
</code>```

答:
You can use position: absolute; and set top left right bottom to 0, then bottom: 25px for mobile version:

.container {
  background-color: red;
  height: 100vh;
  width: 70%;
  position: relative;
}

.item {
  background-color: black;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

@media screen and (max-width: 780px) {
  .item {
    bottom: 20px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item"></div>
</div></code>```

Title: CSS Container margin bottom issue

Body:
Hi for mobile version I need margin bottom (white space from bottom of the screen) to the container, it was not working. I have tried position absolute still it was not working. I don't know what mistake exactly I did in here.

 ****Desktop version CSS****
       #container {
       width: 70%;
       margin: 0 auto;
       display: flex;
       height: 100vh;
       align-items: center;

}

****mobile version CSS****
 `     #container {
       display: block;
       text-align: center;
       margin-bottom:25px;
}

Body:
You can use position: absolute; and set top left right bottom to 0, then bottom: 25px for mobile version:

.container {
  background-color: red;
  height: 100vh;
  width: 70%;
  position: relative;
}

.item {
  background-color: black;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

@media screen and (max-width: 780px) {
  .item {
    bottom: 20px;
  }
}

<div class="container">
  <div class="item"></div>
</div>


问:
Call load() from react-howler
I want to call load() with set timeout ,how add to my code

It offer from library

Docs:

load()

When preload is true this is automatically called. When setting
preload to false, you can call load() manually before playing sounds
(useful for lazy loading large files on slow networks). If you attempt
to play a sound that's not loading or loaded with preload react-howler
will automatically call load().

And there is my code

```<code>  <ReactHowler
          src={Audio}
          preload={false}
          playing={isplaying ? false : true}
        />
</code>```

答:
For a fully controlled example (in a class-based component) take a look at the official examples

The trick is to get a ref to the howler component, then you can call load on it. So the following should work:

```<code>const howlerRef = useRef(null);

const myLoadFunc = ()=>{
  if(howlerRef.current) {
    howlerRef.current.load();
  }
}

return (
  <>
    <ReactHowler
          src={Audio}
          preload={false}
          playing={isplaying ? false : true}
          ref={howlerRef}
        />
    <button onClick={myLoadFunc}>start loading</button>
  </>
)
</code>```

Title: Call load() from react-howler

Body:
I want to call load() with set timeout ,how add to my code

It offer from library

Docs:

load()

When preload is true this is automatically called. When setting
preload to false, you can call load() manually before playing sounds
(useful for lazy loading large files on slow networks). If you attempt
to play a sound that's not loading or loaded with preload react-howler
will automatically call load().

And there is my code

  <ReactHowler
          src={Audio}
          preload={false}
          playing={isplaying ? false : true}
        />

Body:
For a fully controlled example (in a class-based component) take a look at the official examples

The trick is to get a ref to the howler component, then you can call load on it. So the following should work:

const howlerRef = useRef(null);

const myLoadFunc = ()=>{
  if(howlerRef.current) {
    howlerRef.current.load();
  }
}

return (
  <>
    <ReactHowler
          src={Audio}
          preload={false}
          playing={isplaying ? false : true}
          ref={howlerRef}
        />
    <button onClick={myLoadFunc}>start loading</button>
  </>
)


问:
Creating data model class for database handling
I was just starting to work on an database application when I realized I should implement MVC pattern as the application is quite complex and involves a number of database operations.

In regards to this, I have decided to create a separate model class for handling database operations. This class will have all methods which will return me the data after executing Sqlite command(Select for instance) OR will simply execute the SQLite command(Delete for instance). But what I want is to separate this class from Database Adapter class, where I open, create and close my database.

Let me put my concept into code :

```<code>public class DataModel
{
/*

Private members

*/

// Method to Select data from Student table
public ArrayList<String> FetchStudents (parameter 1)
{
private ArrayList<String> arrStudent;

DatabaseAdapter objDB= new DatabaseAdapter();
objDB.open();
/*
Some code
*/
objDB.close();

return arrStudent
}

//Method to delete record from Student table
public DeleteStudent(parameter 1)
{
DatabaseAdapter objDB= new DatabaseAdapter();
objDB.open();
//Some code
objDB.close();
}

/*

Rest of methods

*/
}
</code>```

//DatabaseAdapterClass

```<code>private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* onCreate method is called for the 1st time when database doesn't exists.
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
}
/**
* onUpgrade method is called when database version changes.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                        + newVersion);
}
}
</code>```

Question:

What I want to ask is this the correct approach of implementation? Is it fine if create separate class for database methods? What limitations or issues you guys think might trouble me later on? Also, is there a better way to implement the above concept?

Thanks

Stone

答:
What you are referring to as a 'model class' is more commonly known as a data access object (DAO). Your model would usually be a set of classes that hold your data and business logic. In you case, probably a Student class having an ID, name, GPA, etc. properties. If you want to separate data access from your model, you would have your data access class (DatabaseHelper) query the database and use the data it gets to return Student objects or a List<Student>. There is really not much point in separating the data access class from the database helper, it is better to have all of your database-related code in one place.

Using model classes (only), however, may not always be practical on Android, because it has native support for getting and displaying data from a Cursor (CursorAdapter, etc.). If you want to use any of that, you would have to expose your data not as model objects but as Cursor's. As for  content providers, have a look at those too, but if you don't need to expose your data to other applications, writing a ContentProvider might be overkill.

On another note, you don't want to be opening and closing the database on each query. It is actually safe to leave it open, it will be automatically closed when your app's process dies.

Body:
I was just starting to work on an database application when I realized I should implement MVC pattern as the application is quite complex and involves a number of database operations.

In regards to this, I have decided to create a separate model class for handling database operations. This class will have all methods which will return me the data after executing Sqlite command(Select for instance) OR will simply execute the SQLite command(Delete for instance). But what I want is to separate this class from Database Adapter class, where I open, create and close my database.

Let me put my concept into code :

public class DataModel
{
/*

Private members

*/

// Method to Select data from Student table
public ArrayList<String> FetchStudents (parameter 1)
{
private ArrayList<String> arrStudent;

DatabaseAdapter objDB= new DatabaseAdapter();
objDB.open();
/*
Some code
*/
objDB.close();

return arrStudent
}

//Method to delete record from Student table
public DeleteStudent(parameter 1)
{
DatabaseAdapter objDB= new DatabaseAdapter();
objDB.open();
//Some code
objDB.close();
}

/*

Rest of methods

*/
}

//DatabaseAdapterClass

private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* onCreate method is called for the 1st time when database doesn't exists.
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
}
/**
* onUpgrade method is called when database version changes.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                        + newVersion);
}
}

Question:

What I want to ask is this the correct approach of implementation? Is it fine if create separate class for database methods? What limitations or issues you guys think might trouble me later on? Also, is there a better way to implement the above concept?

Thanks

Stone


问:
SharedResource Localization and Simple Injector in asp.net core 2.1
I have an ASP.NET web api in ASP.NET core 2.1 and I have implemented a shared resource as explained here. This works fine.

The line :

```<code>services.AddLocalization()
</code>```

adds localization to the inbuilt IOC container. (I think this is where the magic happens at least)

Now I have added Simple Injector into the mix for my own classes and I have a class which I have registered as Async Scoped which gets injected with the shared resource (through IStringLocalizer). However, IStringLocalizer is scoped as transient and this is not compatible with Async Scoped (as this has a longer scope). I can obviously solve the problem by setting the option "SuppressLifestyleMismatchVerification" to true, but this doesn't smell right. (in this case it probably doesn't matter but by using this option I mask any other problems I may have) Is there anyway of fixing this problem? Can I change the scoping of the shared resource for example?

答:
Thank you @Steven the clear explanation.
I've written an extension method for localization, and confused with the lifestyle of IStringLocalizer.

```<code>public static class LocalizerExtensions
{
    private static IStringLocalizer<Localizer> _localizer =  default!;

    public static IServiceCollection AddLocalizer(this IServiceCollection services)
    {
        services.Configure<RequestLocalizationOptions>(options =>
        {
            string enUSCulture = "en";
            var supportedCultures = new[]
            {
                new CultureInfo(enUSCulture),
                new CultureInfo("vi"),
            };
            options.DefaultRequestCulture = new RequestCulture(enUSCulture, enUSCulture);
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
            options.RequestCultureProviders.Add(new CustomRequestCultureProvider(context =>
            {
                var lang = GetLang(context);
                return Task.FromResult(new ProviderCultureResult(lang, lang));
            }));
        });
        services.AddSingleton<ILocalizer, Localizer>();
        services.AddLocalization(options => options.ResourcesPath = "Resources");
        return services;
    }

    public static IApplicationBuilder UseLocalizer(this IApplicationBuilder app)
    {
        _localizer = app.ApplicationServices.GetRequiredService<IStringLocalizer<Localizer>>();
        app.UseRequestLocalization();
        return app;
    }

    public static string ToLocalizer(this string name)
    {
        return _localizer[name];
    }

    private static string GetLang(HttpContext context)
    {
        var lang = context.Request.Headers["Language"];
        if (string.IsNullOrWhiteSpace(lang))
        {
            lang = context.Request.Query["Language"];
        }
        if (string.IsNullOrWhiteSpace(lang))
        {
            lang = "vi";
        }
        return lang;
    }
}
</code>```

In method ToLocalizer, I used a static instance of IStringLocalizer<Localizer>, which means singleton lifestyle, and worried about using it correctly. With your explanation, I can use it without any worries

Body:
I have an ASP.NET web api in ASP.NET core 2.1 and I have implemented a shared resource as explained here. This works fine.

The line :

services.AddLocalization()

adds localization to the inbuilt IOC container. (I think this is where the magic happens at least)

Now I have added Simple Injector into the mix for my own classes and I have a class which I have registered as Async Scoped which gets injected with the shared resource (through IStringLocalizer). However, IStringLocalizer is scoped as transient and this is not compatible with Async Scoped (as this has a longer scope). I can obviously solve the problem by setting the option "SuppressLifestyleMismatchVerification" to true, but this doesn't smell right. (in this case it probably doesn't matter but by using this option I mask any other problems I may have) Is there anyway of fixing this problem? Can I change the scoping of the shared resource for example?

Body:
Thank you @Steven the clear explanation.
I've written an extension method for localization, and confused with the lifestyle of IStringLocalizer.

public static class LocalizerExtensions
{
    private static IStringLocalizer<Localizer> _localizer =  default!;

    public static IServiceCollection AddLocalizer(this IServiceCollection services)
    {
        services.Configure<RequestLocalizationOptions>(options =>
        {
            string enUSCulture = "en";
            var supportedCultures = new[]
            {
                new CultureInfo(enUSCulture),
                new CultureInfo("vi"),
            };
            options.DefaultRequestCulture = new RequestCulture(enUSCulture, enUSCulture);
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
            options.RequestCultureProviders.Add(new CustomRequestCultureProvider(context =>
            {
                var lang = GetLang(context);
                return Task.FromResult(new ProviderCultureResult(lang, lang));
            }));
        });
        services.AddSingleton<ILocalizer, Localizer>();
        services.AddLocalization(options => options.ResourcesPath = "Resources");
        return services;
    }

    public static IApplicationBuilder UseLocalizer(this IApplicationBuilder app)
    {
        _localizer = app.ApplicationServices.GetRequiredService<IStringLocalizer<Localizer>>();
        app.UseRequestLocalization();
        return app;
    }

    public static string ToLocalizer(this string name)
    {
        return _localizer[name];
    }

    private static string GetLang(HttpContext context)
    {
        var lang = context.Request.Headers["Language"];
        if (string.IsNullOrWhiteSpace(lang))
        {
            lang = context.Request.Query["Language"];
        }
        if (string.IsNullOrWhiteSpace(lang))
        {
            lang = "vi";
        }
        return lang;
    }
}

In method ToLocalizer, I used a static instance of IStringLocalizer<Localizer>, which means singleton lifestyle, and worried about using it correctly. With your explanation, I can use it without any worries


问:
ORACLE, ignore null to sum
I want to add two columns(number type) of a row, together but when one of those columns is null then the result is null. I handlled it by NVL function(NVL(col1,0) + NVL(col2,0)). But i want to return null when both are null(instead of 0).
how can i handle it?
Is there function in ORACLE that ignore null to sum two columns of a row?</p>
```<code>| col1 | col2  |                                     |
|:---- |:-----:|:-----------------------------------:|
|  1   |   2   |      --> result have to be : 3      |
|  1   |  null |     --> result have to be : 1       |
| null |  null |     --> result have to be : null    |
</code>```

答:
A CASE expression might be the easiest way to go here:

SELECT CASE WHEN col1 IS NULL AND col2 IS NULL
            THEN NULL
            ELSE NVL(col1, 0) + NVL(col2, 0) END AS output
FROM yourTable;
```

Title: ORACLE, ignore null to sum

Body:
I want to add two columns(number type) of a row, together but when one of those columns is null then the result is null. I handlled it by NVL function(NVL(col1,0) + NVL(col2,0)). But i want to return null when both are null(instead of 0).
how can i handle it?
Is there function in ORACLE that ignore null to sum two columns of a row?

| col1 | col2  |                                     |
|:---- |:-----:|:-----------------------------------:|
|  1   |   2   |      --> result have to be : 3      |
|  1   |  null |     --> result have to be : 1       |
| null |  null |     --> result have to be : null    |


问:
Section 'Global Slack Notifier Setting' not showing after installing "Slack Notification Plugin" in my configure section of Jenkins
My Jenkins Version is 2.190.1

I need to ask regarding the implementation of slack notifications in jenkins , although i have gone through many of the tutorials, but the problem is i have installed the plugin successfully when i go to configure Jenkins , Section of "Global Slack Notifier Setting" is missing although slack notification dropdown is shown in post-build section of the Job but not in configure where we used to add these two information

**Team Subdomain &
Integration Token **

i am only just able to see this section in Jenkins->Configure section

Thanks

答:
The solution proposed by @giturr14 is correct. For the sake of completeness, I want to add that,

The team sub-domain must be entered under "workspace"

The integration token must be entered via credential->Add, then select "secret text" and enter the token under secrets, give id and description.

Then select your secret and press "test connection".


问:
JMeter Error While Opening JMX Script: Character reference "&#x0" is an invalid XML character
I wrote a load test script for a company. But two days ago, I saved my changes and left the computer. After that, when I try to open the JMX script, I keep seeing this error on my terminal window: [Fatal Error] :4202:72: Character reference "&#x0" is an invalid XML character.

Please help me to solve this issue. I have no idea what to do. I can send you the JMX script if you want.

Tried with: JMeter 5.1.1 and 5.4.1

Full log at jmeter.log file:

```<code>2022-02-07 12:47:19,759 INFO o.a.j.s.SaveService: Loading file: /Users/admin/Desktop/MW ÖN YÜZ/frontend_PegasusLoadium2022.jmx
2022-02-07 12:47:19,837 WARN o.j.r.p.TestPlanAnalyzer: Cannot parse file: /Users/admin/Desktop/MW ÖN YÜZ/frontend_PegasusLoadium2022.jmx
org.xml.sax.SAXParseException: Character reference "&#x0" is an invalid XML character.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) ~[xercesImpl-2.12.0.jar:?]
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) ~[xercesImpl-2.12.0.jar:?]
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121) ~[?:1.8.0_311]
    at org.jmeterplugins.repository.plugins.TestPlanAnalyzer.getNodeListWithClassNames(TestPlanAnalyzer.java:106) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.plugins.TestPlanAnalyzer.analyze(TestPlanAnalyzer.java:36) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.plugins.PluginSuggester.analyzeTestPlan(PluginSuggester.java:51) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.plugins.PluginSuggester.findPluginsToInstall(PluginSuggester.java:44) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.plugins.PluginSuggester.checkAndSuggest(PluginSuggester.java:28) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.logging.LoggerAppender.append(LoggerAppender.java:33) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:464) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:448) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:431) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:406) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.AwaitCompletionReliabilityStrategy.log(AwaitCompletionReliabilityStrategy.java:63) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.Logger.logMessage(Logger.java:146) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.tryLogMessage(AbstractLogger.java:2170) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.logMessageTrackRecursion(AbstractLogger.java:2125) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.logMessageSafely(AbstractLogger.java:2108) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:2019) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:1890) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.slf4j.Log4jLogger.info(Log4jLogger.java:184) ~[log4j-slf4j-impl-2.11.1.jar:2.11.1]
    at org.apache.jmeter.save.SaveService.loadTree(SaveService.java:428) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.Load.loadProjectFile(Load.java:130) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.Load.loadProjectFile(Load.java:102) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.Load.doActionAfterCheck(Load.java:89) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.AbstractActionWithNoRunningTest.doAction(AbstractActionWithNoRunningTest.java:45) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:70) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) [?:1.8.0_311]
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) [?:1.8.0_311]
    at java.awt.EventQueue.access$500(EventQueue.java:97) [?:1.8.0_311]
    at java.awt.EventQueue$3.run(EventQueue.java:709) [?:1.8.0_311]
    at java.awt.EventQueue$3.run(EventQueue.java:703) [?:1.8.0_311]
    at java.security.AccessController.doPrivileged(Native Method) [?:1.8.0_311]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74) [?:1.8.0_311]
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) [?:1.8.0_311]
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) [?:1.8.0_311]
</code>```

答:
JMeter .jmx scripts are XML files

&#x0 is null character

As per Valid characters in XML article:

Note that the code point U+0000, assigned to the null control character, is the only character encoded in Unicode and ISO/IEC 10646 that is always invalid in any XML 1.0 and 1.1 document.

So the solution would be opening the .jmx script in a text/hex editor of your choice, look for all the occurrences of the null character and delete them.

There is a chance that the null character appeared because the .jmx script was saved using one encoding and you're trying to open it in another encoding so you could try playing with the file.encoding system property by trying to pass various possible encodings via -D command-line argument or putting them to system.properties file but this chance is quite minimal.

Body:
I wrote a load test script for a company. But two days ago, I saved my changes and left the computer. After that, when I try to open the JMX script, I keep seeing this error on my terminal window: [Fatal Error] :4202:72: Character reference "&#x0" is an invalid XML character.

Please help me to solve this issue. I have no idea what to do. I can send you the JMX script if you want.

Tried with: JMeter 5.1.1 and 5.4.1

Full log at jmeter.log file:

2022-02-07 12:47:19,759 INFO o.a.j.s.SaveService: Loading file: /Users/admin/Desktop/MW ÖN YÜZ/frontend_PegasusLoadium2022.jmx
2022-02-07 12:47:19,837 WARN o.j.r.p.TestPlanAnalyzer: Cannot parse file: /Users/admin/Desktop/MW ÖN YÜZ/frontend_PegasusLoadium2022.jmx
org.xml.sax.SAXParseException: Character reference "&#x0" is an invalid XML character.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) ~[xercesImpl-2.12.0.jar:?]
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) ~[xercesImpl-2.12.0.jar:?]
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121) ~[?:1.8.0_311]
    at org.jmeterplugins.repository.plugins.TestPlanAnalyzer.getNodeListWithClassNames(TestPlanAnalyzer.java:106) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.plugins.TestPlanAnalyzer.analyze(TestPlanAnalyzer.java:36) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.plugins.PluginSuggester.analyzeTestPlan(PluginSuggester.java:51) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.plugins.PluginSuggester.findPluginsToInstall(PluginSuggester.java:44) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.plugins.PluginSuggester.checkAndSuggest(PluginSuggester.java:28) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.jmeterplugins.repository.logging.LoggerAppender.append(LoggerAppender.java:33) ~[jmeter-plugins-manager-1.6.jar:?]
    at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:464) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:448) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:431) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:406) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.config.AwaitCompletionReliabilityStrategy.log(AwaitCompletionReliabilityStrategy.java:63) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.core.Logger.logMessage(Logger.java:146) ~[log4j-core-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.tryLogMessage(AbstractLogger.java:2170) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.logMessageTrackRecursion(AbstractLogger.java:2125) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.logMessageSafely(AbstractLogger.java:2108) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:2019) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:1890) ~[log4j-api-2.11.1.jar:2.11.1]
    at org.apache.logging.slf4j.Log4jLogger.info(Log4jLogger.java:184) ~[log4j-slf4j-impl-2.11.1.jar:2.11.1]
    at org.apache.jmeter.save.SaveService.loadTree(SaveService.java:428) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.Load.loadProjectFile(Load.java:130) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.Load.loadProjectFile(Load.java:102) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.Load.doActionAfterCheck(Load.java:89) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.AbstractActionWithNoRunningTest.doAction(AbstractActionWithNoRunningTest.java:45) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:70) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) [?:1.8.0_311]
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) [?:1.8.0_311]
    at java.awt.EventQueue.access$500(EventQueue.java:97) [?:1.8.0_311]
    at java.awt.EventQueue$3.run(EventQueue.java:709) [?:1.8.0_311]
    at java.awt.EventQueue$3.run(EventQueue.java:703) [?:1.8.0_311]
    at java.security.AccessController.doPrivileged(Native Method) [?:1.8.0_311]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74) [?:1.8.0_311]
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) [?:1.8.0_311]
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) [?:1.8.0_311]
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) [?:1.8.0_311]


问:
boolean addition method seems to not work
When trying to print the result of copy() and add() the system prints 0s.
It works when deleting the m1 of m1.matrixArray[i][j] in both add() and copy().
But if deleting it seems to have conflict with the purpose of creating the instance as it is not being used.

Any idea on how to print the value?

```<code>public interface MatrixInterface {
    void makeEmpty(int m);
    boolean storeValue(int i, int j, int value);

    boolean add(MatrixInterface anotherMatrix);
    boolean copy(MatrixInterface anotherMatrix);
}

public class Matrix implements MatrixInterface{
    private int [][] matrixArray;
    private int dimension;

    public Matrix(int n){
        this.matrixArray = new int[n][n];
        this.dimension = n;
    }

    @Override
    public void makeEmpty(int m) {
        //check dimension - conditional statement
        if(m > dimension){
            m = dimension;
        }
        for(int i=0; i<m; i++){
            for(int j=0; j<m; j++){
                matrixArray[i][j]=0;
            }
        }
    }

    @Override
    public boolean storeValue(int i, int j, int value) {
        if(i>=1 && i<= dimension && j>=1 && j<=dimension){
            matrixArray[i-1][j-1] = value;
        }
        return true;
    }

    @Override
    public boolean add(MatrixInterface anotherMatrix) {
        Matrix m1 = new Matrix(((Matrix) anotherMatrix).dimension);
        if(((Matrix) anotherMatrix).dimension == dimension){
            for (int i = 0; i < dimension; i++) {
                for (int j = 0; j < dimension; j++) {
                    m1.matrixArray[i][j] =
                        matrixArray[i][j] + ((Matrix) anotherMatrix).matrixArray[i][j];
                }
            }
        }
        return true;
    }

    @Override
    public boolean copy(MatrixInterface anotherMatrix) {
        Matrix m1 = new Matrix(((Matrix) anotherMatrix).dimension);
        if(((Matrix) anotherMatrix).dimension == dimension){
        for(int i=0; i<dimension; i++){
            for(int j=0; j<dimension; j++){
                m1.matrixArray[i][j] =
                        ((Matrix) anotherMatrix).matrixArray[i][j];
            }
        }
        }
        return true;
    }

    @Override
    public String toString() {
        String outputStr = "";
        for(int i=0; i<dimension; ++i){
            for(int j=0; j<dimension; ++j){
                outputStr += String.format("%4d", matrixArray[i][j]);
            }
            outputStr += "\n";
        }

        return outputStr;
    }

}
</code>```

Test class.

```<code>public class MatrixTest {

    public static void main(String[] args) {
        MatrixInterface matrix1 = new Matrix(2);
        MatrixInterface matrix2 = new Matrix(2);
        matrix1.makeEmpty(2);
        System.out.println(matrix1.toString());
        matrix1.storeValue(1,1,1);
        matrix1.storeValue(1,2,2);
        matrix1.storeValue(2,2,3);
        System.out.println(matrix1.toString());

        matrix2.add(matrix1);
        System.out.println(matrix2.toString());
        System.out.println(matrix2.add(matrix1));

        matrix2.copy(matrix1);
        System.out.println(matrix2.toString());
        System.out.println(matrix2.copy(matrix1));

    }

}
</code>```

答:
You are adding and copying to a new Matrix. Hence the original Matrix this does not change. A Monday morning error.

Missing is the completeness of the interface:

```<code>public interface MatrixInterface {
    int getDimension();
    int retrieveValue(int i, int j);

public class Matrix implements MatrixInterface{
    @Override
    public int getDimension() {
        return dimension;
    }
</code>```

A correct add then could be:

```<code>@Override
public boolean add(MatrixInterface anotherMatrix) {
    // Could do a partial add with:
    // int m = Math.min(dimension, anotherMatrix.getDimension());
    if (dimension != anotherMatrix.getDimension()) {
        return false; // Or:
        // throw IllegalArgumentException("Bounds not equal: "
        //     + dimension + " and " + anotherMatrix.getDimension());
    }
    for (int i = 1; i <= dimension; i++) {
        for (int j = 1; j <= dimension; j++) {
             storeValue(i, j, anotherMatrix.retrieveValue(i, j));
        }
    }
    return true;
}
</code>```

As you see, purely using the interface will make this method work with other implementations. There are diagonal matrices, where you might save many space, say a 100x100 matrix does not cost 10_000 but 5_050 ints. Or a sparse matrics where you might only store non-zero elements with their indices.

In fact as add does not use its class (when replacing dimension with getDimension()), just the interface you could move it to the interface as default boolean add(MatrixInterface anotherMatrix) { ... } - if you already treated default methods in interfaces.

Body:
When trying to print the result of copy() and add() the system prints 0s.
It works when deleting the m1 of m1.matrixArray[i][j] in both add() and copy().
But if deleting it seems to have conflict with the purpose of creating the instance as it is not being used.

Any idea on how to print the value?

public interface MatrixInterface {
    void makeEmpty(int m);
    boolean storeValue(int i, int j, int value);

    boolean add(MatrixInterface anotherMatrix);
    boolean copy(MatrixInterface anotherMatrix);
}

public class Matrix implements MatrixInterface{
    private int [][] matrixArray;
    private int dimension;

    public Matrix(int n){
        this.matrixArray = new int[n][n];
        this.dimension = n;
    }

    @Override
    public void makeEmpty(int m) {
        //check dimension - conditional statement
        if(m > dimension){
            m = dimension;
        }
        for(int i=0; i<m; i++){
            for(int j=0; j<m; j++){
                matrixArray[i][j]=0;
            }
        }
    }

    @Override
    public boolean storeValue(int i, int j, int value) {
        if(i>=1 && i<= dimension && j>=1 && j<=dimension){
            matrixArray[i-1][j-1] = value;
        }
        return true;
    }

    @Override
    public boolean add(MatrixInterface anotherMatrix) {
        Matrix m1 = new Matrix(((Matrix) anotherMatrix).dimension);
        if(((Matrix) anotherMatrix).dimension == dimension){
            for (int i = 0; i < dimension; i++) {
                for (int j = 0; j < dimension; j++) {
                    m1.matrixArray[i][j] =
                        matrixArray[i][j] + ((Matrix) anotherMatrix).matrixArray[i][j];
                }
            }
        }
        return true;
    }

    @Override
    public boolean copy(MatrixInterface anotherMatrix) {
        Matrix m1 = new Matrix(((Matrix) anotherMatrix).dimension);
        if(((Matrix) anotherMatrix).dimension == dimension){
        for(int i=0; i<dimension; i++){
            for(int j=0; j<dimension; j++){
                m1.matrixArray[i][j] =
                        ((Matrix) anotherMatrix).matrixArray[i][j];
            }
        }
        }
        return true;
    }

    @Override
    public String toString() {
        String outputStr = "";
        for(int i=0; i<dimension; ++i){
            for(int j=0; j<dimension; ++j){
                outputStr += String.format("%4d", matrixArray[i][j]);
            }
            outputStr += "\n";
        }

        return outputStr;
    }

}

Test class.

public class MatrixTest {

    public static void main(String[] args) {
        MatrixInterface matrix1 = new Matrix(2);
        MatrixInterface matrix2 = new Matrix(2);
        matrix1.makeEmpty(2);
        System.out.println(matrix1.toString());
        matrix1.storeValue(1,1,1);
        matrix1.storeValue(1,2,2);
        matrix1.storeValue(2,2,3);
        System.out.println(matrix1.toString());

        matrix2.add(matrix1);
        System.out.println(matrix2.toString());
        System.out.println(matrix2.add(matrix1));

        matrix2.copy(matrix1);
        System.out.println(matrix2.toString());
        System.out.println(matrix2.copy(matrix1));

    }

}

Body:
You are adding and copying to a new Matrix. Hence the original Matrix this does not change. A Monday morning error.

Missing is the completeness of the interface:

public interface MatrixInterface {
    int getDimension();
    int retrieveValue(int i, int j);

public class Matrix implements MatrixInterface{
    @Override
    public int getDimension() {
        return dimension;
    }

A correct add then could be:

@Override
public boolean add(MatrixInterface anotherMatrix) {
    // Could do a partial add with:
    // int m = Math.min(dimension, anotherMatrix.getDimension());
    if (dimension != anotherMatrix.getDimension()) {
        return false; // Or:
        // throw IllegalArgumentException("Bounds not equal: "
        //     + dimension + " and " + anotherMatrix.getDimension());
    }
    for (int i = 1; i <= dimension; i++) {
        for (int j = 1; j <= dimension; j++) {
             storeValue(i, j, anotherMatrix.retrieveValue(i, j));
        }
    }
    return true;
}

As you see, purely using the interface will make this method work with other implementations. There are diagonal matrices, where you might save many space, say a 100x100 matrix does not cost 10_000 but 5_050 ints. Or a sparse matrics where you might only store non-zero elements with their indices.

In fact as add does not use its class (when replacing dimension with getDimension()), just the interface you could move it to the interface as default boolean add(MatrixInterface anotherMatrix) { ... } - if you already treated default methods in interfaces.


问:
"Module not found, required by" when implementing maven library via gradle using javafx?
I am using gradle 7.3.1 in Intellij 2021.3 to build a JavaFX application. And I need external libraries dependency for the backend part.

This is the complete build.gradle script that is pre-built by the idea:

```<code>plugins {
    id 'java'
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.10'
    id 'org.beryx.jlink' version '2.24.1'
}

group 'com.github.zukarusan'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

ext {
    junitVersion = '5.8.1'
}

sourceCompatibility = '11'
targetCompatibility = '11'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

application {
    mainModule = 'com.github.zukarusan.app'
    mainClass = 'com.github.zukarusan.app.MainApplication'
}

javafx {
    version = '11.0.2'
    modules = ['javafx.controls', 'javafx.fxml']
}

dependencies {
    implementation('org.controlsfx:controlsfx:11.1.0')
    implementation('com.dlsc.formsfx:formsfx-core:11.3.2') {
        exclude(group: 'org.openjfx')
    }
    implementation('org.kordamp.ikonli:ikonli-javafx:12.2.0')
    implementation('org.kordamp.bootstrapfx:bootstrapfx-core:0.4.0')

    implementation('com.github.wendykierp:JTransforms:3.1') // THIS IS THE EXTERNAL LIBRARY I ADDED

    testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
}

test {
    useJUnitPlatform()
}

jlink {
    imageZip = project.file("${buildDir}/distributions/app-${javafx.platform.classifier}.zip")
    options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages']
    launcher {
        name = 'app'
    }
}

jlinkZip {
    group = 'distribution'
}
</code>```

and then I updated module-info.java:

```<code>module com.github.zukarusan.app {
    requires javafx.controls;
    requires javafx.fxml;
    requires org.controlsfx.controls;
    requires com.dlsc.formsfx;
    requires org.kordamp.ikonli.javafx;
    requires org.kordamp.bootstrapfx.core;
    requires java.desktop;

    requires JTransforms; // UPDATED

    exports com.github.zukarusan.app.controller;
    exports com.github.zukarusan.app.model;
    exports com.github.zukarusan.app;
    opens com.github.zukarusan.app.controller to javafx.fxml;
}
</code>```

Before I updated the module-info
, the application launches just fine and shows a javafx window application.
But, after I updated that, java.lang.FindException is thrown. resulting the following error:

```<code>> Task :MainApplication.main() FAILED
Error occurred during initialization of boot layer
java.lang.module.FindException: Module JTransforms not found, required by com.github.zukarusan.app
</code>```

Do I have to download manually the modules? or any steps that I miss?

 Please enlighten me. :'(

答:
Guided by @jewelsea in the comment, I have finally resolved this issue.

After several days, I figured out that my imported libraries in modular java project are treated as an unnamed module (correct me if I am wrong). As I understood so far, libraries like JTransforms may belong to traditional libraries that do not cover the modularity feature like in Java 9. This means that the jar library does not have Automatic-Module-Name at the very least in its manifest metadata. See the gradle documentation.

That is to say, I will have another approach using a grade plugin extra-java-module-info and found a somewhat similar case in this post.

Ultimately, I add the following script in build.gradle

```<code>plugins {
    ... // other plugins

    id 'de.jjohannes.extra-java-module-info' version '0.11'
}

extraJavaModuleInfo {
    module("JTransforms-3.1.jar", "JTransforms", "3.1") {
        exports("org.jtransforms")
    }
}
</code>```

Then hit that sync button. That's all!

Cheers! Thanks again to @jewelsea.

Body:
I am using gradle 7.3.1 in Intellij 2021.3 to build a JavaFX application. And I need external libraries dependency for the backend part.

This is the complete build.gradle script that is pre-built by the idea:

plugins {
    id 'java'
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.10'
    id 'org.beryx.jlink' version '2.24.1'
}

group 'com.github.zukarusan'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

ext {
    junitVersion = '5.8.1'
}

sourceCompatibility = '11'
targetCompatibility = '11'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

application {
    mainModule = 'com.github.zukarusan.app'
    mainClass = 'com.github.zukarusan.app.MainApplication'
}

javafx {
    version = '11.0.2'
    modules = ['javafx.controls', 'javafx.fxml']
}

dependencies {
    implementation('org.controlsfx:controlsfx:11.1.0')
    implementation('com.dlsc.formsfx:formsfx-core:11.3.2') {
        exclude(group: 'org.openjfx')
    }
    implementation('org.kordamp.ikonli:ikonli-javafx:12.2.0')
    implementation('org.kordamp.bootstrapfx:bootstrapfx-core:0.4.0')

    implementation('com.github.wendykierp:JTransforms:3.1') // THIS IS THE EXTERNAL LIBRARY I ADDED

    testImplementation("org.junit.jupiter:junit-jupiter-api:${junitVersion}")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:${junitVersion}")
}

test {
    useJUnitPlatform()
}

jlink {
    imageZip = project.file("${buildDir}/distributions/app-${javafx.platform.classifier}.zip")
    options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages']
    launcher {
        name = 'app'
    }
}

jlinkZip {
    group = 'distribution'
}

and then I updated module-info.java:

module com.github.zukarusan.app {
    requires javafx.controls;
    requires javafx.fxml;
    requires org.controlsfx.controls;
    requires com.dlsc.formsfx;
    requires org.kordamp.ikonli.javafx;
    requires org.kordamp.bootstrapfx.core;
    requires java.desktop;

    requires JTransforms; // UPDATED

    exports com.github.zukarusan.app.controller;
    exports com.github.zukarusan.app.model;
    exports com.github.zukarusan.app;
    opens com.github.zukarusan.app.controller to javafx.fxml;
}

Before I updated the module-info
, the application launches just fine and shows a javafx window application.
But, after I updated that, java.lang.FindException is thrown. resulting the following error:

> Task :MainApplication.main() FAILED
Error occurred during initialization of boot layer
java.lang.module.FindException: Module JTransforms not found, required by com.github.zukarusan.app

Do I have to download manually the modules? or any steps that I miss?

 Please enlighten me. :'(

Body:
Guided by @jewelsea in the comment, I have finally resolved this issue.

After several days, I figured out that my imported libraries in modular java project are treated as an unnamed module (correct me if I am wrong). As I understood so far, libraries like JTransforms may belong to traditional libraries that do not cover the modularity feature like in Java 9. This means that the jar library does not have Automatic-Module-Name at the very least in its manifest metadata. See the gradle documentation.

That is to say, I will have another approach using a grade plugin extra-java-module-info and found a somewhat similar case in this post.

Ultimately, I add the following script in build.gradle

plugins {
    ... // other plugins

    id 'de.jjohannes.extra-java-module-info' version '0.11'
}

extraJavaModuleInfo {
    module("JTransforms-3.1.jar", "JTransforms", "3.1") {
        exports("org.jtransforms")
    }
}

Then hit that sync button. That's all!

Cheers! Thanks again to @jewelsea.


问:
Good way on creating C# validation class
I have a functionality that upload a file, validate it, save it to database and so on.

All of these actions are on some different classes and methods. But, if something goes wrong in any of these methods, I want to inform these errors to my front-end.

Is there a good way to manage this, let's call, "Error Class"?

Thanks!

答:
One approach that you could take would be to create the "Error Class" like a service in your application and post the different classes and methods that perform various actions could post errors to it.

Now your front-end can either subscribe with the "Error Class" to know of errors immediately or you could return an error code the details of which can be found using the "Error Class"


问:
How to write a python function to return True when there's even number of 0 in a integer and return False otherwise using recursion?
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?</p>
```<code>def valid(n):
    number = str(n)
    position = number.find("0")

    if "0" not in number:
        return 0

    return 1 + valid(number[(position+1):])

print(valid(12340006))

</code>```

答:
I believe the problem is the 0 returned from the if "0" not in number condition. You can try this way:

```<code>def valid(n):

    zeros = str(n).count("0")

    if zeros == 0:
        return False
    else:
        return zeros % 2 == 0
</code>```

Which should work.

Body:
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?

def valid(n):
    number = str(n)
    position = number.find("0")

    if "0" not in number:
        return 0

    return 1 + valid(number[(position+1):])

print(valid(12340006))

Body:
I believe the problem is the 0 returned from the if "0" not in number condition. You can try this way:

def valid(n):

    zeros = str(n).count("0")

    if zeros == 0:
        return False
    else:
        return zeros % 2 == 0

Which should work.


问:
How to scroll table row by row at button click jQuery
I have table with fixed heihgt, and scrollable body, i add the button for scroling row one by one.

Ideas is to scroll row by row by user clicking.

For now i create func for scroll down, but it's not good for me, some how i need to create func to scroll table on click one row down.

```<code>$('#more-arrows').click(function () {
    var scrollBottom = Math.max($('.table-udt').height() - $('tbody').height() / 200 + 1000, 0);
    $('tbody').scrollTop(scrollBottom).animate({
        scrollBottom: 0
    }, 1000);
});
</code>```

JsFiddle

So i want to scroll on #more-arrows click, row one by one scrolle to the bottom.

答:
You can do this by figuring out the position of the row and then moving to it using scrollTop. Here is a snipped to get you started:

let i = 0
$('#more-arrows').click(function(e) {
  if (i < $(`.scrollTable tr`).length) {
    let position = $(`.scrollTable tr:eq(${i})`).offset().top;
    $('.scroll').animate({
      scrollTop: $('.scroll').scrollTop() + position
    }, 300);
    i++
  } else {
    i = 0
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
    margin: 0 1rem;
    background: #fff;
    width: 98%;
    border-spacing: 0 5px;
    border-collapse: separate;
    border-radius: .25rem;
}

thead tr:first-child {
    background: #E84C3D;
    color: #fff;
    border: none;
}

th:first-child,
td:first-child {
    padding: 0 15px 0 20px;
}

tr {
    width: 100%;
    height: 40px;
}

th {
    font-size: 20px;
    border-collapse: separate;
    border-spacing: 5em;
    font-weight: 500;
}

thead tr:last-child th {
    border-bottom: 3px solid #ddd;
}

tbody tr:hover {
    background-color: #f2f2f2;
    cursor: default;
}

tbody tr:last-child td {
    border: none;
}

tbody td {
    border-bottom: 1px solid #ddd;
}

td:last-child {
    text-align: right;
    padding-right: 10px;
}

.scroll {
  max-height: 360px;
  overflow: auto;
}</code>```

      Text1 Text
      Text1 Text
      Text1 Text
      Text1 Text

      Text2 Text
      Text2 Text
      Text2 Text
      Text2 Text

      Text3 Text
      Text3 Text
      Text3 Text
      Text3 Text

      Text4 Text
      Text4 Text
      Text4 Text
      Text4 Text

      Text Text
      Text Text
      Text Text
      Text Text

      Text Text
      Text Text
      Text Text
      Text Text

      More Text
      More Text
      More Text
      More Text

      Text Text
      Text Text
      Text Text
      Text Text

      Text Text
      Text Text
      Text Text
      Text Text

      Text Text
      Text Text
      Text Text
      Text Text

      Text Text
      Text Text
      Text Text
      Text Text

      Text Text
      Text Text
      Text Text
      Text Text

      Text Text
      Text Text
      Text Text
      Text Text

      Text Text
      Text Text
      Text Text
      Text Text

      More Text
      More Text
      More Text
      More Text

      Text Text
      Text Text
      Text Text
      Text Text

      Even More Text Text
      Even More Text Text
      Even More Text Text
      Even More Text Text

  <svg id="more-arrows">
    <polygon class="arrow-top" points="37.6,27.9 1.8,1.3 3.3,0 37.6,25.3 71.9,0 73.7,1.3 " />
    <polygon class="arrow-middle" points="37.6,45.8 0.8,18.7 4.4,16.4 37.6,41.2 71.2,16.4 74.5,18.7 " />
    <polygon class="arrow-bottom" points="37.6,64 0,36.1 5.1,32.8 37.6,56.8 70.4,32.8 75.5,36.1 " />
  </svg>

```

Body:
I have table with fixed heihgt, and scrollable body, i add the button for scroling row one by one.

Ideas is to scroll row by row by user clicking.

For now i create func for scroll down, but it's not good for me, some how i need to create func to scroll table on click one row down.

$('#more-arrows').click(function () {
    var scrollBottom = Math.max($('.table-udt').height() - $('tbody').height() / 200 + 1000, 0);
    $('tbody').scrollTop(scrollBottom).animate({
        scrollBottom: 0
    }, 1000);
});

JsFiddle

So i want to scroll on #more-arrows click, row one by one scrolle to the bottom.

Body:
You can do this by figuring out the position of the row and then moving to it using scrollTop. Here is a snipped to get you started:

let i = 0
$('#more-arrows').click(function(e) {
  if (i < $(`.scrollTable tr`).length) {
    let position = $(`.scrollTable tr:eq(${i})`).offset().top;
    $('.scroll').animate({
      scrollTop: $('.scroll').scrollTop() + position
    }, 300);
    i++
  } else {
    i = 0
  }
});

table {
    margin: 0 1rem;
    background: #fff;
    width: 98%;
    border-spacing: 0 5px;
    border-collapse: separate;
    border-radius: .25rem;
}

thead tr:first-child {
    background: #E84C3D;
    color: #fff;
    border: none;
}

th:first-child,
td:first-child {
    padding: 0 15px 0 20px;
}

tr {
    width: 100%;
    height: 40px;
}

th {
    font-size: 20px;
    border-collapse: separate;
    border-spacing: 5em;
    font-weight: 500;
}

thead tr:last-child th {
    border-bottom: 3px solid #ddd;
}

tbody tr:hover {
    background-color: #f2f2f2;
    cursor: default;
}

tbody tr:last-child td {
    border: none;
}

tbody td {
    border-bottom: 1px solid #ddd;
}

td:last-child {
    text-align: right;
    padding-right: 10px;
}

.scroll {
  max-height: 360px;
  overflow: auto;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scroll">
  <table class="scrollTable">
    <tr>
      <td>Text1 Text</td>
      <td>Text1 Text</td>
      <td>Text1 Text</td>
      <td>Text1 Text</td>
    </tr>
    <tr>
      <td>Text2 Text</td>
      <td>Text2 Text</td>
      <td>Text2 Text</td>
      <td>Text2 Text</td>
    </tr>
    <tr>
      <td>Text3 Text</td>
      <td>Text3 Text</td>
      <td>Text3 Text</td>
      <td>Text3 Text</td>
    </tr>
    <tr>
      <td>Text4 Text</td>
      <td>Text4 Text</td>
      <td>Text4 Text</td>
      <td>Text4 Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>More Text</td>
      <td>More Text</td>
      <td>More Text</td>
      <td>More Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>More Text</td>
      <td>More Text</td>
      <td>More Text</td>
      <td>More Text</td>
    </tr>
    <tr>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
      <td>Text Text</td>
    </tr>
    <tr>
      <td>Even More Text Text</td>
      <td>Even More Text Text</td>
      <td>Even More Text Text</td>
      <td>Even More Text Text</td>
    </tr>
  </table>
</div>

<div class="down-row">
  <svg id="more-arrows">
    <polygon class="arrow-top" points="37.6,27.9 1.8,1.3 3.3,0 37.6,25.3 71.9,0 73.7,1.3 " />
    <polygon class="arrow-middle" points="37.6,45.8 0.8,18.7 4.4,16.4 37.6,41.2 71.2,16.4 74.5,18.7 " />
    <polygon class="arrow-bottom" points="37.6,64 0,36.1 5.1,32.8 37.6,56.8 70.4,32.8 75.5,36.1 " />
  </svg>
</div>


答:
We can note that

[recursion base] Single zero is invalid, other single digit is valid

[recursion step] When we see non-zero digit, nothing should change (check for remaining part should give same result). When we see zero, we should invert the result (if it was odd count before, now it's even, and vice versa).

def is_valid(num):
    n, r = divmod(num, 10)
    if n == 0:
        return r != 0
    return is_valid(n) ^ (r == 0)
```

Title: How to write a python function to return True when there's even number of 0 in a integer and return False otherwise using recursion?