问:
How to enable PodNodeSelector admission controller in EKS version 1.15
Can somebody point in the direction on how to enable PodNodeSelector admission controller in EKS version 1.15 ?

I'm trying to achieve what is explained in this link, but how to do this in Managed Kubernetes like EKS where you don't have access to control plane components.

答:
In fact: You cannot enable PodNodeSelector in EKS.

The fact that EKS is a Managed Kubernetes solution denies any reconfiguration of control plane components. That's why you cannot enable PodNodeSelector.

There is an official documentation about enabled admission controllers in EKS: Aws.amazon.com: EKS: Userguide: Platform-versions

There is ongoing feature request for PodNodeSelector here (as well as some workarounds): Github.com: AWS: Issue: 304.

There is an answer on StackOverflow with similar question How to enable admission controllers in EKS


来源: stackexchange

问:
Setting a custom loss for sklearn gradient boosting classfier
Sklearn gradient boosting classifier accepts deviance and exponential loss, as detailed here and here. But, can we pass a custom loss instead of its predefined loss ('deviance' or 'exponential' loss).

Similar questions on stackoverflow and why they are not answering my question:

I already found this question, which looks most relevant. But it does not cover my question at all, since it does not discuss how could one pass the custom loss to GradientBoostingClassifier.

Also this question looks relevant, but the answer does not explain once you define a class (as described in the answer), how do you pass this as an argument to the GradientBoostingClassifier.

答:
To do so, you should create a subclass of "BaseGradientBoosting" and a subclass of both the first subclass and GradientBoostingClassifier (in the classification case) classes. Inside first class you should pass the name of the custom loss function in the super().__init__, and inside the second subclass you can pass the name of your custom loss function as a _SUPPORTED_LOSS.

Besides, to turn off the ValueError of _check_params in SKlearn gradient boosting, you have to override this function, or consider an exception for this function.

For example:

```<code>class my_base_gradient_boost(BaseGradientBoosting, metaclass=ABCMeta):
    @abstractmethod
    def __init__(self, *args):
       super().__init__(loss='my_custom_loss', *other_args)

    def _check_params(self):
      try:
        super()._check_params()
      except ValueError as e:
        if str(e) == "Loss 'my_costum_loss' not supported. ":
            self.loss_ = self.my_costum_loss
        else:
            raise

class my_classifier(my_base_gradient_boost, GradientBoostingClassifier):

    _SUPPORTED_LOSS = ('my_costum_loss')

    @_deprecate_positional_args
    def __init__(self, *args):
        super().__init__(*args)
</code>```

Please keep in mind that *args are all the arguments of BaseGradientBoosting.

Well, that's a lot of work, but I could not find any better solution to do so. I hope this helps.

P.S. by the way, you are right, the mentioned links don't answer your question.

ContentLicense: CC BY-SA 4.0

Body:
To do so, you should create a subclass of "BaseGradientBoosting" and a subclass of both the first subclass and GradientBoostingClassifier (in the classification case) classes. Inside first class you should pass the name of the custom loss function in the super().__init__, and inside the second subclass you can pass the name of your custom loss function as a _SUPPORTED_LOSS.

Besides, to turn off the ValueError of _check_params in SKlearn gradient boosting, you have to override this function, or consider an exception for this function.

For example:

class my_base_gradient_boost(BaseGradientBoosting, metaclass=ABCMeta):
    @abstractmethod
    def __init__(self, *args):
       super().__init__(loss='my_custom_loss', *other_args)

    def _check_params(self):
      try:
        super()._check_params()
      except ValueError as e:
        if str(e) == "Loss 'my_costum_loss' not supported. ":
            self.loss_ = self.my_costum_loss
        else:
            raise

class my_classifier(my_base_gradient_boost, GradientBoostingClassifier):

    _SUPPORTED_LOSS = ('my_costum_loss')

    @_deprecate_positional_args
    def __init__(self, *args):
        super().__init__(*args)

Please keep in mind that *args are all the arguments of BaseGradientBoosting.

Well, that's a lot of work, but I could not find any better solution to do so. I hope this helps.

P.S. by the way, you are right, the mentioned links don't answer your question.


问:
Apache Jmeter - Selenium test with Firefox headless mode
I would like to run my test script in Apache Jmeter with Firefox Driver Config but I couldn't set up the headless mode and the setAcceptInsecureCerts(true).

I execute the Jmeter with the following command from CLI:

```<code>jmeter -Dwebdriver.gecko.driver="c:\DEVTOOLS\PERFORMANCE_TEST\FIREFOX_GECKO_DRIVER\geckodriver.exe"
</code>```

Unfortunately, the test target site does not use valid or secure certification at the moment,
so I need to set up to accept insecure cert somehow.

Here is my code snippet:

var pkg = JavaImporter(org.openqa.selenium, org.openqa.selenium.support.ui,org.openqa.selenium.firefox.FirefoxOptions)

var wait = new pkg.WebDriverWait(WDS.browser, 20)

pkg.FirefoxOptions.setAcceptInsecureCerts(true)```
</div>
</div>
</p>

```**I got the following error:**
2020-06-02 13:27:59,024 ERROR c.g.j.p.w.s.WebDriverSampler: TypeError: pkg.FirefoxOptions.setAcceptInsecureCerts is not a function in <eval> at line number 4
```

I don't know how is it possible to add the headless argument and AcceptInsecureCerts(true)
to Jmeter code.

Thank you for your help!

答:
Unfortunately this is not something you can control using WebDriver Sampler, the options are in:

Patch FirefoxDriverConfig.java code where FirefoxDriver initialization happens and replace the WebDriver Sampler plugin under "lib/ext" folder of your JMeter installation with your own version

Switch to the JSR223 Sampler where you can instantiate your own FirefoxDriver with whatever capabilities/preferences/command-line arguments you want

If you're not able or not willing to go for the above options you can set acceptInsecureCerts preference using Firefox Driver Config element:

and if your system doesn't have GUI you can use i.e. Xvfb to act as a virtual display like it's described in Headless Execution of Selenium Tests in Jenkins article

Body:
I would like to run my test script in Apache Jmeter with Firefox Driver Config but I couldn't set up the headless mode and the setAcceptInsecureCerts(true).

I execute the Jmeter with the following command from CLI:

jmeter -Dwebdriver.gecko.driver="c:\DEVTOOLS\PERFORMANCE_TEST\FIREFOX_GECKO_DRIVER\geckodriver.exe"

Unfortunately, the test target site does not use valid or secure certification at the moment,
so I need to set up to accept insecure cert somehow.

Here is my code snippet:

var pkg = JavaImporter(org.openqa.selenium, org.openqa.selenium.support.ui,org.openqa.selenium.firefox.FirefoxOptions)

var wait = new pkg.WebDriverWait(WDS.browser, 20)

pkg.FirefoxOptions.setAcceptInsecureCerts(true)

**I got the following error:**
2020-06-02 13:27:59,024 ERROR c.g.j.p.w.s.WebDriverSampler: TypeError: pkg.FirefoxOptions.setAcceptInsecureCerts is not a function in <eval> at line number 4

I don't know how is it possible to add the headless argument and AcceptInsecureCerts(true)
to Jmeter code.

Thank you for your help!


问:
function calling issue in python Rock Paper Scissors project
im fairly new to programing...
im working on a rock paper scissors game and everything works up until i need to show where player wins, or computer opponent wins, or if there is a tie.  The program just keeps asking for input to choose a weapon.
if anyone can show me why the wining or tie functions arent getting called id be very thankful
heres my code:</p>

```<code># Rock Paper Scissors game
import random

# player chooses between Rock Paper or Scissors
def player_move():
    global player_name
    shoot = input('{} Choose Rock, Paper or Scissors: '.format(player_name))
    while shoot[0].lower() != 'r' and shoot[0].lower() != 'p' and shoot[0].lower() != 's':
        print('sorry you must only choose r, p, or s')
        shoot = input('Try again: ')
    if shoot[0].lower() == 'r':
        shoot = 'Rock'
    if shoot[0].lower() == 'p':
        shoot = 'Paper'
    if shoot[0].lower() == 's':
        shoot = 'Scissors'
    print('your move <{}>'.format(shoot))
    return shoot

# computer opponent randomly choses between Rock paper or scissors
def opponent_move():
    lst = ('Rock', 'Paper', 'Scissors')
    move = random.choice(lst)
    print('opponent move <{}>'.format(move))
    return move

# compare between player and comp & declare a winner or a tie
# player winning scenarios
def player_win():
    return ((player_move() == 'Scissors' and opponent_move() == 'Paper') or
            (player_move() == 'Paper' and opponent_move() == 'Rock') or
            (player_move() == 'Rock' and opponent_move() == 'Scissors'))

# opponent winning scenarios
def opponent_win():
    return ((opponent_move() == 'Scissors' and player_move() == 'Paper') or
            (opponent_move() == 'Paper' and player_move() == 'Rock') or
            (opponent_move() == 'Rock' and player_move() == 'Scissors'))

# what happens if there's a tie
def tie():
    return player_move() == opponent_move()

### main ### main ### main ### main ### main ### main ### main ### main ### main ### main ### main ### main ##
print('Welcome to Rock Paper Scissors')
player_name = input('Whats your name? ').capitalize()
limit = int(input('{}, until what score would you like to play? '.format(player_name)))
opponent_score = 0
player_score = 0
play = True

while play:
    while limit > player_score and limit > opponent_score:
        print('opponents score ', opponent_score)
        print('{}s score '.format(player_name), player_score)
        player_move()
        opponent_move()
        if player_win():
            print('{} wins!'.format(player_name))
            player_score += 1
        if opponent_win():
            print('opponent wins :( ')
            opponent_score += 1
        if tie():
            print('its a tie...')
    # when score limit is reached
    if player_score == limit:
        print('Congradulatins {} you won!!!'.format(player_name))
        play = False
    if opponent_score == limit:
        print('{}, im sorry you have lost :( '.format(player_name))
        play = False

# ask if player wants to play again
if not play:
    ask = input('play again? y/n ')
    if ask[0].lower() == 'y':
        opponent_score = 0
        player_score = 0
        play = True
    else:
        print('thanks for playing')
</code>```

答:
In each single round, you make multiple calls to player_move() and opponent_move(). In player_win() and opponent_win() those should not be called again.

Basically you are asking the player and opponent for their move but when you check for the first possible outcome (scissors vs. paper), you suddenly "forgot" their moves and ask them again. Of course, their choice may now be different each time.

Instead, save the result in your main loop, and pass it as an argument, for example:

```<code>def player_win(player_choice, opponent_choice):
    return ((player_choice == 'Scissors' and opponent_choice == 'Paper') or
            (player_choice == 'Paper' and opponent_choice == 'Rock') or
            (player_choice == 'Rock' and opponent_choice == 'Scissors'))

def opponent_win(...):
    return ...
</code>```

and in your main program:

```<code>    player_choice = player_move()
    opponent_choice = opponent_move()
    if player_win(player_choice, opponent_choice):
    ...
</code>```

Body:
im fairly new to programing...
im working on a rock paper scissors game and everything works up until i need to show where player wins, or computer opponent wins, or if there is a tie.  The program just keeps asking for input to choose a weapon.
if anyone can show me why the wining or tie functions arent getting called id be very thankful
heres my code:

# Rock Paper Scissors game
import random

# player chooses between Rock Paper or Scissors
def player_move():
    global player_name
    shoot = input('{} Choose Rock, Paper or Scissors: '.format(player_name))
    while shoot[0].lower() != 'r' and shoot[0].lower() != 'p' and shoot[0].lower() != 's':
        print('sorry you must only choose r, p, or s')
        shoot = input('Try again: ')
    if shoot[0].lower() == 'r':
        shoot = 'Rock'
    if shoot[0].lower() == 'p':
        shoot = 'Paper'
    if shoot[0].lower() == 's':
        shoot = 'Scissors'
    print('your move <{}>'.format(shoot))
    return shoot

# computer opponent randomly choses between Rock paper or scissors
def opponent_move():
    lst = ('Rock', 'Paper', 'Scissors')
    move = random.choice(lst)
    print('opponent move <{}>'.format(move))
    return move

# compare between player and comp & declare a winner or a tie
# player winning scenarios
def player_win():
    return ((player_move() == 'Scissors' and opponent_move() == 'Paper') or
            (player_move() == 'Paper' and opponent_move() == 'Rock') or
            (player_move() == 'Rock' and opponent_move() == 'Scissors'))

# opponent winning scenarios
def opponent_win():
    return ((opponent_move() == 'Scissors' and player_move() == 'Paper') or
            (opponent_move() == 'Paper' and player_move() == 'Rock') or
            (opponent_move() == 'Rock' and player_move() == 'Scissors'))

# what happens if there's a tie
def tie():
    return player_move() == opponent_move()

### main ### main ### main ### main ### main ### main ### main ### main ### main ### main ### main ### main ##
print('Welcome to Rock Paper Scissors')
player_name = input('Whats your name? ').capitalize()
limit = int(input('{}, until what score would you like to play? '.format(player_name)))
opponent_score = 0
player_score = 0
play = True

while play:
    while limit > player_score and limit > opponent_score:
        print('opponents score ', opponent_score)
        print('{}s score '.format(player_name), player_score)
        player_move()
        opponent_move()
        if player_win():
            print('{} wins!'.format(player_name))
            player_score += 1
        if opponent_win():
            print('opponent wins :( ')
            opponent_score += 1
        if tie():
            print('its a tie...')
    # when score limit is reached
    if player_score == limit:
        print('Congradulatins {} you won!!!'.format(player_name))
        play = False
    if opponent_score == limit:
        print('{}, im sorry you have lost :( '.format(player_name))
        play = False

# ask if player wants to play again
if not play:
    ask = input('play again? y/n ')
    if ask[0].lower() == 'y':
        opponent_score = 0
        player_score = 0
        play = True
    else:
        print('thanks for playing')

Body:
In each single round, you make multiple calls to player_move() and opponent_move(). In player_win() and opponent_win() those should not be called again.

Basically you are asking the player and opponent for their move but when you check for the first possible outcome (scissors vs. paper), you suddenly "forgot" their moves and ask them again. Of course, their choice may now be different each time.

Instead, save the result in your main loop, and pass it as an argument, for example:

def player_win(player_choice, opponent_choice):
    return ((player_choice == 'Scissors' and opponent_choice == 'Paper') or
            (player_choice == 'Paper' and opponent_choice == 'Rock') or
            (player_choice == 'Rock' and opponent_choice == 'Scissors'))

def opponent_win(...):
    return ...

and in your main program:

    player_choice = player_move()
    opponent_choice = opponent_move()
    if player_win(player_choice, opponent_choice):
    ...


问:
how to sort the numbers 1, ... n lexicographically without converting the numbers to string?
Assume I have input n how I can print this sequence without convert the number to string?

i.e:-

n = 100
Output :- 1 10 100 11 12 13 14 15 16 17 18 19 2 20 ...

n = 15 Output :- 1 10 11 12 13 14 15 2 3 4 5 6 7 8 9

n = 20 Output :- 1 10 11 12 13 15 15 16 17 18 19 2 20 3 4 5 6 7 8 9

What is the main factor here?

My initial solution that will print the 1's followed by 0's or 2's followed by 0's

```<code> int n = 100;
    for (int i = 1; i <= n; i++) {
        int x = i;
        while (x <= n) {
            System.out.println(x);
            x *= 10;
        }
    }
</code>```

答:
I figured out the solution:-

You can call it with initial k = 1
for example printnum(15, 1

```<code>void printnums(int n, int k) {
    if (k > n) {
        return;
    }

    for (int i = 0; i < 10; i++) {
        if (k <= n) {
            System.out.println(k);

            k *= 10;
            printnums(n, k);
            k /= 10;
            k++;
            if (k % 10 == 0) return;
        }
    }
}
</code>```

I don't know if there are more optimized one?

Body:
Assume I have input n how I can print this sequence without convert the number to string?

i.e:-

n = 100
Output :- 1 10 100 11 12 13 14 15 16 17 18 19 2 20 ...

n = 15 Output :- 1 10 11 12 13 14 15 2 3 4 5 6 7 8 9

n = 20 Output :- 1 10 11 12 13 15 15 16 17 18 19 2 20 3 4 5 6 7 8 9

What is the main factor here?

My initial solution that will print the 1's followed by 0's or 2's followed by 0's

 int n = 100;
    for (int i = 1; i <= n; i++) {
        int x = i;
        while (x <= n) {
            System.out.println(x);
            x *= 10;
        }
    }

Body:
I figured out the solution:-

You can call it with initial k = 1
for example printnum(15, 1

void printnums(int n, int k) {
    if (k > n) {
        return;
    }

    for (int i = 0; i < 10; i++) {
        if (k <= n) {
            System.out.println(k);

            k *= 10;
            printnums(n, k);
            k /= 10;
            k++;
            if (k % 10 == 0) return;
        }
    }
}

I don't know if there are more optimized one?


问:
Properly defining mTLS authentication policy within Istio

I'm trying to run through the following set of commands found in an Istio online course:

Set up Istio Certificate Authority (CA)

Version 2 of the guestbook application uses an external service (tone analyzer) which is not Istio-enabled. Thus, you will disable mTLS globally and enable it only for communication between internal cluster services in this lab.

Ensure Citadel is running. Citadel is Istio's in-cluster Certificate Authority (CA) and is required for generating and managing cryptographic identities in the cluster.

```<code>kubectl get deployment -l istio=citadel -n istio-system
</code>```

This is the expected output:

Define the mTLS authentication policy for the Tone Analyzer service:

```<code>cat <<EOF | istioctl create -f -
apiVersion: authentication.istio.io/v1alpha1
kind: Policy
metadata:
  name: mtls-to-analyzer
  namespace: default
spec:
  targets:
  - name: analyzer
  peers:
  - mtls:
EOF

Created config policy/default/mtls-to-analyzer at revision 3934195
</code>```

Confirm the policy was created:

```<code>kubectl get policies.authentication.istio.io
</code>```

Enable mTLS from guestbook by using a Destination rule:

```<code>cat <<EOF | istioctl create -f -
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: route-with-mtls-for-analyzer
  namespace: default
spec:
  host: "analyzer.default.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
EOF

Created config destination-rule/default/route-with-mtls-for-analyzer at revision 3934279
</code>```

However, I run into the following error when I try to run the 2nd command:

```<code>Error: unknown command "create" for "istioctl"
</code>```

When I use "install" rather than create:

```<code>cat <<EOF | istioctl install -f -
apiVersion: authentication.istio.io/v1alpha1
kind: Policy
metadata:
  name: mtls-to-analyzer
  namespace: default
spec:
  targets:
  - name: Tone Analyzer-qy
  peers:
  - mtls:
EOF
</code>```

I get the following error:

```<code>Error: failed to apply manifests: unknown field "peers" in v1alpha1.IstioOperatorSpec:
</code>```

Could anyone provide some input on how I could modify the YAML so that the mTLS authentication service could be defined properly? I get the correct expected output on the first step, but I get the same "unknown field" error on the fourth step.

答:
istioctl is mainly used to install and debug istio.

To create istio objects should use kubectl

I think what You wanted to use is kubectl instead of istioctl like in example below:

```<code>cat <<EOF | kubectl create -f -
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: route-with-mtls-for-analyzer
  namespace: default
spec:
  host: "analyzer.default.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
EOF
</code>```

Depending on version of kubernetes cluster kubectl create can be depreciated and kubectl apply should be used in its place. So the command would look like this.

```<code>cat <<EOF | kubectl apply -f -
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: route-with-mtls-for-analyzer
  namespace: default
spec:
  host: "analyzer.default.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
EOF
</code>```

For more information review kubernetes documentation.

Hope it helps.

Body:
I'm trying to run through the following set of commands found in an Istio online course:

Set up Istio Certificate Authority (CA)

Version 2 of the guestbook application uses an external service (tone analyzer) which is not Istio-enabled. Thus, you will disable mTLS globally and enable it only for communication between internal cluster services in this lab.

Ensure Citadel is running. Citadel is Istio's in-cluster Certificate Authority (CA) and is required for generating and managing cryptographic identities in the cluster.

kubectl get deployment -l istio=citadel -n istio-system

This is the expected output:

Define the mTLS authentication policy for the Tone Analyzer service:

cat <<EOF | istioctl create -f -
apiVersion: authentication.istio.io/v1alpha1
kind: Policy
metadata:
  name: mtls-to-analyzer
  namespace: default
spec:
  targets:
  - name: analyzer
  peers:
  - mtls:
EOF

Created config policy/default/mtls-to-analyzer at revision 3934195

Confirm the policy was created:

kubectl get policies.authentication.istio.io

Enable mTLS from guestbook by using a Destination rule:

cat <<EOF | istioctl create -f -
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: route-with-mtls-for-analyzer
  namespace: default
spec:
  host: "analyzer.default.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
EOF

Created config destination-rule/default/route-with-mtls-for-analyzer at revision 3934279

However, I run into the following error when I try to run the 2nd command:

Error: unknown command "create" for "istioctl"

When I use "install" rather than create:

cat <<EOF | istioctl install -f -
apiVersion: authentication.istio.io/v1alpha1
kind: Policy
metadata:
  name: mtls-to-analyzer
  namespace: default
spec:
  targets:
  - name: Tone Analyzer-qy
  peers:
  - mtls:
EOF

I get the following error:

Error: failed to apply manifests: unknown field "peers" in v1alpha1.IstioOperatorSpec:

Could anyone provide some input on how I could modify the YAML so that the mTLS authentication service could be defined properly? I get the correct expected output on the first step, but I get the same "unknown field" error on the fourth step.

Body:
istioctl is mainly used to install and debug istio.

To create istio objects should use kubectl

I think what You wanted to use is kubectl instead of istioctl like in example below:

cat <<EOF | kubectl create -f -
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: route-with-mtls-for-analyzer
  namespace: default
spec:
  host: "analyzer.default.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
EOF

Depending on version of kubernetes cluster kubectl create can be depreciated and kubectl apply should be used in its place. So the command would look like this.

cat <<EOF | kubectl apply -f -
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: route-with-mtls-for-analyzer
  namespace: default
spec:
  host: "analyzer.default.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
EOF

For more information review kubernetes documentation.

Hope it helps.


问:
Display only products from the logged in author on WooCommerce admin products list
Is there a way, by which this Admin product dashboard shows only the products created by the logged-in user?

I am trying manage_{$post->post_type}_posts_custom_column function but cannot move much

E.g. I want something like this

```<code>add_action( 'manage_product_posts_custom_column', 'custom_column_content', 10, 2 );
function custom_column_content( $column, $product_id ){
        if( logged in user==Product Author){
            Display product;
        }
        else{
            Dont display product
        }
}
</code>```

答:
The manage_product_posts_custom_column hook is made to manipulate the columns content from admin products list.

So you need instead to alter the product query from admin products list using:

```<code>add_action( 'pre_get_posts', 'admin_pre_get_posts_product_query' );
function admin_pre_get_posts_product_query( $query ) {
    global $pagenow;

    // Targeting admin product list
    if( is_admin() && 'edit.php' == $pagenow && isset($_GET['post_type']) && 'product' === $_GET['post_type'] ) {
        $query->set( 'author', get_current_user_id() ); // Only displays the products created by the current user
    }
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Now you will have only the products belonging to the current user ID, as we filter products by logged in author.

Allowing a specific user role to view all products:

If you want to allow only "administrator" user role to view all products, you will insert in the code, just after global $pagenow; the following lines:

```<code>    // Allow administrator user roles
    if( current_user_can( 'administrator' ) ) return;
</code>```

Body:
Is there a way, by which this Admin product dashboard shows only the products created by the logged-in user?

I am trying manage_{$post->post_type}_posts_custom_column function but cannot move much

E.g. I want something like this

add_action( 'manage_product_posts_custom_column', 'custom_column_content', 10, 2 );
function custom_column_content( $column, $product_id ){
        if( logged in user==Product Author){
            Display product;
        }
        else{
            Dont display product
        }
}

Body:
The manage_product_posts_custom_column hook is made to manipulate the columns content from admin products list.

So you need instead to alter the product query from admin products list using:

add_action( 'pre_get_posts', 'admin_pre_get_posts_product_query' );
function admin_pre_get_posts_product_query( $query ) {
    global $pagenow;

    // Targeting admin product list
    if( is_admin() && 'edit.php' == $pagenow && isset($_GET['post_type']) && 'product' === $_GET['post_type'] ) {
        $query->set( 'author', get_current_user_id() ); // Only displays the products created by the current user
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Now you will have only the products belonging to the current user ID, as we filter products by logged in author.

Allowing a specific user role to view all products:

If you want to allow only "administrator" user role to view all products, you will insert in the code, just after global $pagenow; the following lines:

    // Allow administrator user roles
    if( current_user_can( 'administrator' ) ) return;


问:
Building nested array Jquery
I need help building an array in JQuery.

I want to get the component name and each field inside of it. The HTML is this:

```<code><div class="form-group _components" data-component="generic" id="module-bb3a969f-9029-5b86-8ac0-72180106df93">
    <label for="dynamic_text2">Text Field</label>
    <input type="text" class="form-control _content" data-id="module-bb3a969f-9029-5b86-8ac0-72180106df93"
        name="dynamic_text" value="">
    <input type="text" class="form-control _content" data-id="module-bb3a969f-9029-5b86-8ac0-72180106df93"
        name="dynamic_text2" value="">
</div>
<div class="form-group _components" data-component="generic" id="module-bb3a969f-9029-5b86-8ac0-72180106df93">
    <label for="dynamic_text">Text Field</label>
    <input type="text" class="form-control _content" data-id="module-bb3a969f-9029-5b86-8ac0-72180106df93"
        name="dynamic_text2" value="">
    <input type="text" class="form-control _content" data-id="module-bb3a969f-9029-5b86-8ac0-72180106df93"
        name="dynamic_text2" value="">
</div>
</code>```

Javascript is:

```<code>        let _components = $('div._components');
        let dc = {};

        let dcString;
        let inputArray = [];
        let component = [];
        let input = {};
        _components.each(function () {
            let _input = $(this).children('input');
            console.log(_components.length);

            dc["id"] = $(this).attr('id');
            dc["component"] = $(this).attr('data-component');
            let input = {};
            _input.each(function () {

                if ($(this).attr('data-id') === $(this).parent().attr('id')) {
                    input["type"] = $(this).attr('type');
                    input["name"] = $(this).attr('name');
                    input["value"] = $(this).val();
                    inputArray.push(input);
                    dc["content"] = inputArray;
                }

            });

            component.push(dc);
        });
</code>```

My output is:

```<code>0:
component: "generic"
content: Array(4)
0: {name: "dynamic_text", type: "text", value: "asdfasd"}
1: {name: "dynamic_text2", type: "text", value: "fasdfasdfasdfadsf"}
2: {name: "dynamic_text", type: "text", value: "fasdfa"}
3: {name: "dynamic_text2", type: "text", value: "sdfasdfafafd"}
length: 4
__proto__: Array(0)
id: "module-bb3a969f-9029-5b86-8ac0-72180106df93"
__proto__: Object
1:
component: "generic"
content: Array(4)
0: {name: "dynamic_text", type: "text", value: "asdfasd"}
1: {name: "dynamic_text2", type: "text", value: "fasdfasdfasdfadsf"}
2: {name: "dynamic_text", type: "text", value: "fasdfa"}
3: {name: "dynamic_text2", type: "text", value: "sdfasdfafafd"}
length: 4
__proto__: Array(0)
id: "module-bb3a969f-9029-5b86-8ac0-72180106df93"
</code>```

Which is not what I am looking for as it adds fields that don't belong to the component.

How can I build this array adding just the content fields of the specific component?
Thanks

答:
You only (ever) have one inputArray so each time you

```<code>inputArray.push(input)
</code>```

you're adding to the same inputArray - and dc["content"] points to that one array (you don't get a copy with dc["content"] = inputArray, it points to the same array) - so all of your dc.content point to the same array and all have 4 entries.

In general, keep all the let= to the narrowest scope, in this case, move let inputArray=[] (new array) inside the _components.each

```<code>_components.each(function() {
  let _input = $(this).children('input');
  let inputArray = [];
</code>```

Updated fiddle: https://jsfiddle.net/rny4op0x/

Title: Building nested array Jquery

Body:
I need help building an array in JQuery.

I want to get the component name and each field inside of it. The HTML is this:

    Text Field
    <input type="text" class="form-control _content" data-id="module-bb3a969f-9029-5b86-8ac0-72180106df93"
        name="dynamic_text" value="">
    <input type="text" class="form-control _content" data-id="module-bb3a969f-9029-5b86-8ac0-72180106df93"
        name="dynamic_text2" value="">

    Text Field
    <input type="text" class="form-control _content" data-id="module-bb3a969f-9029-5b86-8ac0-72180106df93"
        name="dynamic_text2" value="">
    <input type="text" class="form-control _content" data-id="module-bb3a969f-9029-5b86-8ac0-72180106df93"
        name="dynamic_text2" value="">

Javascript is:

        let _components = $('div._components');
        let dc = {};

        let dcString;
        let inputArray = [];
        let component = [];
        let input = {};
        _components.each(function () {
            let _input = $(this).children('input');
            console.log(_components.length);

            dc["id"] = $(this).attr('id');
            dc["component"] = $(this).attr('data-component');
            let input = {};
            _input.each(function () {

                if ($(this).attr('data-id') === $(this).parent().attr('id')) {
                    input["type"] = $(this).attr('type');
                    input["name"] = $(this).attr('name');
                    input["value"] = $(this).val();
                    inputArray.push(input);
                    dc["content"] = inputArray;
                }

            });

            component.push(dc);
        });

My output is:

0:
component: "generic"
content: Array(4)
0: {name: "dynamic_text", type: "text", value: "asdfasd"}
1: {name: "dynamic_text2", type: "text", value: "fasdfasdfasdfadsf"}
2: {name: "dynamic_text", type: "text", value: "fasdfa"}
3: {name: "dynamic_text2", type: "text", value: "sdfasdfafafd"}
length: 4
__proto__: Array(0)
id: "module-bb3a969f-9029-5b86-8ac0-72180106df93"
__proto__: Object
1:
component: "generic"
content: Array(4)
0: {name: "dynamic_text", type: "text", value: "asdfasd"}
1: {name: "dynamic_text2", type: "text", value: "fasdfasdfasdfadsf"}
2: {name: "dynamic_text", type: "text", value: "fasdfa"}
3: {name: "dynamic_text2", type: "text", value: "sdfasdfafafd"}
length: 4
__proto__: Array(0)
id: "module-bb3a969f-9029-5b86-8ac0-72180106df93"

Which is not what I am looking for as it adds fields that don't belong to the component.

How can I build this array adding just the content fields of the specific component?
Thanks

Body:
You only (ever) have one inputArray so each time you

inputArray.push(input)

you're adding to the same inputArray - and dc["content"] points to that one array (you don't get a copy with dc["content"] = inputArray, it points to the same array) - so all of your dc.content point to the same array and all have 4 entries.

In general, keep all the let= to the narrowest scope, in this case, move let inputArray=[] (new array) inside the _components.each

_components.each(function() {
  let _input = $(this).children('input');
  let inputArray = [];

Updated fiddle: https://jsfiddle.net/rny4op0x/


问:
Postgres Password Authentication Failed
I am running a Postgres 12 database on Ubuntu 18.04 on WSL (Windows Subsystem for Linux).

I can connect to the database with sudo -u postgres psql without any issues, and can view and create new databases and users.

I created a new user with CREATE USER myusername WITH PASSWORD 'mypassword'; and psql returns CREATE ROLE.

However, when I try to log in as this user with the password that I set with psql -h localhost -U myusername, I get psql: error: could not connect to server: FATAL:  password authentication failed for user "myusername".

I have tried changing the password on this user multiple times with ALTER USER myusername WITH PASSWORD 'newpassword'; and psql returns ALTER ROLE.

A common solution I have found, such as this post, is to modify the pg_hba.conf file.

My pg_hba.conf file is:

```<code>local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
</code>```

I have tried modifying both the first and second lines to md5 and ident, and restarted the postgres server each time, to no avail. I have also tried completely uninstalling and reinstalling Postgres, which does not work either.

Is there anything I am missing? Anything else that I can do to try and fix this? Thanks!

答: Doublecheck if there is another PostgreSQL instance running on the default port number.</p>

Title: Postgres Password Authentication Failed

Body:
I am running a Postgres 12 database on Ubuntu 18.04 on WSL (Windows Subsystem for Linux).

I can connect to the database with sudo -u postgres psql without any issues, and can view and create new databases and users.

I created a new user with CREATE USER myusername WITH PASSWORD 'mypassword'; and psql returns CREATE ROLE.

However, when I try to log in as this user with the password that I set with psql -h localhost -U myusername, I get psql: error: could not connect to server: FATAL:  password authentication failed for user "myusername".

I have tried changing the password on this user multiple times with ALTER USER myusername WITH PASSWORD 'newpassword'; and psql returns ALTER ROLE.

A common solution I have found, such as this post, is to modify the pg_hba.conf file.

My pg_hba.conf file is:

local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5

I have tried modifying both the first and second lines to md5 and ident, and restarted the postgres server each time, to no avail. I have also tried completely uninstalling and reinstalling Postgres, which does not work either.

Is there anything I am missing? Anything else that I can do to try and fix this? Thanks!


问:
insert 0 rows without error
Can an insert ever execute without error but not insert anything?  I am using sql server 2008 and wondering if I can get away with just checking @@error or is there something I am missing.  For an update I check @@error and @@rowcount.  Having @@rowcount = 0 for an insert just seems strange to me.

edit
@Gregory  I basically wondering how I should error check an insert statement.  Are there any strange boundary cases where an insert execute and @@error is 0?

答:
Are you experiencing no errors, but no insert?

Or is this just a question on why you should use ROWCOUNT? ROWCOUNT has other purposes than checking whether or not a single insert worked.

Or are you asking about @@ERROR?

ContentLicense: CC BY-SA 3.0

Title: insert 0 rows without error


问:
System.Text.Json deserialization fails with JsonException "read to much or not enough"
This question applies to custom deserialization classes for System.Text.Json in .Net Core 3.1.

I'm trying to understand why custom deserialization class needs to read to the end of the JSON stream even though it has already produced the required data, otherwise the deserialization fails with JsonException that ends with "read too much or not enough."

I read through Microsoft Documentation for System.Text.Json ([1], [2]), but couldn't figure that out.

Here is an example of the document:

```<code>{
    "Response": {
        "Result": [
            {
                "Code": "CLF",
                "Id": 49,
                "Type": "H"
            },
            {
                "Code": "CLF",
                "Id": 42,
                "Type": "C"
            }
        ]
    }
}
</code>```

The DTO class and deserialisation method are defined as following:

```<code>public class EntityDto
{
    public string Code { get; set; }
    public int Id { get; set; }
    public string Type { get; set; }
}

// This method is a part of class EntityDtoIEnumerableConverter : JsonConverter<IEnumerable<EntityDto>>
public override IEnumerable<EntityDto> Read(
    ref Utf8JsonReader reader,
    Type typeToConvert,
    JsonSerializerOptions options)
{
    if (reader.TokenType != JsonTokenType.StartObject)
    {
        throw new JsonException("JSON payload expected to start with StartObject token.");
    }

    while ((reader.TokenType != JsonTokenType.StartArray) && reader.Read()) { }

    var eodPostions = JsonSerializer.Deserialize<EntityDto[]>(ref reader, options);

    // This loop is required to not get JsonException
    while (reader.Read()) { }

    return new List<EntityDto>(eodPostions);
}
</code>```

Here is how the deserialization class is called.

```<code>var serializerOptions = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};
serializerOptions.Converters.Add(new EntityDtoIEnumerableConverter());

HttpResponseMessage message = await httpClient.GetAsync(requestUrl);
message.EnsureSuccessStatusCode();

var contentStream = await msg.Content.ReadAsStreamAsync();
var result = await JsonSerializer.DeserializeAsync<IEnumerable<EntityDto>>(contentStream, serializerOptions);
</code>```

When the last loop while (reader.Read()) { } in deserialization method is absent, or commented out, the last call await JsonSerializer.DeserializeAsync<... fails with the JsonException, which ends with read too much or not enough. Can anyone explain why? Or is there a better way to write this deserialization?

Updated the second block of code to use EntityDtoIEnumerableConverter.

答:
When reading an object, JsonConverter<T>.Read() must leave the Utf8JsonReader positioned on the EndObject token of the object where it was originally positioned.  (And for arrays, the EndArray of the original array.)
When writing a Read() method that parses through multiple levels of JSON, this can be done by remembering the CurrentDepth of the reader upon entry, and then reading until an EndObject is found at the same depth.

Since your EntityDtoIEnumerableConverter.Read() method seems to be trying to descend the JSON token hierarchy until an array is encountered, upon which it deserializes the array into an EntityDto[] (essentially peeling off the "Response" and "Result" wrapper properties), your code can be rewritten as follows:

```<code>public override IEnumerable<EntityDto> Read(
    ref Utf8JsonReader reader,
    Type typeToConvert,
    JsonSerializerOptions options)
{
    if (reader.TokenType != JsonTokenType.StartObject)
    {
        throw new JsonException("JSON payload expected to start with StartObject token.");
    }

    List<EntityDto> list = null;
    var startDepth = reader.CurrentDepth;

    while (reader.Read())
    {
        if (reader.TokenType == JsonTokenType.EndObject && reader.CurrentDepth == startDepth)
            return list;
        if (reader.TokenType == JsonTokenType.StartArray)
        {
            if (list != null)
                throw new JsonException("Multiple lists encountered.");
            var eodPostions = JsonSerializer.Deserialize<EntityDto[]>(ref reader, options);
            (list = new List<EntityDto>(eodPostions.Length)).AddRange(eodPostions);
        }
    }
    throw new JsonException(); // Truncated file or internal error
}
</code>```

Notes:

In your original code you returned as soon as the array was deserialized.  Since JsonSerializer.Deserialize<EntityDto[]>(ref reader, options) only advances the reader to the end of the nested array, you never advanced the reader to the required object end.  This caused the exception you were seeing.  (Advancing until the end of the JSON stream also seems to have worked when the current object was the root object, but would not have worked for nested objects.)

None of the converters currently shown in the documentation article How to write custom converters for JSON serialization (marshalling) in .NET to which you linked attempt to flatten multiple levels of JSON into a single .Net object as you are doing, so the need to track the current depth seems not to have arisen there in practice.

Demo fiddle here.

Body:
This question applies to custom deserialization classes for System.Text.Json in .Net Core 3.1.

I'm trying to understand why custom deserialization class needs to read to the end of the JSON stream even though it has already produced the required data, otherwise the deserialization fails with JsonException that ends with "read too much or not enough."

I read through Microsoft Documentation for System.Text.Json ([1], [2]), but couldn't figure that out.

Here is an example of the document:

{
    "Response": {
        "Result": [
            {
                "Code": "CLF",
                "Id": 49,
                "Type": "H"
            },
            {
                "Code": "CLF",
                "Id": 42,
                "Type": "C"
            }
        ]
    }
}

The DTO class and deserialisation method are defined as following:

public class EntityDto
{
    public string Code { get; set; }
    public int Id { get; set; }
    public string Type { get; set; }
}

// This method is a part of class EntityDtoIEnumerableConverter : JsonConverter<IEnumerable<EntityDto>>
public override IEnumerable<EntityDto> Read(
    ref Utf8JsonReader reader,
    Type typeToConvert,
    JsonSerializerOptions options)
{
    if (reader.TokenType != JsonTokenType.StartObject)
    {
        throw new JsonException("JSON payload expected to start with StartObject token.");
    }

    while ((reader.TokenType != JsonTokenType.StartArray) && reader.Read()) { }

    var eodPostions = JsonSerializer.Deserialize<EntityDto[]>(ref reader, options);

    // This loop is required to not get JsonException
    while (reader.Read()) { }

    return new List<EntityDto>(eodPostions);
}

Here is how the deserialization class is called.

var serializerOptions = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};
serializerOptions.Converters.Add(new EntityDtoIEnumerableConverter());

HttpResponseMessage message = await httpClient.GetAsync(requestUrl);
message.EnsureSuccessStatusCode();

var contentStream = await msg.Content.ReadAsStreamAsync();
var result = await JsonSerializer.DeserializeAsync<IEnumerable<EntityDto>>(contentStream, serializerOptions);

When the last loop while (reader.Read()) { } in deserialization method is absent, or commented out, the last call await JsonSerializer.DeserializeAsync<... fails with the JsonException, which ends with read too much or not enough. Can anyone explain why? Or is there a better way to write this deserialization?

Updated the second block of code to use EntityDtoIEnumerableConverter.

Body:
When reading an object, JsonConverter<T>.Read() must leave the Utf8JsonReader positioned on the EndObject token of the object where it was originally positioned.  (And for arrays, the EndArray of the original array.)
When writing a Read() method that parses through multiple levels of JSON, this can be done by remembering the CurrentDepth of the reader upon entry, and then reading until an EndObject is found at the same depth.

Since your EntityDtoIEnumerableConverter.Read() method seems to be trying to descend the JSON token hierarchy until an array is encountered, upon which it deserializes the array into an EntityDto[] (essentially peeling off the "Response" and "Result" wrapper properties), your code can be rewritten as follows:

public override IEnumerable<EntityDto> Read(
    ref Utf8JsonReader reader,
    Type typeToConvert,
    JsonSerializerOptions options)
{
    if (reader.TokenType != JsonTokenType.StartObject)
    {
        throw new JsonException("JSON payload expected to start with StartObject token.");
    }

    List<EntityDto> list = null;
    var startDepth = reader.CurrentDepth;

    while (reader.Read())
    {
        if (reader.TokenType == JsonTokenType.EndObject && reader.CurrentDepth == startDepth)
            return list;
        if (reader.TokenType == JsonTokenType.StartArray)
        {
            if (list != null)
                throw new JsonException("Multiple lists encountered.");
            var eodPostions = JsonSerializer.Deserialize<EntityDto[]>(ref reader, options);
            (list = new List<EntityDto>(eodPostions.Length)).AddRange(eodPostions);
        }
    }
    throw new JsonException(); // Truncated file or internal error
}

Notes:

In your original code you returned as soon as the array was deserialized.  Since JsonSerializer.Deserialize<EntityDto[]>(ref reader, options) only advances the reader to the end of the nested array, you never advanced the reader to the required object end.  This caused the exception you were seeing.  (Advancing until the end of the JSON stream also seems to have worked when the current object was the root object, but would not have worked for nested objects.)

None of the converters currently shown in the documentation article How to write custom converters for JSON serialization (marshalling) in .NET to which you linked attempt to flatten multiple levels of JSON into a single .Net object as you are doing, so the need to track the current depth seems not to have arisen there in practice.

Demo fiddle here.


问:
instance.invokeMethod memory leak
I am making lots of calls back to C# through .invokeMethod, and my GarbageCollector seems to be choking. Apparently I do not quite understand Javascript/Blazor interop memory management, so hopefully one of you can assist.

I am setting up window.requestAnimationFrame to call back to c#. The JS looks as follows:

```<code><script type="text/javascript">

    window.anim = {
        start: function (instance) {
            console.log('start');
            return window.requestAnimationFrame(function (timestamp) { anim.callback(instance); });
        },

        callback: function (instance) {
            instance.invokeMethod('IncrementCount');
            var callbackId = window.requestAnimationFrame(function (timestamp) { anim.callback(instance); });

        },

        stop: function (callbackId) {
            window.cancelAnimationFrame(callbackId);
        }
    };

</script>
</code>```

My Razor page looks as follows:

```<code>@page "/counter"
@inject IJSRuntime JSRuntime;

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var dotNetReference = DotNetObjectReference.Create(this);
            await JSRuntime.InvokeAsync<string>("window.anim.start", dotNetReference);
        }
    }

    [JSInvokable("IncrementCount")]
    public void IncrementCount()
    {
        currentCount++;

        StateHasChanged();
    }
}
</code>```

My GarbageCollector quite quickly comes up with "GC_MINOR: (Nursery full)" messages, and my System / JSArrayBufferData looks huge.
From the documentation, i can gather that objects should be disposed, but should they also in instances like this? (and where?!)

(Update: OK, so System / JSArrayBufferData is always huge, even when running the Blazor samples. So I guess that's not any indication on its own.. But that still doesn't help me)

The reason why this is a problem is that the GC VERY often kicks in as soon as I try to do anything meaningful. The example here is just to illustrate that it happens even in the simplest of cases.

Thanks!

/Thomas

答:
This may not work and is being added as a more complete suggestion to the comment made on the original question. I would encourage the OP to comment on how effective this is, and also anyone else to correct me where I'm wrong so that I can learn more about this.

Due to the ``IJSRuntime``` filling up the memory, the thought behind this is that it's possible the the lifetime scope of the runtime is lasting far longer than it should, and since Blazor is a stateful framework the state is being carried along with it. </p>

<p>Something to try is to use <code>OwningComponentBase</code> to enforce the scope of the JS Runtime to the life of the component, intead of the life of the connection in Blazor Server or as a singleton in Blazor WASM. Set up should only take a few lines of code. At the top of the Razor file: </p>

<pre class="lang-cs prettyprint-override"><code>@inherits OwningComponentBase
</code>```

and then in the @code block:

@code {

    // Property for the runtime, NOT injected here
    public IJSRuntime Runtime { get; set; }

    // Sets up the Runtime as a scoped service, so it will release and be available
    // for Garbage Collection when the component is torn down
    protected override void OnInitialized()
    {
        Runtime = ScopedServices.GetRequiredService<IJSRuntime>();
    }

}
```

If my thinking is correct, this should help with the memory management. I encourage others who may be more knowledgeable on the subject to comment on or edit this post as well.

This is following the Official Documentation here regarding scoped service lifetimes in Blazor.

Hopefully this helps, please report back!

Title: instance.invokeMethod memory leak

Body:
I am making lots of calls back to C# through .invokeMethod, and my GarbageCollector seems to be choking. Apparently I do not quite understand Javascript/Blazor interop memory management, so hopefully one of you can assist.

I am setting up window.requestAnimationFrame to call back to c#. The JS looks as follows:

My Razor page looks as follows:

@page "/counter"
@inject IJSRuntime JSRuntime;

Counter

Current count: @currentCount

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var dotNetReference = DotNetObjectReference.Create(this);
            await JSRuntime.InvokeAsync<string>("window.anim.start", dotNetReference);
        }
    }

    [JSInvokable("IncrementCount")]
    public void IncrementCount()
    {
        currentCount++;

        StateHasChanged();
    }
}

My GarbageCollector quite quickly comes up with "GC_MINOR: (Nursery full)" messages, and my System / JSArrayBufferData looks huge.
From the documentation, i can gather that objects should be disposed, but should they also in instances like this? (and where?!)

(Update: OK, so System / JSArrayBufferData is always huge, even when running the Blazor samples. So I guess that's not any indication on its own.. But that still doesn't help me)

The reason why this is a problem is that the GC VERY often kicks in as soon as I try to do anything meaningful. The example here is just to illustrate that it happens even in the simplest of cases.

Thanks!

/Thomas

Body:
This may not work and is being added as a more complete suggestion to the comment made on the original question. I would encourage the OP to comment on how effective this is, and also anyone else to correct me where I'm wrong so that I can learn more about this.

Due to the ``IJSRuntime``` filling up the memory, the thought behind this is that it's possible the the lifetime scope of the runtime is lasting far longer than it should, and since Blazor is a stateful framework the state is being carried along with it.

Something to try is to use OwningComponentBase to enforce the scope of the JS Runtime to the life of the component, intead of the life of the connection in Blazor Server or as a singleton in Blazor WASM. Set up should only take a few lines of code. At the top of the Razor file:

@inherits OwningComponentBase

and then in the @code block:

@code {

    // Property for the runtime, NOT injected here
    public IJSRuntime Runtime { get; set; }

    // Sets up the Runtime as a scoped service, so it will release and be available
    // for Garbage Collection when the component is torn down
    protected override void OnInitialized()
    {
        Runtime = ScopedServices.GetRequiredService<IJSRuntime>();
    }

}

If my thinking is correct, this should help with the memory management. I encourage others who may be more knowledgeable on the subject to comment on or edit this post as well.

This is following the Official Documentation here regarding scoped service lifetimes in Blazor.

Hopefully this helps, please report back!


问:
When use this code ```Form1 form = new Form1();``` something goes wrong
I'm trying to use use the code form.mainPnl.Controls.Add(background); where mainPnl is a panel I have added to Form1 that im just using for a base, and background is being created during debug.

```<code>var background = new Panel
{
Name = "background",
Dock = DockStyle.Fill,
BackColor = Color.Black,
};
</code>```

Im working in a side class (Not sure what it's called. It's just not the base class) which means I cant use anything from the mainPnl panel without getting it from Form1 so I need to use Form1 form = new Form1(); but whenever I use this I think it's looping and crashing the program.

Main Class:

```<code>public partial class Form1 : Form
    {
        public Panel mainPnl
        {
            get
            {
                return mainPanel;
            }
        }
        public TextBox textbox
        {
            get
            {
                return hey;
            }
        }

        Menu menu = new Menu();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            menu.Main();
        }

        private void Update_Tick(object sender, EventArgs e)
        {

        }
    }
</code>```

Side Class:

```<code>class Menu
    {
        Form1 form = new Form1();

        public void Main()
        {
            createObjects();
        }

        public void createObjects()
        {
            var background = new Panel
            {
                Name = "background",
                Dock = DockStyle.Fill,
                BackColor = Color.Black,
            };
            form.mainPnl.Controls.Add(background);
        }
    }
</code>```

Thats the only code. But when I run the code, it shows an error and highlights that code and says 'Exception of type 'System.StackOverflowException' was thrown'

答:
Recursion! StackoverflowExeption usually happens because of recursion (in my experience)</p>

```<code>public partial class Form1 : Form
{
  Menu menu = new Menu(); // Creates new Menu
}
class Menu
{
  Form1 form = new Form1(); // Creates new Form1
}
</code>```

Body:
I'm trying to use use the code form.mainPnl.Controls.Add(background); where mainPnl is a panel I have added to Form1 that im just using for a base, and background is being created during debug.

var background = new Panel
{
Name = "background",
Dock = DockStyle.Fill,
BackColor = Color.Black,
};

Im working in a side class (Not sure what it's called. It's just not the base class) which means I cant use anything from the mainPnl panel without getting it from Form1 so I need to use Form1 form = new Form1(); but whenever I use this I think it's looping and crashing the program.

Main Class:

public partial class Form1 : Form
    {
        public Panel mainPnl
        {
            get
            {
                return mainPanel;
            }
        }
        public TextBox textbox
        {
            get
            {
                return hey;
            }
        }

        Menu menu = new Menu();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            menu.Main();
        }

        private void Update_Tick(object sender, EventArgs e)
        {

        }
    }

Side Class:

class Menu
    {
        Form1 form = new Form1();

        public void Main()
        {
            createObjects();
        }

        public void createObjects()
        {
            var background = new Panel
            {
                Name = "background",
                Dock = DockStyle.Fill,
                BackColor = Color.Black,
            };
            form.mainPnl.Controls.Add(background);
        }
    }

Thats the only code. But when I run the code, it shows an error and highlights that code and says 'Exception of type 'System.StackOverflowException' was thrown'

Body:
Recursion! StackoverflowExeption usually happens because of recursion (in my experience)

public partial class Form1 : Form
{
  Menu menu = new Menu(); // Creates new Menu
}
class Menu
{
  Form1 form = new Form1(); // Creates new Form1
}


问:
Excel formula based on previous month
I inherited a worksheet that has a number of formulas (see below).  The formula is trying to pull the rate from the previous month but once the month changes the amount is 0, so the current month = 0.  Surely there must be a better way to write this formula but I'm stuck.  Any suggestions would be greatly appreciated.  Thanks for your help.</p>

```<code>Jan  500
Feb  =IF(MONTH(TODAY())=2,x7,"0")
Mar  =IF(MONTH(TODAY())=3,Y7,"0")
Apr  =IF(MONTH(TODAY())=4,Z7,"0")
May  =IF(MONTH(TODAY())=5,AA7,"0")
Jun  =IF(MONTH(TODAY())=6,AB7,"0")
</code>```

答:
I think what you need is to just check to see if today's date is less than the month you are evaluating for.
This may be what you are looking for:  </p>

```<code>Feb =IF(MONTH(TODAY()) < 2,0,x7)
March =IF(MONTH(TODAY()) < 3,0,y7)
</code>```

Title: Excel formula based on previous month

Body:
I inherited a worksheet that has a number of formulas (see below).  The formula is trying to pull the rate from the previous month but once the month changes the amount is 0, so the current month = 0.  Surely there must be a better way to write this formula but I'm stuck.  Any suggestions would be greatly appreciated.  Thanks for your help.

Jan  500
Feb  =IF(MONTH(TODAY())=2,x7,"0")
Mar  =IF(MONTH(TODAY())=3,Y7,"0")
Apr  =IF(MONTH(TODAY())=4,Z7,"0")
May  =IF(MONTH(TODAY())=5,AA7,"0")
Jun  =IF(MONTH(TODAY())=6,AB7,"0")

Body:
I think what you need is to just check to see if today's date is less than the month you are evaluating for.
This may be what you are looking for:

Feb =IF(MONTH(TODAY()) < 2,0,x7)
March =IF(MONTH(TODAY()) < 3,0,y7)


问:
How to cancel BackgroundWorker in WPF without DoEvents
I have a search box that works great in WinForms, but is giving me trouble in WPF.

It works by starting a search each time a letter is pushed, similar to Google.

```<code>    If (txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter) Then
        If SearchWorker.IsBusy Then
            SearchWorker.CancelAsync()
            Do While SearchWorker.IsBusy
                'Application.DoEvents()
                'System.Threading.Thread.Sleep(500)
            Loop
        End If
        doSearchText = txtQuickSearch.Text
        SearchWorker.RunWorkerAsync()
    End If
</code>```

Every time a key is pushed it cancels the current searchWorker then restarts it. In WinForms the Do while searchworker.isbusy doevents loop worked great, but since I don't have access to that anymore, I need to figure out a better way to do it. Sleep() deadlocks it, and I've tried just doing i+=1 as a way to pass time until it's not busy, but that doesn't work either...

What should I do?

Update: Here's what I changed it to. It works, but the cancel part doesn't seem to ever trigger, this doesn't seem to be running async...

```<code>Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports System.Threading
Imports System.Threading.Tasks

Public Class QuickSearch
    Private doSearchText As String
    Private canceled As Boolean
    Private curSearch As String
    Dim searchResults As New ObservableCollection(Of ocSearchResults)

    'Task Factory
    Private cts As CancellationTokenSource
    Private searchtask As Task(Of ObservableCollection(Of ocSearchResults))

    Private Sub txtQuickSearch_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles txtQuickSearch.KeyDown
        If e.Key = Key.Enter Then
            curSearch = ""
        End If
        If ((txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter)) And Not txtQuickSearch.Text = curSearch Then
            If Not cts Is Nothing Then
                cts.Cancel()
                ColorChecker.CancelAsync()
                Try
                    ' searchtask.Wait()
                Catch ex As AggregateException
                    MsgBox(ex.InnerException.Message)
                End Try
                cts = New CancellationTokenSource
            Else
                cts = New CancellationTokenSource
            End If
            Dim cToken = cts.Token
            Me.Height = 400
            doSearchText = txtQuickSearch.Text
'This always completes fully before continuing on to tRunWorkerComplete(searchtask.Result) '
            searchtask = Task(Of ObservableCollection(Of ocSearchResults)).Factory.StartNew(Function() tPerformSearch(cToken), cToken)
            Try
                tRunWorkerCompleted(searchtask.Result)
            Catch ex As AggregateException
                ' MsgBox(ex.InnerException.Message)
            End Try
        Else
            If Not cts Is Nothing Then
                cts.Cancel()
            End If
            searchResults.Clear()
        End If
    End Sub

    Function tPerformSearch(ByVal ct As CancellationToken) As ObservableCollection(Of ocSearchResults)
        On Error GoTo sError

        canceled = False
        If curSearch = doSearchText Then
            canceled = True
            Return Nothing
        End If
        curSearch = doSearchText
        Dim SR As New ObservableCollection(Of ocSearchResults)

        Dim t As ocSearchResults
        Dim rSelect As New ADODB.Recordset
        Dim sSql As String = "SELECT DISTINCT CustomerID, CustomerName, City, State, Zip FROM qrySearchFieldsQuick WHERE "
        Dim sWhere As String = "CustomerName Like '" & doSearchText & "%'"

        SR.Clear()

        With rSelect
            .Open(sSql & sWhere & " ORDER BY CustomerName", MyCn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly)
            Do While Not .EOF
                If ct.IsCancellationRequested Then ' This never shows true, the process always returns a value, as if it wasn't async'
                    canceled = True
                    Return Nothing
                End If

                Do While IsDBNull(.Fields("CustomerID").Value)
                    .MoveNext()
                Loop

                t = New ocSearchResults(.Fields!CustomerID.Value, .Fields!CustomerName.Value.ToString.Trim, .Fields!City.Value.ToString.Trim, .Fields!State.Value.ToString.Trim, .Fields!Zip.Value.ToString.Trim)
                If Not SR.Contains(t) Then
                    SR.Add(t)
                End If
aMoveNext:
                .MoveNext()
            Loop
            .Close()
        End With

        Return SR
        Exit Function
sError:
        MsgBox(ErrorToString, MsgBoxStyle.Exclamation)
    End Function

    Sub tRunWorkerCompleted(ByVal SR As ObservableCollection(Of ocSearchResults))
        If canceled Then
            Exit Sub
        End If
        If cts.IsCancellationRequested Then
            Exit Sub
        End If

        searchResults.Clear()
        For Each t As ocSearchResults In SR
            searchResults.Add(t)
        Next

        ColorChecker = New BackgroundWorker
        ColorChecker.WorkerReportsProgress = True
        ColorChecker.WorkerSupportsCancellation = True
        ColorChecker.RunWorkerAsync(searchResults)

        lblRecordCount.Text = "(" & searchResults.Count & ") Records"

        progBar.Value = 100
        Exit Sub
sError:
        MsgBox(ErrorToString)
    End Sub
</code>```

答:
I don't know enough VB to give you any well written sample code, but if you're on .Net 4.0 I suggest switching to the System.Threading.Tasks namespace, which has cancellation abilities.

```<code>If (txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter) Then
    If TokenSource Is Not Nothing Then
        TokenSource.Cancel()
        TokenSource = New CancellationTokenSource()
    End If
    Task.Factory.StartNew(SomeSearchMethod, txtQuickSearch.Text, TokenSource.Token)
End If
</code>```

Body:
I have a search box that works great in WinForms, but is giving me trouble in WPF.

It works by starting a search each time a letter is pushed, similar to Google.

    If (txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter) Then
        If SearchWorker.IsBusy Then
            SearchWorker.CancelAsync()
            Do While SearchWorker.IsBusy
                'Application.DoEvents()
                'System.Threading.Thread.Sleep(500)
            Loop
        End If
        doSearchText = txtQuickSearch.Text
        SearchWorker.RunWorkerAsync()
    End If

Every time a key is pushed it cancels the current searchWorker then restarts it. In WinForms the Do while searchworker.isbusy doevents loop worked great, but since I don't have access to that anymore, I need to figure out a better way to do it. Sleep() deadlocks it, and I've tried just doing i+=1 as a way to pass time until it's not busy, but that doesn't work either...

What should I do?

Update: Here's what I changed it to. It works, but the cancel part doesn't seem to ever trigger, this doesn't seem to be running async...

Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports System.Threading
Imports System.Threading.Tasks

Public Class QuickSearch
    Private doSearchText As String
    Private canceled As Boolean
    Private curSearch As String
    Dim searchResults As New ObservableCollection(Of ocSearchResults)

    'Task Factory
    Private cts As CancellationTokenSource
    Private searchtask As Task(Of ObservableCollection(Of ocSearchResults))

    Private Sub txtQuickSearch_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles txtQuickSearch.KeyDown
        If e.Key = Key.Enter Then
            curSearch = ""
        End If
        If ((txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter)) And Not txtQuickSearch.Text = curSearch Then
            If Not cts Is Nothing Then
                cts.Cancel()
                ColorChecker.CancelAsync()
                Try
                    ' searchtask.Wait()
                Catch ex As AggregateException
                    MsgBox(ex.InnerException.Message)
                End Try
                cts = New CancellationTokenSource
            Else
                cts = New CancellationTokenSource
            End If
            Dim cToken = cts.Token
            Me.Height = 400
            doSearchText = txtQuickSearch.Text
'This always completes fully before continuing on to tRunWorkerComplete(searchtask.Result) '
            searchtask = Task(Of ObservableCollection(Of ocSearchResults)).Factory.StartNew(Function() tPerformSearch(cToken), cToken)
            Try
                tRunWorkerCompleted(searchtask.Result)
            Catch ex As AggregateException
                ' MsgBox(ex.InnerException.Message)
            End Try
        Else
            If Not cts Is Nothing Then
                cts.Cancel()
            End If
            searchResults.Clear()
        End If
    End Sub

    Function tPerformSearch(ByVal ct As CancellationToken) As ObservableCollection(Of ocSearchResults)
        On Error GoTo sError

        canceled = False
        If curSearch = doSearchText Then
            canceled = True
            Return Nothing
        End If
        curSearch = doSearchText
        Dim SR As New ObservableCollection(Of ocSearchResults)

        Dim t As ocSearchResults
        Dim rSelect As New ADODB.Recordset
        Dim sSql As String = "SELECT DISTINCT CustomerID, CustomerName, City, State, Zip FROM qrySearchFieldsQuick WHERE "
        Dim sWhere As String = "CustomerName Like '" & doSearchText & "%'"

        SR.Clear()

        With rSelect
            .Open(sSql & sWhere & " ORDER BY CustomerName", MyCn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly)
            Do While Not .EOF
                If ct.IsCancellationRequested Then ' This never shows true, the process always returns a value, as if it wasn't async'
                    canceled = True
                    Return Nothing
                End If

                Do While IsDBNull(.Fields("CustomerID").Value)
                    .MoveNext()
                Loop

                t = New ocSearchResults(.Fields!CustomerID.Value, .Fields!CustomerName.Value.ToString.Trim, .Fields!City.Value.ToString.Trim, .Fields!State.Value.ToString.Trim, .Fields!Zip.Value.ToString.Trim)
                If Not SR.Contains(t) Then
                    SR.Add(t)
                End If
aMoveNext:
                .MoveNext()
            Loop
            .Close()
        End With

        Return SR
        Exit Function
sError:
        MsgBox(ErrorToString, MsgBoxStyle.Exclamation)
    End Function

    Sub tRunWorkerCompleted(ByVal SR As ObservableCollection(Of ocSearchResults))
        If canceled Then
            Exit Sub
        End If
        If cts.IsCancellationRequested Then
            Exit Sub
        End If

        searchResults.Clear()
        For Each t As ocSearchResults In SR
            searchResults.Add(t)
        Next

        ColorChecker = New BackgroundWorker
        ColorChecker.WorkerReportsProgress = True
        ColorChecker.WorkerSupportsCancellation = True
        ColorChecker.RunWorkerAsync(searchResults)

        lblRecordCount.Text = "(" & searchResults.Count & ") Records"

        progBar.Value = 100
        Exit Sub
sError:
        MsgBox(ErrorToString)
    End Sub

Body:
I don't know enough VB to give you any well written sample code, but if you're on .Net 4.0 I suggest switching to the System.Threading.Tasks namespace, which has cancellation abilities.

If (txtQuickSearch.Text.Length >= 3) Or (e.Key = Key.Enter) Then
    If TokenSource Is Not Nothing Then
        TokenSource.Cancel()
        TokenSource = New CancellationTokenSource()
    End If
    Task.Factory.StartNew(SomeSearchMethod, txtQuickSearch.Text, TokenSource.Token)
End If


问:
Mysql join results from 2 tables
I have 2 tables. 'media_id' from category table references 'id' from media table. Each item in media table can have zero or more categories from category table.

media table

```<code>| id | options | order_id | player_id |
|-------------------------------------|
| 1  | ...     | 0        | 5         |
|-------------------------------------|
| 2  | ...     | 1        | 11        |
|-------------------------------------|
| 3  | ...     | 2        | 7         |
|_____________________________________|
</code>```

category table

```<code> __________________________
| id | category | media_id |
|--------------------------|
| 1  | fashion  | 1        |
|--------------------------|
| 2  | sport    | 2        |
|--------------------------|
| 3  | sport    | 3        |
|--------------------------|
| 4  | cats     | 4        |
|--------------------------|
| 5  | dogs     | 4        |
|--------------------------|
| 6  | sport    | 5        |
|__________________________|
</code>```

Have would I select all data from both tables where player_id=5 ORDER BY order_id in single query?

Response should be array(id, options, order_id, category)

I can run one query to fetch all items from media table where player_id=5. Then I would loop all results and for each result select all categories from category table where media_id=id from media table. But this would be multiple queries.

答:
Have you tried this?

```<code>SELECT *
FROM media
INNER JOIN category
ON media.id = category.media_id
WHERE media.player_id = 5
ORDER BY media.order_id
</code>```

Not sure if that's completely what you're looking for...

Title: Mysql join results from 2 tables

Body:
I have 2 tables. 'media_id' from category table references 'id' from media table. Each item in media table can have zero or more categories from category table.

media table

| id | options | order_id | player_id |
|-------------------------------------|
| 1  | ...     | 0        | 5         |
|-------------------------------------|
| 2  | ...     | 1        | 11        |
|-------------------------------------|
| 3  | ...     | 2        | 7         |
|_____________________________________|

category table

 __________________________
| id | category | media_id |
|--------------------------|
| 1  | fashion  | 1        |
|--------------------------|
| 2  | sport    | 2        |
|--------------------------|
| 3  | sport    | 3        |
|--------------------------|
| 4  | cats     | 4        |
|--------------------------|
| 5  | dogs     | 4        |
|--------------------------|
| 6  | sport    | 5        |
|__________________________|

Have would I select all data from both tables where player_id=5 ORDER BY order_id in single query?

Response should be array(id, options, order_id, category)

I can run one query to fetch all items from media table where player_id=5. Then I would loop all results and for each result select all categories from category table where media_id=id from media table. But this would be multiple queries.

Body:
Have you tried this?

SELECT *
FROM media
INNER JOIN category
ON media.id = category.media_id
WHERE media.player_id = 5
ORDER BY media.order_id

Not sure if that's completely what you're looking for...


问:
Can I schedule a mail delivery without using GAS trigger?
Gmail has the option to schedule mailings from the application.

Is this option implemented in GmailApp.sendEmail()?

I don't want to use Google Apps Script triggers, I want to use the option given by the GmailApp

答:
Unfortunately, the only option available of scheduling the sending of an email is by using the triggers.

What you can do instead is to file a Feature Request for the Gmail API using Google Issue Tracker here and provide the details needed regarding this.


问:
Get data after second underscore from back in python dataframe?
I'm trying to get data after second underscore from back in python dataframe?

```<code>    number
0   a_bc_def 12_23_this_6729
1   abc_def,122$3_this_6729
2   abc_def_1_2_23_this_6729

    number
0   this_6729
1   this_6729
2   this_6729
</code>```

I tried to get data from second underscore from beginning.

```<code>df['number'] = df['number'].str.split('_',2).apply(lambda x: x[-1])
</code>```

How to do that from second underscore from back ?

答:
One way could be to reverse the string for the same, do the operation, and reverse again.

```<code>df['number'].apply(lambda x: str(x)[::-1].split('_',2)[-1][::-1])
</code>```

It's not very efficient since you need to reverse twice, but of strings are not too long this will not be that bad in my opinion.

Body:
I'm trying to get data after second underscore from back in python dataframe?

    number
0   a_bc_def 12_23_this_6729
1   abc_def,122$3_this_6729
2   abc_def_1_2_23_this_6729

    number
0   this_6729
1   this_6729
2   this_6729

I tried to get data from second underscore from beginning.

df['number'] = df['number'].str.split('_',2).apply(lambda x: x[-1])

How to do that from second underscore from back ?

Body:
One way could be to reverse the string for the same, do the operation, and reverse again.

df['number'].apply(lambda x: str(x)[::-1].split('_',2)[-1][::-1])

It's not very efficient since you need to reverse twice, but of strings are not too long this will not be that bad in my opinion.


问:
how to push a count into 1D array to make it 2D
I want to create a 1D array into 2D.

I have an array arr1 which is 1D

Now I am searching the elements of this 1D arrayarr1 into another array arr2 which contains the search variables. I am successfully able to count the occurrence of arr1 from arr2, but unable to store the count in arr1.

arr2 = [a,a,a,a,b,d,e,f,f,f,g,g....]

```<code>var arr1 = ["a","b","c".......]

  for (i =0; i<shrink_days.length; i++){
    var count = arr2.flat().reduce(function(n, val) {
    return n + (val === arr1[i]);
}, 0);
  //arr1[i][1].push(count)
}
</code>```

my arr1[i].push(count) gives error 'arr1[i][1].push is not a function'.

What I want to achieve is : arr1 = [[a,4],[b,1],[c,0],[d,1],[e,1],[f,3],[g,2]......]

答:
You can replace the element of the first array with a new array containing the original element and the count:

arr1[i] = [arr1[i], count]

Arguably, if you care about immutability, you should leave arr1 untouched and create a third array with that structure.

Body:
I want to create a 1D array into 2D.

I have an array arr1 which is 1D

Now I am searching the elements of this 1D arrayarr1 into another array arr2 which contains the search variables. I am successfully able to count the occurrence of arr1 from arr2, but unable to store the count in arr1.

arr2 = [a,a,a,a,b,d,e,f,f,f,g,g....]

var arr1 = ["a","b","c".......]

  for (i =0; i<shrink_days.length; i++){
    var count = arr2.flat().reduce(function(n, val) {
    return n + (val === arr1[i]);
}, 0);
  //arr1[i][1].push(count)
}

my arr1[i].push(count) gives error 'arr1[i][1].push is not a function'.

What I want to achieve is : arr1 = [[a,4],[b,1],[c,0],[d,1],[e,1],[f,3],[g,2]......]


问:
How to set up a running environment on Ubuntu?
I want to customize a command to set up running environment, but I'm having some issue here. For example, I can run:

```<code>envsetup
</code>```

and it will run the following script to help set up the environment:

```<code>cd /opt/dir/set_up | source environment
</code>```

I have tried to add the following code to my $HOME .bashrc file, but it's not working (Maybe I should add it to the .bashrc in my root dir?):

```<code>alias envsetup = 'cd /opt/dir/set_up | source environment'
</code>```

Could anyone let me know what might be wrong here please?

答:
A couple of things:

The cd command changes directories and doesn't output anything to
standard output (stdout). So there's no point in piping its output to another command with |. If you want to execute two commands in sequence, you can separate with ;.

When defining an alias you can't be too generous
with spaces.

Here's an option, then, to do what I think you want:

```<code>alias envsetup='cd /opt/dir/set_up ; source environment'
</code>```

Per additional desire expressed in the comment, if you want to come back to the original directory, you can do it this way:

```<code>alias envsetup='(cd /opt/dir/set_up ; source environment)'
</code>```

This runs the commands in a subshell so your current shell setup is unchanged, including the current working directory.

Note that since this runs in a subshell, if source is intended to change the environment variables in a persistent way, then this will not work. You can, alternatively, try something like this:

```<code>alias envsetup='p=$(pwd) ; cd /opt/dir/set_up ; source environment ; cd $p'
</code>```

This will run in the same shell. You can choose whatever name you wish for p.

Body:
I want to customize a command to set up running environment, but I'm having some issue here. For example, I can run:

envsetup

and it will run the following script to help set up the environment:

cd /opt/dir/set_up | source environment

I have tried to add the following code to my $HOME .bashrc file, but it's not working (Maybe I should add it to the .bashrc in my root dir?):

alias envsetup = 'cd /opt/dir/set_up | source environment'

Could anyone let me know what might be wrong here please?

Body:
A couple of things:

The cd command changes directories and doesn't output anything to
standard output (stdout). So there's no point in piping its output to another command with |. If you want to execute two commands in sequence, you can separate with ;.

When defining an alias you can't be too generous
with spaces.

Here's an option, then, to do what I think you want:

alias envsetup='cd /opt/dir/set_up ; source environment'

Per additional desire expressed in the comment, if you want to come back to the original directory, you can do it this way:

alias envsetup='(cd /opt/dir/set_up ; source environment)'

This runs the commands in a subshell so your current shell setup is unchanged, including the current working directory.

Note that since this runs in a subshell, if source is intended to change the environment variables in a persistent way, then this will not work. You can, alternatively, try something like this:

alias envsetup='p=$(pwd) ; cd /opt/dir/set_up ; source environment ; cd $p'

This will run in the same shell. You can choose whatever name you wish for p.


问:
Problem exporting XML multiple values on PHP 7.2 & Prestashop 1.7
I'm trying to export products from Prestashop 1.7 to an XML. Everything works great, but the script exports a product multiple times, depending on the categories that belongs to.
For example Product1 is in All products - Clothes - Men , in this situation will be exported 3 times in XML.

I tried to use array_unique based on product ID but it doesn`t work. Can someone, please, point me to the right direction?

The full code can be found here: https://pastebin.com/MQxfYSj2

On this part of the code i tried to use array_unique with no result:

```<code>    private function getProductFromArray($arrProduct){
    $objProduct = new Okazii_Connector_Product();

    $objProduct->ID = $arrProduct['id_product'];
    $objProduct->UniqueID = $arrProduct['id_product'];
    $objProduct->Title = $arrProduct['name'];
    if (mb_strlen($arrProduct['description']) > 3){
        $objProduct->Description = $arrProduct['description'];
    } else if (mb_strlen($arrProduct['description_short'])) {
        $objProduct->Description = $arrProduct['description_short'];
    } else {
        $objProduct->Description = $arrProduct['name'];
    }
    $objProduct->Amount = $arrProduct['quantity'];

    if ($objProduct->Amount == 0){
        $objProduct->Amount = $this->getAmountFromStock($arrProduct['id_product']);
    }
    $objProduct->Category = $this->getCategoryString($arrProduct['id_category']);
    $objProduct->Currency = $this->getCurrency();
    $objProduct->Price = $arrProduct['price'];

    if(!empty($arrProduct['available_now']) && $objProduct->Amount > 0)
    {
        $objProduct->InStock = $arrProduct['available_now'];
    }

    if(!empty($arrProduct['gtin']))
    {
        $objProduct->GTIN = $arrProduct['gtin'];
    }
    else if(!empty($arrProduct['ean13']))
    {
        $objProduct->GTIN = $arrProduct['ean13'];
    }
    else if(!empty($arrProduct['isbn']))
    {
        $objProduct->GTIN = $arrProduct['isbn'];
    }

    $this->setProductImages($objProduct);
    $this->setProductBrand($objProduct, $arrProduct['id_manufacturer']);

    return $objProduct;
}
</code>```

I also tried on the top of the script to get only unique products based on product ID, not working as well.

Other usefull info: PHP 7.2, Prestashop 1.7.6.5

答:
Try to create an attribute in the very beginning of the class like

private $exportedProductsIds = [];

and then after each iteration put exported product id into it just before the return

```<code>array_push($this->exportedProductsIds, $objProduct->id);
</code>```

and then add a verification before run if the id is already in the $exportedProductsIds then skip the iteration

```<code>if (!in_array($objProduct->id, $this->exportedProductsIds)) {
   //run your code
}
</code>```

But I think the best place to put this code would be that one where you call getProductFromArray method from.

I assume like this

```<code>private function exportProducts($products)
{
     foreach ($products as $product) {
         if (in_array($objProduct->id, $this->exportedProductsIds)) {
             continue;
         }
         if ($this->getProductFromArray($arrProduct)) {
             array_push($this->exportedProductsIds, $objProduct->id);
         }
     }
}
</code>```

Body:
I'm trying to export products from Prestashop 1.7 to an XML. Everything works great, but the script exports a product multiple times, depending on the categories that belongs to.
For example Product1 is in All products - Clothes - Men , in this situation will be exported 3 times in XML.

I tried to use array_unique based on product ID but it doesn`t work. Can someone, please, point me to the right direction?

The full code can be found here: https://pastebin.com/MQxfYSj2

On this part of the code i tried to use array_unique with no result:

    private function getProductFromArray($arrProduct){
    $objProduct = new Okazii_Connector_Product();

    $objProduct->ID = $arrProduct['id_product'];
    $objProduct->UniqueID = $arrProduct['id_product'];
    $objProduct->Title = $arrProduct['name'];
    if (mb_strlen($arrProduct['description']) > 3){
        $objProduct->Description = $arrProduct['description'];
    } else if (mb_strlen($arrProduct['description_short'])) {
        $objProduct->Description = $arrProduct['description_short'];
    } else {
        $objProduct->Description = $arrProduct['name'];
    }
    $objProduct->Amount = $arrProduct['quantity'];

    if ($objProduct->Amount == 0){
        $objProduct->Amount = $this->getAmountFromStock($arrProduct['id_product']);
    }
    $objProduct->Category = $this->getCategoryString($arrProduct['id_category']);
    $objProduct->Currency = $this->getCurrency();
    $objProduct->Price = $arrProduct['price'];

    if(!empty($arrProduct['available_now']) && $objProduct->Amount > 0)
    {
        $objProduct->InStock = $arrProduct['available_now'];
    }

    if(!empty($arrProduct['gtin']))
    {
        $objProduct->GTIN = $arrProduct['gtin'];
    }
    else if(!empty($arrProduct['ean13']))
    {
        $objProduct->GTIN = $arrProduct['ean13'];
    }
    else if(!empty($arrProduct['isbn']))
    {
        $objProduct->GTIN = $arrProduct['isbn'];
    }

    $this->setProductImages($objProduct);
    $this->setProductBrand($objProduct, $arrProduct['id_manufacturer']);

    return $objProduct;
}

I also tried on the top of the script to get only unique products based on product ID, not working as well.

Other usefull info: PHP 7.2, Prestashop 1.7.6.5

Body:
Try to create an attribute in the very beginning of the class like

private $exportedProductsIds = [];

and then after each iteration put exported product id into it just before the return

array_push($this->exportedProductsIds, $objProduct->id);

and then add a verification before run if the id is already in the $exportedProductsIds then skip the iteration

if (!in_array($objProduct->id, $this->exportedProductsIds)) {
   //run your code
}

But I think the best place to put this code would be that one where you call getProductFromArray method from.

I assume like this

private function exportProducts($products)
{
     foreach ($products as $product) {
         if (in_array($objProduct->id, $this->exportedProductsIds)) {
             continue;
         }
         if ($this->getProductFromArray($arrProduct)) {
             array_push($this->exportedProductsIds, $objProduct->id);
         }
     }
}


问:
T-SQL query to show table definition?
What is a query that will show me the full definition, including indexes and keys for a SQL Server table?  I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio.  But SQLCMD is always an option.

UPDATE:  I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime.  Is there something else I am missing with sp_help?

Here is what I call:

sp_help airports

Note that I really do want the DDL that defines the table.

答:
Another way is to execute sp_columns procedure.</p>

```<code>EXEC sys.sp_columns @TABLE_NAME = 'YourTableName'
</code>```

Title: T-SQL query to show table definition?

Body:
Another way is to execute sp_columns procedure.

EXEC sys.sp_columns @TABLE_NAME = 'YourTableName'


问:
Save HTMLFile ComObject to file in Powershell
After loading a html file using

```<code>$html = New-Object -ComObject "HTMLFile"
$content = $(Get-Content $path -raw)
$html.IHTMLDocument2_write($content)
</code>```

I have manipulated the $html object and now want to save it to another file. How can I do this?

答: I just started using the HTMLFile COM object, but I believe that $html.documentElement.outerHTML should be a string containing the entire document including the opening  tag, but not the <!DOCTYPE> tag.  You can access $html.doctype or just shove in a <!DOCTYPE html> yourself, then you should wind up with a valid page on disk.

Body:
After loading a html file using

$html = New-Object -ComObject "HTMLFile"
$content = $(Get-Content $path -raw)
$html.IHTMLDocument2_write($content)

I have manipulated the $html object and now want to save it to another file. How can I do this?

Body: I just started using the HTMLFile COM object, but I believe that $html.documentElement.outerHTML should be a string containing the entire document including the opening <html> tag, but not the <!DOCTYPE> tag.  You can access $html.doctype or just shove in a <!DOCTYPE html> yourself, then you should wind up with a valid page on disk.


问:
I am using multiple firebase projects in an Android App. I am getting this error : Missing google_app_id. Firebase Analytics disabled
I have added following code to initialise there projects.

```<code>FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:129574837465:android:0123456773a52cf4f6") // Required for Analytics.
            .setApiKey("iubdeibneh8gzDt7Xn9f-jdjjdjdjdj") // Required for Auth.
            .setDatabaseUrl("https://databasename-d7r7.firebaseio.com") // Required for RTDB.
            .build();

FirebaseApp.initializeApp(context /* Context */, options, "secondary");

FirebaseOptions options2 = new FirebaseOptions.Builder()
            .setApplicationId("1:129574837465:android:0123456773a52cf4f6") // Required for Analytics.
            .setApiKey("iubdeibneh8gzDt7Xn9f-jdjjdjdjdj") // Required for Auth.
            .setDatabaseUrl("https://databasename2-d7r7.firebaseio.com") // Required for RTDB.
            .build();

FirebaseApp.initializeApp(context /* Context */, options2, "secondary2");

FirebaseOptions options3 = new FirebaseOptions.Builder()
            .setApplicationId("1:129574837465:android:0123456773a52cf4f6") // Required for Analytics.
            .setApiKey("kjdkj-o_3nk4jn4k3kjk23j") // Required for Auth.
            .setDatabaseUrl("https://databasename3-d7r7.firebaseio.com") // Required for RTDB.
            .build();

FirebaseApp.initializeApp(context /* Context */, options3, "secondary3");
</code>```

After initialisation my app is running fine. I can use FirebaseAuth, and FirebaseRTDB just fine but it is throwing error when it has to access firebase_Application_Id for analytics.

I have cross checked the ids from google-services.json files of all the projects. I don't know why but it throws error saying:

```<code>Missing google_app_id. Firebase Analytics disabled.
</code>```

I couldn't figure out the root of this error.

答:
Manually add google_app_id to the strings.xml file like:

You can get google_app_id from google-services.json, in which it is defined as mobilesdk_app_id.

Body:
I have added following code to initialise there projects.

FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:129574837465:android:0123456773a52cf4f6") // Required for Analytics.
            .setApiKey("iubdeibneh8gzDt7Xn9f-jdjjdjdjdj") // Required for Auth.
            .setDatabaseUrl("https://databasename-d7r7.firebaseio.com") // Required for RTDB.
            .build();

FirebaseApp.initializeApp(context /* Context */, options, "secondary");

FirebaseOptions options2 = new FirebaseOptions.Builder()
            .setApplicationId("1:129574837465:android:0123456773a52cf4f6") // Required for Analytics.
            .setApiKey("iubdeibneh8gzDt7Xn9f-jdjjdjdjdj") // Required for Auth.
            .setDatabaseUrl("https://databasename2-d7r7.firebaseio.com") // Required for RTDB.
            .build();

FirebaseApp.initializeApp(context /* Context */, options2, "secondary2");

FirebaseOptions options3 = new FirebaseOptions.Builder()
            .setApplicationId("1:129574837465:android:0123456773a52cf4f6") // Required for Analytics.
            .setApiKey("kjdkj-o_3nk4jn4k3kjk23j") // Required for Auth.
            .setDatabaseUrl("https://databasename3-d7r7.firebaseio.com") // Required for RTDB.
            .build();

FirebaseApp.initializeApp(context /* Context */, options3, "secondary3");

After initialisation my app is running fine. I can use FirebaseAuth, and FirebaseRTDB just fine but it is throwing error when it has to access firebase_Application_Id for analytics.

I have cross checked the ids from google-services.json files of all the projects. I don't know why but it throws error saying:

Missing google_app_id. Firebase Analytics disabled.

I couldn't figure out the root of this error.