问:
If for &*x both * and & are not evaluated, then why not have the same rule for *&x?
C2x, 6.5.3.2 Address and indirection operators, Semantics, 3:

The unary & operator yields the address of its operand. If the operand has type "type", the result has type "pointer to type". If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.

If for &*x both * and & are not evaluated, then why not have the same rule for *&x? I.e. the same rule for the unary * operator.

答:
Because the value may change, reference not.

```<code>int foo(volatile int x)
{
    return *&x;
}

int *bar(volatile int *x)
{
    return &*x;
}
</code>```
```<code>foo:
        mov     DWORD PTR [rsp-4], edi
        mov     eax, DWORD PTR [rsp-4]
        ret
bar:
        mov     rax, rdi
        ret
</code>```

Interesting this will be evaluated (& only):

```<code>int *bar(int * volatile x)
{
    return &*x;
}
</code>```

So it is invalidating my previous opinion

Body:
Because the value may change, reference not.

int foo(volatile int x)
{
    return *&x;
}

int *bar(volatile int *x)
{
    return &*x;
}

foo:
        mov     DWORD PTR [rsp-4], edi
        mov     eax, DWORD PTR [rsp-4]
        ret
bar:
        mov     rax, rdi
        ret

Interesting this will be evaluated (& only):

int *bar(int * volatile x)
{
    return &*x;
}

So it is invalidating my previous opinion


来源: stackexchange

问:
Cypress - How to store a value from a request that changes each time to assert on it?
Our company is switching to Cybersource & tokenized credit cards. The token is new each time.

I'm trying to find a way to store the token from the request and reference it to assert it's correct.

Example of the request:

```<code>request:
body:
accountRegistrationPreferences: {email: ''}
paymentDetails: Array(1)
0:
billingAddress: {address: {…}, contactInfo: {…}, personalInfo: {…}}
cardId: "eusercc42210010"
tokenDetails:
referenceId: "bcc8c381-79d6-4a83-a10a-d67e2d585268"
token:
</code>```

"eyJraWQiOiIwOFJORkptMWFIVlhhZUhRaUJrNHZNRFF1MGt3WW9kNCIsImFsZyI6IlJTMjU2In0.eyJkYXRhIjp7ImV4cGlyYXRpb25ZZWFyIjoiMjAzMCIsImV4cGlyYXRpb25Nb250aCI6IjAzIn0sImlzcyI6IkZsZXgvMDgiLCJleHAiOjE2NDQ0MzE2ODQsInR5cGUiOiJtZi0wLjExLjAiLCJpYXQiOjE2NDQ0MzA3ODQsImp0aSI6IjFFNVpSSEQzTFBaUzM0NUdIVVVUUjJQRjdFNzBZSDlKN1dTQjRTWEhTVEJEN08xTFRFUzg2MjA0MDk0NEFBNjIiLCJjb250ZW50Ijp7InBheW1lbnRJbmZvcm1hdGlvbiI6eyJjYXJkIjp7ImV4cGlyYXRpb25ZZWFyIjp7InZhbHVlIjoiMjAzMCJ9LCJzZWN1cml0eUNvZGUiOnt9LCJleHBpcmF0aW9uTW9udGgiOnsidmFsdWUiOiIwMyJ9fX19fQ.bCR73pMD9eXILtZHQRrmqgzcLqI_QCTEVtnQXNPJLOk-RxMUar8LbC1BS59G6FpynCI2rvJVMPixjtes2WRcnM77cjOlTarNM4-VnAJnqKluXy2jx5Hgtn_OrT7aSaS8NOoSyYzwPFlbkqsBMV5oT5kmiHZ8Qn4qBnga8sEYmPFgzoAUUnQ6uWLN1ZkZnKCO8uizZ_HaKUjdUQCyRzgWbtKfTctD9aAi5AcSNgAVbWTV_gt155jFa11v8mLF4iaqA3bLdJfEh4lu9HxB17sOShZBoZvxEQ3fN8gDkk4f56VlswB-aN3J5QFI7me36pgwY5khAhYrFma1o79V-b2KYw"

```<code>type: "tokenizedCreditCard"
</code>```

Here's the Cypress test

```<code>  it("User clicks confirm & pay button to complete order", () => {
cy.intercept("/api/checkout/payandcommit?*").as("placeOrder");
cy.placeOrderAndPay();
cy.wait("@placeOrder").then((interception) => {
  console.log(interception);
  // Order status should equal 200
  cy.wrap(interception.response.statusCode).should("eq", 200);
  // Check payment details card type
  cy.wrap(interception.request.body.paymentDetails[0].type).should(
    "include",
    "tokenizedCreditCard"
  );
  cy.wrap(
    interception.request.body.paymentDetails[0].tokenDetails.token
  ).should("include", token);
  // Check request to ensure delivery charge is passed at £0 due to Unlimited membership.
  cy.wrap(
    interception.response.body.response.order.orderPriceInfo.shipping
  ).should("eq", 0);
  // Ensure standard delivery is returned in the order response.
  cy.wrap(
    interception.response.body.response.order.shippingDetails[0]
      .shippingMethod.type
  ).should("include", "standard");
});
</code>```

});

This is the part I'm struggling with:

```<code>cy.wrap(
interception.request.body.paymentDetails[0].tokenDetails.token).should("include", token);
</code>```

How can I store the token value that's changed each time so I can assert on it?

Is this possible? Any help would be amazing, I'm a bit of a doob and learning.

答:
To test that the response has a token property,

cy.wrap(interception.request.body.paymentDetails[0].tokenDetails)
  .should('have.property', 'token')
//or
cy.wrap(interception.request.body.paymentDetails[0])
  .should('have.deep.property', 'token')  // this assertion searches the object
```
<p>To store the token an alias might be used</p>
<pre class="lang-js prettyprint-override"><code>cy.wrap(interception.request.body.paymentDetails[0].tokenDetails.token)
  .as('token')

// Later in test
cy.get('@token').then(token => {
  expect(token).to.eq(expectedToken)
})
</code>```

The token alias gets a new value every time you use .as('token'), so there's no problem with the changing token value.

ContentLicense: CC BY-SA 4.0

Body:
Our company is switching to Cybersource & tokenized credit cards. The token is new each time.

I'm trying to find a way to store the token from the request and reference it to assert it's correct.

Example of the request:

request:
body:
accountRegistrationPreferences: {email: ''}
paymentDetails: Array(1)
0:
billingAddress: {address: {…}, contactInfo: {…}, personalInfo: {…}}
cardId: "eusercc42210010"
tokenDetails:
referenceId: "bcc8c381-79d6-4a83-a10a-d67e2d585268"
token:

"eyJraWQiOiIwOFJORkptMWFIVlhhZUhRaUJrNHZNRFF1MGt3WW9kNCIsImFsZyI6IlJTMjU2In0.eyJkYXRhIjp7ImV4cGlyYXRpb25ZZWFyIjoiMjAzMCIsImV4cGlyYXRpb25Nb250aCI6IjAzIn0sImlzcyI6IkZsZXgvMDgiLCJleHAiOjE2NDQ0MzE2ODQsInR5cGUiOiJtZi0wLjExLjAiLCJpYXQiOjE2NDQ0MzA3ODQsImp0aSI6IjFFNVpSSEQzTFBaUzM0NUdIVVVUUjJQRjdFNzBZSDlKN1dTQjRTWEhTVEJEN08xTFRFUzg2MjA0MDk0NEFBNjIiLCJjb250ZW50Ijp7InBheW1lbnRJbmZvcm1hdGlvbiI6eyJjYXJkIjp7ImV4cGlyYXRpb25ZZWFyIjp7InZhbHVlIjoiMjAzMCJ9LCJzZWN1cml0eUNvZGUiOnt9LCJleHBpcmF0aW9uTW9udGgiOnsidmFsdWUiOiIwMyJ9fX19fQ.bCR73pMD9eXILtZHQRrmqgzcLqI_QCTEVtnQXNPJLOk-RxMUar8LbC1BS59G6FpynCI2rvJVMPixjtes2WRcnM77cjOlTarNM4-VnAJnqKluXy2jx5Hgtn_OrT7aSaS8NOoSyYzwPFlbkqsBMV5oT5kmiHZ8Qn4qBnga8sEYmPFgzoAUUnQ6uWLN1ZkZnKCO8uizZ_HaKUjdUQCyRzgWbtKfTctD9aAi5AcSNgAVbWTV_gt155jFa11v8mLF4iaqA3bLdJfEh4lu9HxB17sOShZBoZvxEQ3fN8gDkk4f56VlswB-aN3J5QFI7me36pgwY5khAhYrFma1o79V-b2KYw"

type: "tokenizedCreditCard"

Here's the Cypress test

  it("User clicks confirm & pay button to complete order", () => {
cy.intercept("/api/checkout/payandcommit?*").as("placeOrder");
cy.placeOrderAndPay();
cy.wait("@placeOrder").then((interception) => {
  console.log(interception);
  // Order status should equal 200
  cy.wrap(interception.response.statusCode).should("eq", 200);
  // Check payment details card type
  cy.wrap(interception.request.body.paymentDetails[0].type).should(
    "include",
    "tokenizedCreditCard"
  );
  cy.wrap(
    interception.request.body.paymentDetails[0].tokenDetails.token
  ).should("include", token);
  // Check request to ensure delivery charge is passed at £0 due to Unlimited membership.
  cy.wrap(
    interception.response.body.response.order.orderPriceInfo.shipping
  ).should("eq", 0);
  // Ensure standard delivery is returned in the order response.
  cy.wrap(
    interception.response.body.response.order.shippingDetails[0]
      .shippingMethod.type
  ).should("include", "standard");
});

});

This is the part I'm struggling with:

cy.wrap(
interception.request.body.paymentDetails[0].tokenDetails.token).should("include", token);

How can I store the token value that's changed each time so I can assert on it?

Is this possible? Any help would be amazing, I'm a bit of a doob and learning.

Body:
To test that the response has a token property,

cy.wrap(interception.request.body.paymentDetails[0].tokenDetails)
  .should('have.property', 'token')
//or
cy.wrap(interception.request.body.paymentDetails[0])
  .should('have.deep.property', 'token')  // this assertion searches the object

To store the token an alias might be used

cy.wrap(interception.request.body.paymentDetails[0].tokenDetails.token)
  .as('token')

// Later in test
cy.get('@token').then(token => {
  expect(token).to.eq(expectedToken)
})

The token alias gets a new value every time you use .as('token'), so there's no problem with the changing token value.


问:
Retrieve child entry from Firebase Realtime Database without []. - Swift 5
I'm a little stuck with something small but that is giving me some headaches! I have a Realtime Database and I am able to retrieve the information I need from it. My only problem is that instead of printing for example (ex.: 200) is printing (ex.: [200])!

This is my code:

```<code>func readData() {

  FirebaseDatabase.Database.database().reference().child("Available_Funds").observeSingleEvent(of: .value, with: { snapshot in
            guard let value = snapshot.value as? [String: Any] else {
                return
            }
            let amountWallet = value.values
            print(amountWallet)
            self.currentBalanceLabel.text = "$" + "\(amountWallet)"
            print("\(value)")
        })
    }
</code>```

Right now what I get printed with this code is $[200] for example, instead of just $200, which is what I intend to get.

Tried looking online, but no luck with this! Does someone know how to remove these square brackets from printing?

答:
values is an Array -- thus the []. When you say value.values, you're asking for all of the values of the key/value pairs in snapshot.value.

If you intend to get a single value from it, you would use amountWallet[0] to get the first element. Keep in mind that this will crash if amountWallet has 0 elements (arrays are zero indexed).

amountWallet.first will give you an Optional that will be safe to use, but you would need to unwrap it for printing:

```<code>let amountWallet = value.values
if let singleAmount = amountWallet.first {
  print(singleAmount)
  self.currentBalanceLabel.text = "$" + "\(singleAmount)"
}

</code>```

Body:
I'm a little stuck with something small but that is giving me some headaches! I have a Realtime Database and I am able to retrieve the information I need from it. My only problem is that instead of printing for example (ex.: 200) is printing (ex.: [200])!

This is my code:

func readData() {

  FirebaseDatabase.Database.database().reference().child("Available_Funds").observeSingleEvent(of: .value, with: { snapshot in
            guard let value = snapshot.value as? [String: Any] else {
                return
            }
            let amountWallet = value.values
            print(amountWallet)
            self.currentBalanceLabel.text = "$" + "\(amountWallet)"
            print("\(value)")
        })
    }

Right now what I get printed with this code is $[200] for example, instead of just $200, which is what I intend to get.

Tried looking online, but no luck with this! Does someone know how to remove these square brackets from printing?

Body:
values is an Array -- thus the []. When you say value.values, you're asking for all of the values of the key/value pairs in snapshot.value.

If you intend to get a single value from it, you would use amountWallet[0] to get the first element. Keep in mind that this will crash if amountWallet has 0 elements (arrays are zero indexed).

amountWallet.first will give you an Optional that will be safe to use, but you would need to unwrap it for printing:

let amountWallet = value.values
if let singleAmount = amountWallet.first {
  print(singleAmount)
  self.currentBalanceLabel.text = "$" + "\(singleAmount)"
}


问:
Why is pd.to_datetime() only changing type if utc is True?
After loading my csv file into my notebook in VS Code i wanted to change the columns type from object to datetime for some columns. So i did the following:

object values of columns

These are example values in the columns.

```<code>my_col_1 -> 2022-02-07 20:19:04+01:00
my_col_2 -> 2020-10-27
my_col_3 -> 2020-10-27 16:00:00+01:00
my_col_4 -> 2020-10-27 18:00:00+01:00
</code>```

check

```<code>df_example.dtypes

my_col_1 object
my_col_2 object
my_col_3 object
my_col_4 object
</code>```

convert

```<code>format_1 = '%Y-%m-%d %H:%M:%S'
format_2 = '%Y-%m-%d'

df_example['my_col_1'] = pd.to_datetime(df_example['my_col_1'], format=format_1,
    exact=True, errors='raise', utc=False)

df_example['my_col_2'] = pd.to_datetime(df_example['my_col_2'], format=format_2,
        exact=True, errors='raise', utc=False)

df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=False)

df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=False)
</code>```

check

After converting the columns i wanted to check if everything worked out fine.

```<code>df_example.dtypes

my_col_1 datetime64[ns, pytz.FixedOffset(60)]
my_col_2 datetime64[ns]
my_col_3 object
my_col_4 object
</code>```

This is strange. It seems my_col_3 and my_col_4 were not converted. But at the same time no Issue or Error was raised also while processing the code. my_col_3 and my_col_4 have the exact same format as my_col_1, yet they were not converted.

second approach

lets change the utc=Falseto utc=True

```<code>df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=True)

df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=True)
</code>```

check

lets check again.

```<code>df_example.dtypes

my_col_1 datetime64[ns, pytz.FixedOffset(60)]
my_col_2 datetime64[ns]
my_col_3 datetime64[ns, UTC]
my_col_4 datetime64[ns, UTC]
</code>```

now i have

my_col_1 with UTC+01:00

my_col_3 with UTC+00:00 (turns 15:00:00 to 14:00:00 for example)

my_col_4 with UTC+00:00 (the same)

Question

This is strange. I do not want my_col_3 and my_col_4 to convert to the  UTC+00:00 Timezone because i live in UTC+01:00.

Do i have to introduce another process step and re-apply my Timezone once again to these columns? But it seems redundant. Why not simply use the timezone already given in the columns like pandas does in my_col_1? Can i tell pd.to_datetime() what my timezone is? like utc=Truebut with tz=01:00?

答:
So here is my Solution. Converting it with dt.tz_convert('Europe/Berlin') does the job. So i guess there is no way around to just take the already given +01:00 value. Turn the Column with to_datetime to UTC +00:00and afterwards you have to convert it to your Timezone again.

```<code>df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=True).dt.tz_convert('Europe/Berlin')

df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=True).dt.tz_convert('Europe/Berlin')
</code>```

now my columns have changed into datetime with right Timezone

```<code>df_example.dtypes

my_col_3 datetime64[ns, Europe/Berlin]
my_col_4 datetime64[ns, Europe/Berlin]
</code>```

Body:
After loading my csv file into my notebook in VS Code i wanted to change the columns type from object to datetime for some columns. So i did the following:

object values of columns

These are example values in the columns.

my_col_1 -> 2022-02-07 20:19:04+01:00
my_col_2 -> 2020-10-27
my_col_3 -> 2020-10-27 16:00:00+01:00
my_col_4 -> 2020-10-27 18:00:00+01:00

check

df_example.dtypes

my_col_1 object
my_col_2 object
my_col_3 object
my_col_4 object

convert

format_1 = '%Y-%m-%d %H:%M:%S'
format_2 = '%Y-%m-%d'

df_example['my_col_1'] = pd.to_datetime(df_example['my_col_1'], format=format_1,
    exact=True, errors='raise', utc=False)

df_example['my_col_2'] = pd.to_datetime(df_example['my_col_2'], format=format_2,
        exact=True, errors='raise', utc=False)

df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=False)

df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=False)

check

After converting the columns i wanted to check if everything worked out fine.

df_example.dtypes

my_col_1 datetime64[ns, pytz.FixedOffset(60)]
my_col_2 datetime64[ns]
my_col_3 object
my_col_4 object

This is strange. It seems my_col_3 and my_col_4 were not converted. But at the same time no Issue or Error was raised also while processing the code. my_col_3 and my_col_4 have the exact same format as my_col_1, yet they were not converted.

second approach

lets change the utc=Falseto utc=True

df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=True)

df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=True)

check

lets check again.

df_example.dtypes

my_col_1 datetime64[ns, pytz.FixedOffset(60)]
my_col_2 datetime64[ns]
my_col_3 datetime64[ns, UTC]
my_col_4 datetime64[ns, UTC]

now i have

my_col_1 with UTC+01:00

my_col_3 with UTC+00:00 (turns 15:00:00 to 14:00:00 for example)

my_col_4 with UTC+00:00 (the same)

Question

This is strange. I do not want my_col_3 and my_col_4 to convert to the  UTC+00:00 Timezone because i live in UTC+01:00.

Do i have to introduce another process step and re-apply my Timezone once again to these columns? But it seems redundant. Why not simply use the timezone already given in the columns like pandas does in my_col_1? Can i tell pd.to_datetime() what my timezone is? like utc=Truebut with tz=01:00?

Body:
So here is my Solution. Converting it with dt.tz_convert('Europe/Berlin') does the job. So i guess there is no way around to just take the already given +01:00 value. Turn the Column with to_datetime to UTC +00:00and afterwards you have to convert it to your Timezone again.

df_example['my_col_3'] = pd.to_datetime(df_example['my_col_3'],format=format_1,
        exact=True, errors='raise', utc=True).dt.tz_convert('Europe/Berlin')

df_example['my_col_4'] = pd.to_datetime(df_example['my_col_4'],format=format_1,
        exact=True, errors='raise', utc=True).dt.tz_convert('Europe/Berlin')

now my columns have changed into datetime with right Timezone

df_example.dtypes

my_col_3 datetime64[ns, Europe/Berlin]
my_col_4 datetime64[ns, Europe/Berlin]


问:
Cost must be multiple by 5
I am working small application with basic CRUD operation and I have Product Model.
In this model I have something like

```<code>public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int amountAvailable { get; set; }
        public double cost { get; set; }

        [ForeignKey(nameof(User))]
        public int UserId { get; set; }
        public User Users { get; set; }

    }
</code>```

Right now, I need some shortcut or some hack how to make cost (cost of the product), but it should be a multiple of 5, meaning the price can be 5,10,15,20,25,30... etc.
Is there anything which I can force user to put price something like thiss?
I try with [DataAnnotation] and using Range but I think this will not work.

答:
Try:

```<code>public class MultipleOf5Attribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return ((int)value) % 5 == 0;
    }
}
</code>```

use the decimal instead of the int

Title: Cost must be multiple by 5

Body:
I am working small application with basic CRUD operation and I have Product Model.
In this model I have something like

public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int amountAvailable { get; set; }
        public double cost { get; set; }

        [ForeignKey(nameof(User))]
        public int UserId { get; set; }
        public User Users { get; set; }

    }

Right now, I need some shortcut or some hack how to make cost (cost of the product), but it should be a multiple of 5, meaning the price can be 5,10,15,20,25,30... etc.
Is there anything which I can force user to put price something like thiss?
I try with [DataAnnotation] and using Range but I think this will not work.

Body:
Try:

public class MultipleOf5Attribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return ((int)value) % 5 == 0;
    }
}

use the decimal instead of the int


问:
How can I wrap the content using a permalink in a foreach loop
How can I wrap the content in the overlay div with a permalink that corresponds to the category. I want the image to be clickable and also pull the category name with the matching image. I want this to be dynamic in the event new categories are added.</p>
```<code><?php
/**
 *
 * Catergory Display
 *
 */

$categories = get_categories( array(
    'orderby' => 'name',
    'order'   => 'ASC',
    'hide_empty'      => false,
) );

 ?>

<div class="container">
    <div class="row">

 <?php

foreach( $categories as $category ) {
    $image = get_field('category_image', 'category_' . $category->term_id);

    $size = 'featured-thumbnail'; // (thumbnail, medium, large, full or custom size)
    $cat_link = get_category_link($category->cat_ID);

     ?>

    <div class="category-holder col-lg-4 col-md-6 col-sm-12 ">
            <div class="category-display-img">

                <?php echo wp_get_attachment_image( $image, $size ); ?>
                <a href="<?php echo esc_url( get_permalink($cat_link) )?>">
            <div class="overlay"><?php echo '<a class="" href="'.$cat_link.'">'.$category->name.'</a>'; // category link ?></div>
                </a>
            </div>

    </div>

           <?php
    // echo '```';
    // print_r($cat_link);
    // wp_die();
} ?>

   </div>
</div>
</code>```

答:
You can wrap the anchor tag around the div with the overlay class.

Delete this part

```<code><a href="<?php echo esc_url( get_permalink($cat_link) )?>">
            <div class="overlay"><?php echo '<a class="" href="'.$cat_link.'">'.$category->name.'</a>'; // category link ?></div>
                </a>
</code>```

And use this in its place

">

        <?php echo $category->name ?>

```

Body:
How can I wrap the content in the overlay div with a permalink that corresponds to the category. I want the image to be clickable and also pull the category name with the matching image. I want this to be dynamic in the event new categories are added.

<?php
/**
 *
 * Catergory Display
 *
 */

$categories = get_categories( array(
    'orderby' => 'name',
    'order'   => 'ASC',
    'hide_empty'      => false,
) );

 ?>

 <?php

foreach( $categories as $category ) {
    $image = get_field('category_image', 'category_' . $category->term_id);

    $size = 'featured-thumbnail'; // (thumbnail, medium, large, full or custom size)
    $cat_link = get_category_link($category->cat_ID);

     ?>

                <?php echo wp_get_attachment_image( $image, $size ); ?>
                <a href="<?php echo esc_url( get_permalink($cat_link) )?>">

<?php echo ''.$category->name.''; // category link ?>

           <?php
    // echo '
';
    // print_r($cat_link);
    // wp_die();
} ?>

Body:
You can wrap the anchor tag around the div with the overlay class.

Delete this part

<a href="<?php echo esc_url( get_permalink($cat_link) )?>">
            <div class="overlay"><?php echo '<a class="" href="'.$cat_link.'">'.$category->name.'</a>'; // category link ?></div>
                </a>

And use this in its place

<a href="<?php echo $cat_link ?>">
    <div class="overlay">
        <?php echo $category->name ?>
    </div>
</a>


问:
How to install MongoDB 5.0.3 on Linux Mint 19+
I want to install MongoDB 5.0.3 on Linux Mint 19.3.

I use these instructions which work on Ubuntu 20.04:

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add

sudo apt-get install gnupg

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

sudo apt-get update

sudo apt-get install -y mongodb-org

However, even after installing this, I cannot start the Mongo daemon with sudo systemctl start mongod (error: mongod.service not found).

And when I start mongo, it shows an older version:

How can I install MongoDB 5.0.3 on Linux Mint 19?

答: Linux Mint 19.3 is based on Ubuntu Bionic (18.04), not Focal (20.04). That is probably why you are having issues.  Select the command for the bionic install.  See here</p>


问:
Accessing a float value in AsyncTask
Here is a pseudo code :

```
class MoWeFi extends Activity</p>

```    static TouchSurfaceView TSV;
    static DrawRenderer mRenderer;
    static UserInterface mUI;
    DownloadData mDD = new DownloadData();
    static float zoom = 1.f;

    mDD.execute();
    mUI = new UserInterface();
    setContentView(mUI);
```

<p>class UserInterface extends LinearLayout
    MoWeFi.TSV = new TouchSurfaceView(context);
    MoWeFi.mRenderer = new DrawRenderer(context);
    MoWeFi.TSV.setRenderer(MoWeFi.mRenderer);
    MoWeFi.TSV.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    this.addView(MoWeFi.TSV);</p>

```    TextView tv = new TextView(context);
    this.addView(tv);

    TextView tv2 = new TextView(context);
    this.addView(tv2);
```

<p>class DownloadData extends AsyncTask
    protected Void doInBackground(){
        do{
        this.publishProgress();
        try{Thread.sleep(1000);catch (InterruptedException e){}
        }while(running)
    }
    @Override
    protected void onProgressUpdate(){
    //...
    MoWeFi.TSV.requestRender();
    MoWeFi.mUI.tv.setText("zoom="+MoWeFi.zoom); // IT DOES NOT WORK !!! ALWAYS GET 1.f.
    }</p>

<p>class TouchSurfaceView extends GLSurfaceView
    gl.glTranslatef(0, 0, -1.f / MoWeFi.zoom); // IT WORKS !!!</p>

<p>class DrawRenderer implements GLSurfaceView.Renderer
    //Pinch-zoom
    ...
    MoWeFi.zoom *= detector.getScaleFactor();
        MoWeFi.zoom = Math.max(0.5f, Math.min(MoWeFi.zoom, 5.0f));</p>

<code>MoWeFi.mUI.tv2.setText("zoom="+MoWeFi.zoom); // IT WORKS !!!
</code>```

So no error whatsoever. Just not able to access my zoom variable everywhere.
I am new to Java, I am surely missing important concept.

EDIT add float in the first lines

EDIT 2 add publishProgress in the asyncTask

EDIT 3 logcat shows nothing

答: change this public static zoom = 1.f; by public static float zoom = 1.f;

ContentLicense: CC BY-SA 3.0

Title: Accessing a float value in AsyncTask

Body:
Here is a pseudo code :

class MoWeFi extends Activity

    static TouchSurfaceView TSV;
    static DrawRenderer mRenderer;
    static UserInterface mUI;
    DownloadData mDD = new DownloadData();
    static float zoom = 1.f;

    mDD.execute();
    mUI = new UserInterface();
    setContentView(mUI);

class UserInterface extends LinearLayout
    MoWeFi.TSV = new TouchSurfaceView(context);
    MoWeFi.mRenderer = new DrawRenderer(context);
    MoWeFi.TSV.setRenderer(MoWeFi.mRenderer);
    MoWeFi.TSV.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    this.addView(MoWeFi.TSV);

    TextView tv = new TextView(context);
    this.addView(tv);

    TextView tv2 = new TextView(context);
    this.addView(tv2);

class DownloadData extends AsyncTask
    protected Void doInBackground(){
        do{
        this.publishProgress();
        try{Thread.sleep(1000);catch (InterruptedException e){}
        }while(running)
    }
    @Override
    protected void onProgressUpdate(){
    //...
    MoWeFi.TSV.requestRender();
    MoWeFi.mUI.tv.setText("zoom="+MoWeFi.zoom); // IT DOES NOT WORK !!! ALWAYS GET 1.f.
    }

class TouchSurfaceView extends GLSurfaceView
    gl.glTranslatef(0, 0, -1.f / MoWeFi.zoom); // IT WORKS !!!

class DrawRenderer implements GLSurfaceView.Renderer
    //Pinch-zoom
    ...
    MoWeFi.zoom *= detector.getScaleFactor();
        MoWeFi.zoom = Math.max(0.5f, Math.min(MoWeFi.zoom, 5.0f));

MoWeFi.mUI.tv2.setText("zoom="+MoWeFi.zoom); // IT WORKS !!!

So no error whatsoever. Just not able to access my zoom variable everywhere.
I am new to Java, I am surely missing important concept.

EDIT add float in the first lines

EDIT 2 add publishProgress in the asyncTask

EDIT 3 logcat shows nothing


问:
Fill Down Formula while ignoring empty cells- Google Scripts
I am trying to write a script that will replace the following formula:

=ARRAYFORMULA(IF((BM3:BM <> "") * (BN3:BN <> ""), BM3:BM + BN3:BN,))

This is where I am at so far:

```<code>function Formula_Columns() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  ss.getRange("BP3").setFormula("=BM3 + BN3");
  var lr = ss.getLastRow();
  var fillDownRange = ss.getRange(3,68,lr-2);
  ss.getRange("BP3").copyTo(fillDownRange);
}
</code>```

What I would like to happen is when the date is entered into column BM the formula will combine the date in column BM with the time set in column BN and place it into column BP.  I need the script to add the function into BP only when a cell in BM has a date in it.  As the script is written now, it enters 12/30/1899 0:00:00 if there is no date and time entered in column BM & BN respectively. (See screenshot below)

I would appreciate some help with this.  Thank you in advance.

答:
There are three ways I see how to solve this. See the methods below:

Script:

```<code>// Copying just the displayed values and returning the combined values
function writeValuesOnly() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var dates = ss.getRange(3, 65, lr - 2, 2).getDisplayValues();
  dates = dates.map(row => {
    // if BM and BN is present
    if(row[0] && row[1])
      return [row[0] + ' ' + row[1]];
    // else, return blank
    else
      return [''];
  });
  ss.getRange(3, 68, dates.length, dates[0].length).setValues(dates);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}

// Writing the ARRAYFORMULA on BP3
// Then set the formatting of the column to Date Time
function writeArrayFormula() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  ss.getRange(3, 68).setFormula(`=ARRAYFORMULA(IF((BM3:BM <> "") * (BN3:BN <> ""), BM3:BM + BN3:BN,))`);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}

// Copying formula to all cells in the column until last row of column BM
function writeFormulaPerCell() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var colValues = ss.getRange("BM3:BM" + lr).getValues();
  var colLastRow = lr - colValues.reverse().findIndex(cell => cell[0] != '');
  // if BM and BN is present, populate
  ss.getRange(3, 68, colLastRow - 2, 1).setFormulaR1C1(`=IF(AND(R[0]C[-3] <> "", R[0]C[-2] <> ""),  R[0]C[-3] + R[0]C[-2], "")`);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}
</code>```

Comparison:

Note:

Using writeValuesOnly will not automatically update the value when BM and BN is updated.

If you want to use writeFormulaPerCell, you need to use setFormulaR1C1 instead since when it is copied to other rows/columns, the formula will automatically adjust based on the range.

Not using setNumberFormat (or not formatting the range output) might yield unexpected results such as showing float data type instead.

References:

setNumberFormaat

setFormulaR1C1

Body:
I am trying to write a script that will replace the following formula:

=ARRAYFORMULA(IF((BM3:BM <> "") * (BN3:BN <> ""), BM3:BM + BN3:BN,))

This is where I am at so far:

function Formula_Columns() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  ss.getRange("BP3").setFormula("=BM3 + BN3");
  var lr = ss.getLastRow();
  var fillDownRange = ss.getRange(3,68,lr-2);
  ss.getRange("BP3").copyTo(fillDownRange);
}

What I would like to happen is when the date is entered into column BM the formula will combine the date in column BM with the time set in column BN and place it into column BP.  I need the script to add the function into BP only when a cell in BM has a date in it.  As the script is written now, it enters 12/30/1899 0:00:00 if there is no date and time entered in column BM & BN respectively. (See screenshot below)

I would appreciate some help with this.  Thank you in advance.

Body:
There are three ways I see how to solve this. See the methods below:

Script:

// Copying just the displayed values and returning the combined values
function writeValuesOnly() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var dates = ss.getRange(3, 65, lr - 2, 2).getDisplayValues();
  dates = dates.map(row => {
    // if BM and BN is present
    if(row[0] && row[1])
      return [row[0] + ' ' + row[1]];
    // else, return blank
    else
      return [''];
  });
  ss.getRange(3, 68, dates.length, dates[0].length).setValues(dates);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}

// Writing the ARRAYFORMULA on BP3
// Then set the formatting of the column to Date Time
function writeArrayFormula() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  ss.getRange(3, 68).setFormula(`=ARRAYFORMULA(IF((BM3:BM <> "") * (BN3:BN <> ""), BM3:BM + BN3:BN,))`);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}

// Copying formula to all cells in the column until last row of column BM
function writeFormulaPerCell() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();
  var colValues = ss.getRange("BM3:BM" + lr).getValues();
  var colLastRow = lr - colValues.reverse().findIndex(cell => cell[0] != '');
  // if BM and BN is present, populate
  ss.getRange(3, 68, colLastRow - 2, 1).setFormulaR1C1(`=IF(AND(R[0]C[-3] <> "", R[0]C[-2] <> ""),  R[0]C[-3] + R[0]C[-2], "")`);
  // make sure to format the whole column to date time
  ss.getRange(3, 68, lr - 2, 1).setNumberFormat("MM/dd/yyyy HH:mm:ss")
}

Comparison:

Note:

Using writeValuesOnly will not automatically update the value when BM and BN is updated.

If you want to use writeFormulaPerCell, you need to use setFormulaR1C1 instead since when it is copied to other rows/columns, the formula will automatically adjust based on the range.

Not using setNumberFormat (or not formatting the range output) might yield unexpected results such as showing float data type instead.

References:

setNumberFormaat

setFormulaR1C1


Title: How to get row number according to row partitioning in r

Body:
I am trying to give ranknumber according to qtr wise here is the inpt and output

INPUT:-

year   qtr  month   day          salry
2001    q1  jan     1           1000.00
2001    q1  jan     2           1500.00
2001    q1  feb     1           3000.00
2001    q1  feb     2           2100.00
2001    q1  march   1          1000.00
2001    q1  march   2          1200.00
2001    q2  april   1          1300.00
2001    q2  april   2          1900.00
2001    q2  may     1          1000.00
2001    q2  may     2          1800.00
2001    q2  june    1          1600.00
2001    q2  june    2          1900.00
2001    q3  july    1          2000.00
2001    q3  july    2          1800.00
2001    q3  august  1          2100.00
2001    q3  august  2          1500.00
2001    q3  sept    1          1700.00
2001    q3  sept    2          1400.00
2001    q4  oct     1          1300.00
2001    q4  oct     2          1200.00
2001    q4  nov     1          1100.00
2001    q4  nov     2          1700.00
2001    q4  dec     1          1000.00
2001    q4  dec     2          1700.00

OUTPUT:-

year    qtr     month  day  salry      rank
2001    q1      feb     1   3000.00     1
2001    q1      feb     2   2100.00     2
2001    q1      jan     2   1500.00     3
2001    q1      march   2   1200.00     4
2001    q1      jan     1   1000.00     5
2001    q1      march   1   1000.00     6
2001    q2      april   2   1900.00     1
2001    q2      june    2   1900.00     2
2001    q2      may     2   1800.00     3
2001    q2      june    1   1600.00     4
2001    q2      april   1   1300.00     5
2001    q2      may     1   1000.00     6
2001    q3      august  1   2100.00     1
2001    q3      july    1   2000.00     2
2001    q3      july    2   1800.00     3
2001    q3      sept    1   1700.00     4
2001    q3      august  2   1500.00     5
2001    q3      sept    2   1400.00     6
2001    q4      nov     2   1700.00     1
2001    q4      dec     2   1700.00     2
2001    q4      oct     1   1300.00     3
2001    q4      oct     2   1200.00     4
2001    q4      nov     1   1100.00     5
2001    q4      dec     1   1000.00     6

Body:
This should work using tidyverse packages

library(tidyverse)

dat <- tibble::tribble(~year,~qtr, ~month, ~salry,
                       2001, 'q1', 'jan 1', 1000.00,
                       2001, 'q1', 'jan 2', 1500.00,
                       2001, 'q1', 'feb 1', 3000.00,
                       2001, 'q1', 'feb 2', 2100.00,
                       2001, 'q1', 'march 1', 1000.00,
                       2001, 'q1', 'march 2', 1200.00,
                       2001, 'q2', 'april 1', 1300.00,
                       2001, 'q2', 'april 2', 1900.00,
                       2001, 'q2', 'may 1', 1000.00,
                       2001, 'q2', 'may 2', 1800.00,
                       2001, 'q2', 'june 1', 1600.00,
                       2001, 'q2', 'june 2', 1900.00,
                       2001, 'q3', 'july 1', 2000.00,
                       2001, 'q3', 'july 2', 1800.00,
                       2001, 'q3', 'august 1', 2100.00,
                       2001, 'q3', 'august 2', 1500.00,
                       2001, 'q3', 'sept 1', 1700.00,
                       2001, 'q3', 'sept 2', 1400.00,
                       2001, 'q4', 'oct 1', 1300.00,
                       2001, 'q4', 'oct 2', 1200.00,
                       2001, 'q4', 'nov 1', 1100.00,
                       2001, 'q4', 'nov 2', 1700.00,
                       2001, 'q4', 'dec 1', 1000.00,
                       2001, 'q4', 'dec 2', 1700.00
) %>%
  dplyr::group_by(qtr) %>%
  dplyr::arrange(qtr, salry) %>%
  dplyr::mutate(rank = dplyr::row_number())


问:
Spring Boot: Storing Enum Integer Constant value to MySQL Database Table
I'm a beginner in Spring Boot and Java and having following issues while trying to store VoteType Enum Constant value in the database as Integer.

In MySQL DB, value for DOWNVOTE and UPVOTE is being stored as 0 and 1 respectively instead of -1 and 1.

I am unable to print the Integer Constant value of DOWNVOTE and UPVOTE. I've tried to do System.out.println(VoteType.UPVOTE.ordinal()), but it still prints UPVOTE instead of it's Integer value i.e. 1

Here's my code:

VoteType.java

```<code>public enum VoteType {
     DOWNVOTE(-1), UPVOTE(1);

    private final int direction;

    VoteType(int direction) {
        this.direction= direction;
    }

    public Integer getDirection() {
        return direction;
    }

}
</code>```

VoteService.java

```<code>@Service
@Transactional
@AllArgsConstructor
public class VoteService {

    private final VoteRepository voteRepository;
    private final PostRepository postRepository;
    private final AuthService authService;

    @Transactional
    public void vote(VoteDto voteDto) {
        Post post = postRepository.findById(voteDto.getPostId())
                .orElseThrow(() -> new PostNotFoundException("Post Not Found with ID - " + voteDto.getPostId()));
        Optional<Vote> voteByPostAndUser =
                voteRepository.findTopByPostAndUserOrderByIdDesc(post,
                                                                 authService.getCurrentUser());
        if (voteByPostAndUser.isPresent() &&
                voteByPostAndUser.get().getType()
                        .equals(voteDto.getVoteType())) {
            throw new MyRedditException("You have already "
                    + voteDto.getVoteType() + "'d for this post");
        }
        if (UPVOTE.equals(voteDto.getVoteType())) {
            post.setVoteCount(post.getVoteCount() + 1);
        } else {
            post.setVoteCount(post.getVoteCount() - 1);
        }

        voteRepository.save(mapDtoToVote(voteDto, post));

        postRepository.save(post);
    }

    private Vote mapDtoToVote(VoteDto voteDto, Post post) {
        return Vote.builder()
                .type(voteDto.getVoteType())
                .post(post)
                .user(authService.getCurrentUser())
                .build();
    }
}

</code>```

VoteController.java

```<code>@RestController
@RequestMapping("/api/votes/")
@AllArgsConstructor
public class VoteController {
    private final VoteService voteService;

    @PostMapping
    public ResponseEntity<Void> save(@RequestBody VoteDto voteDto){
        voteService.vote(voteDto);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

}
</code>```

VoteDto.java

```<code>@AllArgsConstructor
@NoArgsConstructor
@Data
public class VoteDto {
    private VoteType voteType;
    private Long postId;
}
</code>```

Vote.java

```<code>@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "vote")
public class Vote {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "type")
    private VoteType type;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id")
    private Post post;

}
</code>```

Screenshot of Vote Table where Type is getting stored as 0 and 1 instead of -1 and 1 for DOWNVOTE and UPVOTE respectively.

Please let me know if more detail is needed to answer this question. Thanks.

答:
Simply define type as Integer and translate to enum in get/set methods.</p>
```<code>@Column(name = "type")
private Integer type;

public VoteType getType() {
    return VoteType.fromValue(this.type);
}

public void setType(VoteType type) {
    this.type = type.getValue();
}
</code>```

Body:
I'm a beginner in Spring Boot and Java and having following issues while trying to store VoteType Enum Constant value in the database as Integer.

In MySQL DB, value for DOWNVOTE and UPVOTE is being stored as 0 and 1 respectively instead of -1 and 1.

I am unable to print the Integer Constant value of DOWNVOTE and UPVOTE. I've tried to do System.out.println(VoteType.UPVOTE.ordinal()), but it still prints UPVOTE instead of it's Integer value i.e. 1

Here's my code:

VoteType.java

public enum VoteType {
     DOWNVOTE(-1), UPVOTE(1);

    private final int direction;

    VoteType(int direction) {
        this.direction= direction;
    }

    public Integer getDirection() {
        return direction;
    }

}

VoteService.java

@Service
@Transactional
@AllArgsConstructor
public class VoteService {

    private final VoteRepository voteRepository;
    private final PostRepository postRepository;
    private final AuthService authService;

    @Transactional
    public void vote(VoteDto voteDto) {
        Post post = postRepository.findById(voteDto.getPostId())
                .orElseThrow(() -> new PostNotFoundException("Post Not Found with ID - " + voteDto.getPostId()));
        Optional<Vote> voteByPostAndUser =
                voteRepository.findTopByPostAndUserOrderByIdDesc(post,
                                                                 authService.getCurrentUser());
        if (voteByPostAndUser.isPresent() &&
                voteByPostAndUser.get().getType()
                        .equals(voteDto.getVoteType())) {
            throw new MyRedditException("You have already "
                    + voteDto.getVoteType() + "'d for this post");
        }
        if (UPVOTE.equals(voteDto.getVoteType())) {
            post.setVoteCount(post.getVoteCount() + 1);
        } else {
            post.setVoteCount(post.getVoteCount() - 1);
        }

        voteRepository.save(mapDtoToVote(voteDto, post));

        postRepository.save(post);
    }

    private Vote mapDtoToVote(VoteDto voteDto, Post post) {
        return Vote.builder()
                .type(voteDto.getVoteType())
                .post(post)
                .user(authService.getCurrentUser())
                .build();
    }
}

VoteController.java

@RestController
@RequestMapping("/api/votes/")
@AllArgsConstructor
public class VoteController {
    private final VoteService voteService;

    @PostMapping
    public ResponseEntity<Void> save(@RequestBody VoteDto voteDto){
        voteService.vote(voteDto);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

}

VoteDto.java

@AllArgsConstructor
@NoArgsConstructor
@Data
public class VoteDto {
    private VoteType voteType;
    private Long postId;
}

Vote.java

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Table(name = "vote")
public class Vote {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "type")
    private VoteType type;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id")
    private Post post;

}

Screenshot of Vote Table where Type is getting stored as 0 and 1 instead of -1 and 1 for DOWNVOTE and UPVOTE respectively.

Please let me know if more detail is needed to answer this question. Thanks.

Body:
Simply define type as Integer and translate to enum in get/set methods.

@Column(name = "type")
private Integer type;

public VoteType getType() {
    return VoteType.fromValue(this.type);
}

public void setType(VoteType type) {
    this.type = type.getValue();
}


问:
"psql: could not connect to server: Connection refused" Error when connecting to remote database
I am trying to connect to a Postgres database installed in a remote server using the following command:

psql -h host_ip -U db_username -d db_name

This is the error that occurs:

psql: could not connect to server: Connection refused
Is the server running on host "<host_ip>" and accepting
TCP/IP connections on port 5432?

Postgres installed version is 9.4.

Host operating system: Ubuntu 15.04

Client operating system: Centos 7

I already tried the following but the issue remains unresolved:

Edited pg_hba.conf file to include

host    all     all     0.0.0.0/0  md5

Edited 'postgresql.conf' and changed the listen parameter to

listen_addresses='*'

Restarted Postgres service.

Disabled firewall and iptables on host and client.

I checked by running the psql command locally and it worked.

I tried the second solution given in this question. Running nmap gave me the following output:

Starting Nmap 6.47 ( http://nmap.org ) at 2015-09-07 18:08 IST Nmap scan report for 10.17.250.250 Host is up (0.0000040s latency). Not shown: 997 closed ports PORT   STATE SERVICE 22/tcp open  ssh 25/tcp open  smtp 80/tcp open  http

Am I missing something? Hope someone can help.

答:
Step 1: edit file potgresql.conf

file location should be : etc/postgresql/10/main/

Look for:

#Connection Settings -

#listen_addresses = ''          # what IP address(es) to listen on;

remove # before listening addresses

add '*' :

listen_addresses = '*'

Step 2: edit file pg_hba.conf

file location should be : etc/postgresql/10/main/

add below given line at the end

host    all    all      0.0.0.0/0     md5

Step 3: restart postgres server

```<code>sudo /etc/init.d/postgresql restart
</code>```

Step 4: check postgres server status

```<code>sudo netstat -plunt |grep postgres
</code>```

Make sure you are using same port to access the DB

Body:
Step 1: edit file potgresql.conf

file location should be : etc/postgresql/10/main/

Look for:

#Connection Settings -

#listen_addresses = ''          # what IP address(es) to listen on;

remove # before listening addresses

add '*' :

listen_addresses = '*'

Step 2: edit file pg_hba.conf

file location should be : etc/postgresql/10/main/

add below given line at the end

host    all    all      0.0.0.0/0     md5

Step 3: restart postgres server

sudo /etc/init.d/postgresql restart

Step 4: check postgres server status

sudo netstat -plunt |grep postgres

Make sure you are using same port to access the DB


问:
foreach on parsing xml but shows only one record
```<code>foreach($xml1->results as $info) {
                    $title = $info->listing->title;
                    $favicon = $info->listing->favicon;

                    echo $favicon;
                    echo "<a href=".$redirect;
                    echo ">".$title."</a><BR>";

                }
</code>```

The output is all fine, but only showing one record.  What could be the problem.

XML Structure

```<code><listing>
   <title></title>
   <url></url>
   <description>[result-description]</description>
</listing>
</code>```

答:
Your code and question suggests that the $xml contains a tag at least two tags "results".

The simplexml ignores the root tag as being part of the object, it only includes the attributes.

so, if your xml looks like

```<code><results>
    <listing>
        <title></title>
        <favicon></favicon>
    </listing>
    <listing>
        <title></title>
        <favicon></favicon>
    </listing>
</results>
</code>```

the code should be

```<code>foreach($xml1->listing as $info)
</code>```

Body:
foreach($xml1->results as $info) {
                    $title = $info->listing->title;
                    $favicon = $info->listing->favicon;

                    echo $favicon;
                    echo "".$title."
";

                }

The output is all fine, but only showing one record.  What could be the problem.

XML Structure

<listing>
   <title></title>
   <url></url>
   <description>[result-description]</description>
</listing>

Body:
Your code and question suggests that the $xml contains a tag at least two tags "results".

The simplexml ignores the root tag as being part of the object, it only includes the attributes.

so, if your xml looks like

<results>
    <listing>
        <title></title>
        <favicon></favicon>
    </listing>
    <listing>
        <title></title>
        <favicon></favicon>
    </listing>
</results>

the code should be

foreach($xml1->listing as $info)


问:
Is enum { a } e = 1; valid?
A simple question: is enum { a } e = 1; valid?

In other words: does assigning a value, which isn't present in the set of values of enumeration constants, lead to well-defined behavior?

Demo:

```<code>$ gcc t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>

$ clang t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>

$ icc t0.c -std=c11 -pedantic -Wall -Wextra -c
t0.c(1): warning #188: enumerated type mixed with another type
# note: the same warning for enum { a } e = 0;

$ cl t0.c /std:c11 /Za /c
<nothing>
</code>```

答:
In short

The validity of enum { a } e = 1; is ensured for the particular value of 1, a combination of different reasons, based on the definition of enum types, conversion rules of compatible types,  and compatibility guarantees.

Spoiler alert: it's much more complex in C18 than the quote of any single paragraph (see my comment under the accepted answer).

Full explanation

I'll quote the C18 standard step by step (N2176 to be precise).  Highlights are from me.

First, we know that enum { a } is an integer type:

6.2.5. Types

16: An enumeration comprises a set of named integer constant values. Each distinct enumeration constitutes a different enumerated type.

17: The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types.

Then,  we can demonstrate that if enum { a } is an integer type "large enough" to hold 1, the assignment would valid (because there is no explicit statement of the contrary):

6.2.7 Compatible types and composite types

1:Two types have compatible type if their types are the same. (...)

6.3. Conversions

2: Unless explicitly stated otherwise, conversion of an operand value to a compatible type causes no change to the value or the representation.

6.7.2.2 Enumeration specifiers

4: Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

But is the type large enough? From here we deduct that the value of a is 0.  Since it's also the largest enum constant in the set, we can deduct that enum { a } is "at least" compatible with char:

6.7.2.2 Enumeration specifiers

3: (...) An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant.

In conclusion, the assignment is legal, because the litteral 1 is also compatible with char.

Beware of implementation dependent assumptions!

But be careful, such an integer assignment is not necessarily valid for whatever integer you choose:

```<code>enum { a } = INT_MAX;  // Implementation dependent, see J.3.9
enum { a, b=INT_MAX } = 1024;  // ok: b requires int as compatible type
</code>```

In the first case, the enum is only guaranteed to be compatible with char.  But we have no guarantee that it's compatible with an int:

J.3. Implementation-defined behavior

(...)
**J.3.9. Structures, unions, enumerations, and bit-fields

(...)

The integer type compatible with each enumerated type (6.7.2.2).

In the second case,  we used specification of an inteer value to force a compatible type with int.

Title: Is enum { a } e = 1; valid?

Body:
A simple question: is enum { a } e = 1; valid?

In other words: does assigning a value, which isn't present in the set of values of enumeration constants, lead to well-defined behavior?

Demo:

$ gcc t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>

$ clang t0.c -std=c11 -pedantic -Wall -Wextra -c
<nothing>

$ icc t0.c -std=c11 -pedantic -Wall -Wextra -c
t0.c(1): warning #188: enumerated type mixed with another type
# note: the same warning for enum { a } e = 0;

$ cl t0.c /std:c11 /Za /c
<nothing>

Body:
In short

The validity of enum { a } e = 1; is ensured for the particular value of 1, a combination of different reasons, based on the definition of enum types, conversion rules of compatible types,  and compatibility guarantees.

Spoiler alert: it's much more complex in C18 than the quote of any single paragraph (see my comment under the accepted answer).

Full explanation

I'll quote the C18 standard step by step (N2176 to be precise).  Highlights are from me.

First, we know that enum { a } is an integer type:

6.2.5. Types

16: An enumeration comprises a set of named integer constant values. Each distinct enumeration constitutes a different enumerated type.

17: The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types.

Then,  we can demonstrate that if enum { a } is an integer type "large enough" to hold 1, the assignment would valid (because there is no explicit statement of the contrary):

6.2.7 Compatible types and composite types

1:Two types have compatible type if their types are the same. (...)

6.3. Conversions

2: Unless explicitly stated otherwise, conversion of an operand value to a compatible type causes no change to the value or the representation.

6.7.2.2 Enumeration specifiers

4: Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

But is the type large enough? From here we deduct that the value of a is 0.  Since it's also the largest enum constant in the set, we can deduct that enum { a } is "at least" compatible with char:

6.7.2.2 Enumeration specifiers

3: (...) An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant.

In conclusion, the assignment is legal, because the litteral 1 is also compatible with char.

Beware of implementation dependent assumptions!

But be careful, such an integer assignment is not necessarily valid for whatever integer you choose:

enum { a } = INT_MAX;  // Implementation dependent, see J.3.9
enum { a, b=INT_MAX } = 1024;  // ok: b requires int as compatible type

In the first case, the enum is only guaranteed to be compatible with char.  But we have no guarantee that it's compatible with an int:

J.3. Implementation-defined behavior

(...)
**J.3.9. Structures, unions, enumerations, and bit-fields

(...)

The integer type compatible with each enumerated type (6.7.2.2).

In the second case,  we used specification of an inteer value to force a compatible type with int.


问:
Vue 3 defineProps with Types and ComponentObjectPropsOptions (like default or validator)
From within a setup method, using defineProps I can use

```<code>const props = defineProps<{tabs: Tab[]}> = ()
</code>```

which allows me to have the type Tab[] on props.tabs

however, if I want to specify ComponentObjectPropsOptions, I believe the syntax is

```<code>const props = defineProps = ({
  type: Array, //can not use Tab[] here
  required: true,
  validator: ...
})
</code>```

but with that syntax I lose my type on props.tabs :(

答:
You'll need to use the PropType utility to type cast your array.

https://vuejs.org/api/utility-types.html#proptype-t

const props = defineProps = ({
  type: Array as PropType<Tab[]>,
  required: true,
  validator: ...
})

```

Body:
From within a setup method, using defineProps I can use

const props = defineProps<{tabs: Tab[]}> = ()

which allows me to have the type Tab[] on props.tabs

however, if I want to specify ComponentObjectPropsOptions, I believe the syntax is

const props = defineProps = ({
  type: Array, //can not use Tab[] here
  required: true,
  validator: ...
})

but with that syntax I lose my type on props.tabs :(


问:
Call a function in it self?
I saw an example online that looks like this:

```<code> def DecimalToBinary(num):

      if num >= 1:
         DecimalToBinary(num // 2)
      print(num % 2, end = '')

print(DecimalToBinary(12))
</code>```

I'll be happy if someone explain it to me.

答:
It is called recursion. A type of concept of function calling itself. If it has no proper if statement that terminates the function itself, loop will not end or it will error. In your case it terminated.</p>
```<code>01100None
</code>```

Title: Call a function in it self?

Body:
I saw an example online that looks like this:

 def DecimalToBinary(num):

      if num >= 1:
         DecimalToBinary(num // 2)
      print(num % 2, end = '')

print(DecimalToBinary(12))

I'll be happy if someone explain it to me.

Body:
It is called recursion. A type of concept of function calling itself. If it has no proper if statement that terminates the function itself, loop will not end or it will error. In your case it terminated.

01100None


问:
Flutter ButtomNavigationBarItem add round circle and make it clickable
so, I am working on my ButtomNavigationBar which should include a rectangle for the icon in the center. I have already archived that. However, now I am facing one problems:

Sadly the shape and icon itself is not clickable. Nothing happens when I click on it (even when I try printing something to the console). It only switches the screen when clicking slightly outside of the shape. For me this seems like a "z-index" problem. Any idea on how I can solve this?

I also have tried to wrap my Container into a GestureDetector but that also does not work..

```<code>BottomNavigationBarItem(
    icon: GestureDetector(
    onTap: () =>  { onClicked },
    child:
        Container(
            // same code as below
        ),
    ),
    label: 'Add',
),
</code>```

This is my complete code:

BottomNavigation

```<code>class BottomNavigation extends StatelessWidget {
  int selectedIndex;
  ValueChanged<int> onClicked;
  BottomNavigation({Key? key, required this.selectedIndex, required this.onClicked}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      currentIndex: selectedIndex,
      selectedItemColor: AppColors.orange,
      onTap: onClicked,
      type: BottomNavigationBarType.fixed,
      showSelectedLabels: false,
      showUnselectedLabels: false,
      backgroundColor: AppColors.white,
      items: <BottomNavigationBarItem>[
        const BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.home),
          label: 'Home',
        ),
        const BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.search),
          label: 'Search',
        ),
        BottomNavigationBarItem(
          icon: Container(
            decoration: BoxDecoration(
              color: AppColors.orange,
              shape: BoxShape.circle,
            ),
            child: Padding(
                padding: const EdgeInsets.all(0.0),
                child: IconButton(
                  onPressed: () =>  { onClicked },
                    icon: Icon(CupertinoIcons.plus, color: AppColors.white)
                )
            ),
          ),
          label: 'Add',
        ),
        const BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.bell),
          label: 'Notifications',
        ),
        const BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.news),
          label: 'Blog',
        ),
      ],
    );
  }
}
</code>```

Home (where the BottomNavigation gets integrated):

```<code>class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int _selectedIndex = 0;

  final screens = [
    HomePage(),
    SearchPage(),
    ProductSubmitPage(),
    NotificationPage(),
    BlogPage()
  ];

  void onClicked(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: screens[_selectedIndex],
        bottomNavigationBar: BottomNavigation(
          selectedIndex: _selectedIndex,
          onClicked: onClicked,
        )
    );
  }
}
</code>```

This stack inspired my on how to add a shape to the icon: https://stackoverflow.com/a/67577496/9445999

UPDATE:
Here is my dartpad: https://dartpad.dev/?id=c42f306078c7ece655816482c5c0d413

Kind regards

答:
Your error is on the calling of your function.
You should be doing this like either one of this lines:

//Being 2 the index of this in the list
onPressed: () =>  onClicked(2),
onPressed: () {onClicked(2);},
```

I have no experience with this BottomNavigationBarItem so I don't know why it's behaving this way, but that would solve your problem.

Body:
so, I am working on my ButtomNavigationBar which should include a rectangle for the icon in the center. I have already archived that. However, now I am facing one problems:

Sadly the shape and icon itself is not clickable. Nothing happens when I click on it (even when I try printing something to the console). It only switches the screen when clicking slightly outside of the shape. For me this seems like a "z-index" problem. Any idea on how I can solve this?

I also have tried to wrap my Container into a GestureDetector but that also does not work..

BottomNavigationBarItem(
    icon: GestureDetector(
    onTap: () =>  { onClicked },
    child:
        Container(
            // same code as below
        ),
    ),
    label: 'Add',
),

This is my complete code:

BottomNavigation

class BottomNavigation extends StatelessWidget {
  int selectedIndex;
  ValueChanged<int> onClicked;
  BottomNavigation({Key? key, required this.selectedIndex, required this.onClicked}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      currentIndex: selectedIndex,
      selectedItemColor: AppColors.orange,
      onTap: onClicked,
      type: BottomNavigationBarType.fixed,
      showSelectedLabels: false,
      showUnselectedLabels: false,
      backgroundColor: AppColors.white,
      items: <BottomNavigationBarItem>[
        const BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.home),
          label: 'Home',
        ),
        const BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.search),
          label: 'Search',
        ),
        BottomNavigationBarItem(
          icon: Container(
            decoration: BoxDecoration(
              color: AppColors.orange,
              shape: BoxShape.circle,
            ),
            child: Padding(
                padding: const EdgeInsets.all(0.0),
                child: IconButton(
                  onPressed: () =>  { onClicked },
                    icon: Icon(CupertinoIcons.plus, color: AppColors.white)
                )
            ),
          ),
          label: 'Add',
        ),
        const BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.bell),
          label: 'Notifications',
        ),
        const BottomNavigationBarItem(
          icon: Icon(CupertinoIcons.news),
          label: 'Blog',
        ),
      ],
    );
  }
}

Home (where the BottomNavigation gets integrated):

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int _selectedIndex = 0;

  final screens = [
    HomePage(),
    SearchPage(),
    ProductSubmitPage(),
    NotificationPage(),
    BlogPage()
  ];

  void onClicked(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: screens[_selectedIndex],
        bottomNavigationBar: BottomNavigation(
          selectedIndex: _selectedIndex,
          onClicked: onClicked,
        )
    );
  }
}

This stack inspired my on how to add a shape to the icon: https://stackoverflow.com/a/67577496/9445999

UPDATE:
Here is my dartpad: https://dartpad.dev/?id=c42f306078c7ece655816482c5c0d413

Kind regards

Body:
Your error is on the calling of your function.
You should be doing this like either one of this lines:

//Being 2 the index of this in the list
onPressed: () =>  onClicked(2),
onPressed: () {onClicked(2);},

I have no experience with this BottomNavigationBarItem so I don't know why it's behaving this way, but that would solve your problem.


问:
React: check the pressed key on form submit
I am using React (and Material UI), and I am trying to submit a form. As default by pressing enter when focused on the text field, the form submits. I want it to only happen when I press the Submit button.

The form

```<code><Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
    <TextField
        margin="normal"
        required
        fullWidth
        id="title"
        label="Title"
        name="title"
        autoComplete="title"
        autoFocus
        defaultValue={title}
    />
    <TextArea setData={setData} data={JSON.parse(description)} />
    <Button
        type="submit"
        fullWidth
        variant="contained"
        sx={{ mt: 3, mb: 2 }}
    >
        Finish
    </Button>
    <Link href="/">
        Back
    </Link>
</Box>
</code>```

The submit function

```<code> const handleSubmit = async (e) =>
    {
        e.preventDefault();
        console.log(e)
        //
    }

</code>```

答:
This is default behavior since you have your code in a form. It shouldn't matter to you where the users cursor is. This is necessary for screen readers and for basic user experience.

To focus on the next field, the user should be able to tab to the next field.

e.preventDefault is to keep the page from reloading on submit.

Body:
I am using React (and Material UI), and I am trying to submit a form. As default by pressing enter when focused on the text field, the form submits. I want it to only happen when I press the Submit button.

The form

<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
    <TextField
        margin="normal"
        required
        fullWidth
        id="title"
        label="Title"
        name="title"
        autoComplete="title"
        autoFocus
        defaultValue={title}
    />
    <TextArea setData={setData} data={JSON.parse(description)} />
    <Button
        type="submit"
        fullWidth
        variant="contained"
        sx={{ mt: 3, mb: 2 }}
    >
        Finish
    </Button>
    <Link href="/">
        Back
    </Link>
</Box>

The submit function

 const handleSubmit = async (e) =>
    {
        e.preventDefault();
        console.log(e)
        //
    }


问:
Which Linux distribution has the most active/recent Ruby support?
I have installed Ubuntu 11.04 and tried to install Ruby as apt-get install ruby. The default version in repositories was 1.8.7, okay, install 1.9.2 manually. Then I'm going for rubygems, download tar file, install rubygems, try to install something with them, zlib-mistake appeared. Found the solution with rvm, didn't help. Now I'm stuck with broken gem command and useless rvm installed.

The question is - which Linux distribution is the most friendly for a Ruby beginner?

答:
The distribution shouldn't matter at all, if you're using RVM (strongly suggested). Otherwise, if you want to have the latest up-to-date packages (including ruby) you could turn to rolling release distros (such as Archlinux or Gentoo). You can always add other repositories to any distro, and get more updated packages this way, as others suggested for Ubuntu.

Update: It's been years since my original reply. Nowadays, with Docker, Podman and toolbx, the distro itself is even less relevant. With containers, one can set up an isolated Ruby environment and ensure developer-production parity.


问:
The documentation generated by open-api-catalog in ORDS get an error when opening in Swagger
The documentation generated by open-api-catalog brings some errors which cannot open in Swagger. Examples that present in the browser console:

duplicate mapping key

missed comma between flow collection entries

When we have a module in ORDS just with GET handlers, the documentation works fine in Swagger.

But when it's defined two or more POST or PUT handlers, we get a errors.

An example of the end-points definition:

```<code>begin
   ORDS.DEFINE_MODULE(
      p_module_name    => 'so',
      p_base_path      => '/so/',
      p_items_per_page =>  15,
      p_status         => 'PUBLISHED',
      p_comments       => NULL);

 ORDS.DEFINE_TEMPLATE(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_priority       => 0,
      p_etag_type      => 'HASH',
      p_etag_query     => NULL,
      p_comments       => '...');
  ORDS.DEFINE_HANDLER(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_method         => 'PUT',
      p_source_type    => 'plsql/block',
      p_items_per_page =>  0,
      p_mimes_allowed  => 'application/json',
      p_comments       => '...',
      p_source         =>
'BEGIN

   UPDATE USERS_OP
      SET id_papel_acesso_ops = :id_papel_acesso_ops
        , dt_alteracao = :dt_alteracao
        , cd_usuario_alteracao = :cd_usuario_alteracao
    WHERE id_op = :id_op
      AND id_user = :id_user;

    COMMIT;

    :status_code := 204; -- No Content

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        :status_code := 400;
        HTP.PRN(''{"error": "'' || SQLERRM || ''"}'');

END;'
      );

  ORDS.DEFINE_HANDLER(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_method         => 'POST',
      p_source_type    => 'plsql/block',
      p_items_per_page =>  0,
      p_mimes_allowed  => 'application/json',
      p_comments       => '...',
      p_source         =>
'BEGIN

   INSERT INTO USERS_OP (id_papel_acesso_ops, id_user, id_op) VALUES(:id_papel_acesso_ops, :id_user, :id_op);

    COMMIT;

    :status_code := 204; -- No Content

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        :status_code := 400;
        HTP.PRN(''{"error": "'' || SQLERRM || ''"}'');

END;'
      );
    end;
    /
</code>```

NOTE 1:  Updated the example to two handler (POST and PUT)

NOTE 2: this description changed a little considering the initial version, to make the question more general.

答:
Using ORDS 21.4 and creating a module to hold your template/handler, here's what I get.

REST Definition with ORDS API, module named 'so':

```<code> begin
   ORDS.DEFINE_MODULE(
      p_module_name    => 'so',
      p_base_path      => '/so/',
      p_items_per_page =>  15,
      p_status         => 'PUBLISHED',
      p_comments       => NULL);

 ORDS.DEFINE_TEMPLATE(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_priority       => 0,
      p_etag_type      => 'HASH',
      p_etag_query     => NULL,
      p_comments       => '...');
  ORDS.DEFINE_HANDLER(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_method         => 'PUT',
      p_source_type    => 'plsql/block',
      p_items_per_page =>  0,
      p_mimes_allowed  => 'application/json',
      p_comments       => '...',
      p_source         =>
'BEGIN

   UPDATE USERS_OP
      SET id_papel_acesso_ops = :id_papel_acesso_ops
        , dt_alteracao = :dt_alteracao
        , cd_usuario_alteracao = :cd_usuario_alteracao
    WHERE id_op = :id_op
      AND id_user = :id_user;

    COMMIT;

    :status_code := 204; -- No Content

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        :status_code := 400;
        HTP.PRN(''{"error": "'' || SQLERRM || ''"}'');

END;'
      );
    end;
    /

</code>```

Ask for the OpenData {json}

```<code>{
    "swagger": "2.0",
    "info": {
        "title": "ORDS generated API for so",
        "version": "1.0.0"
    },
    "host": "pvqhdhmzqnn1hi4-tjsatp.adb.us-ashburn-1.oraclecloudapps.com",
    "basePath": "/ords/admin/so",
    "schemes": [
        "https"
    ],
    "produces": [
        "application/json"
    ],
    "paths": {
        "/users/{id_user}/op/{id_op}": {
            "put": {
                "description": "...",
                "responses": {
                    "200": {
                        "description": "The successfully updated record.",
                        "schema": {
                            "type": "object",
                            "properties": {}
                        }
                    },
                    "201": {
                        "description": "The successfully created record.",
                        "schema": {
                            "type": "object",
                            "properties": {}
                        }
                    }
                },
                "consumes": [
                    "application/json"
                ],
                "parameters": [
                    {
                        "name": "id_op",
                        "in": "path",
                        "required": true,
                        "type": "string",
                        "description": "implicit",
                        "pattern": "^[^/]+$"
                    },
                    {
                        "name": "id_user",
                        "in": "path",
                        "required": true,
                        "type": "string",
                        "description": "implicit",
                        "pattern": "^[^/]+$"
                    },
                    {
                        "name": "payload",
                        "in": "body",
                        "required": true,
                        "schema": {
                            "$ref": "#/definitions/so_ITEM"
                        }
                    }
                ]
            }
        }
    },
    "definitions": {
        "STRING": {
            "type": "string"
        },
        "so_ITEM": {
            "properties": {
                "id_papel_acesso_ops": {
                    "type": "string"
                },
                "dt_alteracao": {
                    "type": "string"
                },
                "cd_usuario_alteracao": {
                    "type": "string"
                },
                "status_code": {
                    "type": "string"
                }
            }
        }
    }
}
</code>```

Feed THAT into editor.swagger.io -

Body:
The documentation generated by open-api-catalog brings some errors which cannot open in Swagger. Examples that present in the browser console:

duplicate mapping key

missed comma between flow collection entries

When we have a module in ORDS just with GET handlers, the documentation works fine in Swagger.

But when it's defined two or more POST or PUT handlers, we get a errors.

An example of the end-points definition:

begin
   ORDS.DEFINE_MODULE(
      p_module_name    => 'so',
      p_base_path      => '/so/',
      p_items_per_page =>  15,
      p_status         => 'PUBLISHED',
      p_comments       => NULL);

 ORDS.DEFINE_TEMPLATE(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_priority       => 0,
      p_etag_type      => 'HASH',
      p_etag_query     => NULL,
      p_comments       => '...');
  ORDS.DEFINE_HANDLER(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_method         => 'PUT',
      p_source_type    => 'plsql/block',
      p_items_per_page =>  0,
      p_mimes_allowed  => 'application/json',
      p_comments       => '...',
      p_source         =>
'BEGIN

   UPDATE USERS_OP
      SET id_papel_acesso_ops = :id_papel_acesso_ops
        , dt_alteracao = :dt_alteracao
        , cd_usuario_alteracao = :cd_usuario_alteracao
    WHERE id_op = :id_op
      AND id_user = :id_user;

    COMMIT;

    :status_code := 204; -- No Content

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        :status_code := 400;
        HTP.PRN(''{"error": "'' || SQLERRM || ''"}'');

END;'
      );

  ORDS.DEFINE_HANDLER(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_method         => 'POST',
      p_source_type    => 'plsql/block',
      p_items_per_page =>  0,
      p_mimes_allowed  => 'application/json',
      p_comments       => '...',
      p_source         =>
'BEGIN

   INSERT INTO USERS_OP (id_papel_acesso_ops, id_user, id_op) VALUES(:id_papel_acesso_ops, :id_user, :id_op);

    COMMIT;

    :status_code := 204; -- No Content

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        :status_code := 400;
        HTP.PRN(''{"error": "'' || SQLERRM || ''"}'');

END;'
      );
    end;
    /

NOTE 1:  Updated the example to two handler (POST and PUT)

NOTE 2: this description changed a little considering the initial version, to make the question more general.

Body:
Using ORDS 21.4 and creating a module to hold your template/handler, here's what I get.

REST Definition with ORDS API, module named 'so':

 begin
   ORDS.DEFINE_MODULE(
      p_module_name    => 'so',
      p_base_path      => '/so/',
      p_items_per_page =>  15,
      p_status         => 'PUBLISHED',
      p_comments       => NULL);

 ORDS.DEFINE_TEMPLATE(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_priority       => 0,
      p_etag_type      => 'HASH',
      p_etag_query     => NULL,
      p_comments       => '...');
  ORDS.DEFINE_HANDLER(
      p_module_name    => 'so',
      p_pattern        => 'users/:id_user/op/:id_op',
      p_method         => 'PUT',
      p_source_type    => 'plsql/block',
      p_items_per_page =>  0,
      p_mimes_allowed  => 'application/json',
      p_comments       => '...',
      p_source         =>
'BEGIN

   UPDATE USERS_OP
      SET id_papel_acesso_ops = :id_papel_acesso_ops
        , dt_alteracao = :dt_alteracao
        , cd_usuario_alteracao = :cd_usuario_alteracao
    WHERE id_op = :id_op
      AND id_user = :id_user;

    COMMIT;

    :status_code := 204; -- No Content

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK;
        :status_code := 400;
        HTP.PRN(''{"error": "'' || SQLERRM || ''"}'');

END;'
      );
    end;
    /

Ask for the OpenData {json}

{
    "swagger": "2.0",
    "info": {
        "title": "ORDS generated API for so",
        "version": "1.0.0"
    },
    "host": "pvqhdhmzqnn1hi4-tjsatp.adb.us-ashburn-1.oraclecloudapps.com",
    "basePath": "/ords/admin/so",
    "schemes": [
        "https"
    ],
    "produces": [
        "application/json"
    ],
    "paths": {
        "/users/{id_user}/op/{id_op}": {
            "put": {
                "description": "...",
                "responses": {
                    "200": {
                        "description": "The successfully updated record.",
                        "schema": {
                            "type": "object",
                            "properties": {}
                        }
                    },
                    "201": {
                        "description": "The successfully created record.",
                        "schema": {
                            "type": "object",
                            "properties": {}
                        }
                    }
                },
                "consumes": [
                    "application/json"
                ],
                "parameters": [
                    {
                        "name": "id_op",
                        "in": "path",
                        "required": true,
                        "type": "string",
                        "description": "implicit",
                        "pattern": "^[^/]+$"
                    },
                    {
                        "name": "id_user",
                        "in": "path",
                        "required": true,
                        "type": "string",
                        "description": "implicit",
                        "pattern": "^[^/]+$"
                    },
                    {
                        "name": "payload",
                        "in": "body",
                        "required": true,
                        "schema": {
                            "$ref": "#/definitions/so_ITEM"
                        }
                    }
                ]
            }
        }
    },
    "definitions": {
        "STRING": {
            "type": "string"
        },
        "so_ITEM": {
            "properties": {
                "id_papel_acesso_ops": {
                    "type": "string"
                },
                "dt_alteracao": {
                    "type": "string"
                },
                "cd_usuario_alteracao": {
                    "type": "string"
                },
                "status_code": {
                    "type": "string"
                }
            }
        }
    }
}

Feed THAT into editor.swagger.io -


问:
Partial deduction of template parameter using constructor
I have seen this asked before in several ways, and all the solutions are always the same: use a helper function or even use nested classes. For me, both of those solutions look clumpsy. So I wonder how come in the c++17/c++20 era there is not better solution to this problem:

EDIT: The question here is if there is any method to use impl<int> i(b);, because currently compiler fails due to the lack of second template argument.

```<code>template<class T1, class T2>
struct impl
{
    impl(const T2& _t2) : t2(_t2) {}

    T1 t1;
    const T2& t2;
};

int main()
{
    int a{};
    double b{};
    impl<int, double> i(b);//This works...
    impl<int> i(b);//... but this doesn't due to lack of 2nd template parameter!!!
}
</code>```

I understand that partial spetialization can present problems in some cases, but it is not possible to use CTAD or any other method in this case??? If so, how?

答:
I most often use a "type tag" to overcome this kind of problems. It also comes in handy for similar issues, like the lack of partial specialization of function templates.</p>
```<code>#include <type_traits>

template<typename T> struct type_t{};
template<typename T> constexpr type_t<T> type;

template<class T1, class T2>
struct impl
{
    impl(const T2& _t2, type_t<T1> = {}) : t2(_t2) {}

    T1 t1;
    const T2& t2;
};

int main()
{
    int a{};
    double b{};
    impl<int, double> i(b);//This works...
    impl j(b, type<int>); // This works as well
    static_assert(std::is_same_v<decltype(j),impl<int, double>>);
}
</code>```

Body:
I have seen this asked before in several ways, and all the solutions are always the same: use a helper function or even use nested classes. For me, both of those solutions look clumpsy. So I wonder how come in the c++17/c++20 era there is not better solution to this problem:

EDIT: The question here is if there is any method to use impl<int> i(b);, because currently compiler fails due to the lack of second template argument.

template<class T1, class T2>
struct impl
{
    impl(const T2& _t2) : t2(_t2) {}

    T1 t1;
    const T2& t2;
};

int main()
{
    int a{};
    double b{};
    impl<int, double> i(b);//This works...
    impl<int> i(b);//... but this doesn't due to lack of 2nd template parameter!!!
}

I understand that partial spetialization can present problems in some cases, but it is not possible to use CTAD or any other method in this case??? If so, how?

Body:
I most often use a "type tag" to overcome this kind of problems. It also comes in handy for similar issues, like the lack of partial specialization of function templates.

#include <type_traits>

template<typename T> struct type_t{};
template<typename T> constexpr type_t<T> type;

template<class T1, class T2>
struct impl
{
    impl(const T2& _t2, type_t<T1> = {}) : t2(_t2) {}

    T1 t1;
    const T2& t2;
};

int main()
{
    int a{};
    double b{};
    impl<int, double> i(b);//This works...
    impl j(b, type<int>); // This works as well
    static_assert(std::is_same_v<decltype(j),impl<int, double>>);
}


问:
React Component receives the Redux states but can't dispatch actions
The action I want to trigger works on its own, the axis request works and it retrieves data from an api. However when I try to run it from the component using connect and then accessing it as a prop, it is like the function doesn't run, and the redux state don't update accordingly.

This is how I use connect with my react component (getChannels is imported before from the action js file

```<code>const mapStateToProps = (state) => ({
  channels: state.Channels.channels,
})

export default connect(mapStateToProps,{ getChannels })(ChannelList)
</code>```

This is how I call the function inside the component

```<code>componentDidMount(){

    this.props.getChannels

  }
</code>```

When I log the props to the console I get the initial redux states, and a function object.

console log image

I have tried different ways of dispatching the action but I am new to this so I can't identify why it doesn't work. Below is my action file

```<code>import axios from 'axios'

import { GET_CHANNELS } from "./types";

// GET CHANNELS

export const getChannels = () => (dispatch) => {

 axios
  .get('/TeamChat/RetrieveChannels')
  .then((res) => {
    console.log(res)
    dispatch({
      type: GET_CHANNELS,
      payload: res.data,
    });
  })
  .catch((err) => console.log(err));
};
</code>```

And bellow is my reducer

```<code>   import { GET_CHANNELS } from '../actions/types.js';

const initialState = {
  channels: ['channel 1'],
}

export default function (state = initialState,action) {
  switch(action.type) {

    case GET_CHANNELS:
      return {
        ...state,
        channels: action.payload
  };
    default:
      return state;

  }
}
</code>```

Thank you so much for helping me... I have been following this tutorial https://www.youtube.com/watch?v=BmL8iaLMnQ0&list=PLillGF-RfqbbRA-CIUxlxkUpbq0IFkX60&index=4&ab_channel=TraversyMedia, and I can't identify where I am making a mistake.

答:
You need to call the method,
so do
this.props.getChannels()
instead of
this.props.getChannels

But generally, you should be using the useSelector and useDispatch hooks in 2022. connect/mapStateToProps are a legacy api that is only around to provide support for legacy class components. If you are following a tutorial sthat shows you connect, it probably also shows you other outdated concepts: modern Redux does not use switch..case reducers, ACTION_TYPEs, hand-written action creators, immutable reducer logic or createStore and applyMiddleware. As a consequence, modern Redux is less prone to bugs, easier to read and only 1/4 of the code. If your tutorial is still showing these outdated practices, please follow the official Redux tutorial instead.

Body:
The action I want to trigger works on its own, the axis request works and it retrieves data from an api. However when I try to run it from the component using connect and then accessing it as a prop, it is like the function doesn't run, and the redux state don't update accordingly.

This is how I use connect with my react component (getChannels is imported before from the action js file

const mapStateToProps = (state) => ({
  channels: state.Channels.channels,
})

export default connect(mapStateToProps,{ getChannels })(ChannelList)

This is how I call the function inside the component

componentDidMount(){

    this.props.getChannels

  }

When I log the props to the console I get the initial redux states, and a function object.

console log image

I have tried different ways of dispatching the action but I am new to this so I can't identify why it doesn't work. Below is my action file

import axios from 'axios'

import { GET_CHANNELS } from "./types";

// GET CHANNELS

export const getChannels = () => (dispatch) => {

 axios
  .get('/TeamChat/RetrieveChannels')
  .then((res) => {
    console.log(res)
    dispatch({
      type: GET_CHANNELS,
      payload: res.data,
    });
  })
  .catch((err) => console.log(err));
};

And bellow is my reducer

   import { GET_CHANNELS } from '../actions/types.js';

const initialState = {
  channels: ['channel 1'],
}

export default function (state = initialState,action) {
  switch(action.type) {

    case GET_CHANNELS:
      return {
        ...state,
        channels: action.payload
  };
    default:
      return state;

  }
}

Thank you so much for helping me... I have been following this tutorial https://www.youtube.com/watch?v=BmL8iaLMnQ0&list=PLillGF-RfqbbRA-CIUxlxkUpbq0IFkX60&index=4&ab_channel=TraversyMedia, and I can't identify where I am making a mistake.


问:
Absolute centering a flex item loses the button hovers, why?
I'm trying to create a header for a page that puts the title of the page in the middle and centered absolutely. I tried to do this with flex box and justify-content:space-between However as shown below I get the title skewed depending on the buttons width on the right (I've exaggerated that to show the effect)

While I was able to absolutely center the title (using absolute positioning on the h1) as in the example of "Want", a strange side-effect shows up on the buttons- they aren't clickable anymore! I'm flummoxed. What's going on here? How do I center the title and still keep the buttons working (with flex)?

body {
  max-width: 32em;
  margin: 0 auto;
}

nav {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  height: 2em;
  justify-content: space-between;
  border-bottom: 1px solid gray;
  margin: 20px auto;
}

/* My attempt at keeping h1 absolutely centered on the page width */

h1.want {
  left: 0;
  position: absolute;
  right: 0;
  text-align: center;
  top: 20px;
  padding: 0;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    <div>
      <button>Foo</button>
    </div>
    <div>
      <div>
        <h1 class="want">Want</h1>
      </div>
    </div>
    <div>
      <button>Bar</button>
      <button>Bas</button>
      <button>Bat</button>
      <button>Bau</button>
    </div>
  </nav>
  The buttons don't work here!
  <nav>
    <div>
      <button>Foo</button>
    </div>
    <div>
      <div>
        <h1>Got this</h1>
      </div>
    </div>
    <div>
      <button>Bar</button>
      <button>Bas</button>
      <button>Bat</button>
      <button>Bau</button>
    </div>
  </nav>
  Buttons work here.
</header></code>```

答:
Like @Phix pointed out in the comment, using position: absolute with left: 0 and right: 0 effectively gives the h1 a 100% width which then covers the associated buttons so they are unreachable. You can prove this by giving that h1 a background color (or better yet - use the dev tools in the browser).

If you simply remove all of the styling for h1.want you get the desired result without resorting to absolute positioning:

<!DOCTYPE html>

        <button>Foo</button>

Want

        <button>Bar</button>
        <button>Bas</button>
        <button>Bat</button>
        <button>Bau</button>

    The buttons don't work here!

        <button>Foo</button>

Got this

        <button>Bar</button>
        <button>Bas</button>
        <button>Bat</button>
        <button>Bau</button>

    Buttons work here.

```

Body:
I'm trying to create a header for a page that puts the title of the page in the middle and centered absolutely. I tried to do this with flex box and justify-content:space-between However as shown below I get the title skewed depending on the buttons width on the right (I've exaggerated that to show the effect)

While I was able to absolutely center the title (using absolute positioning on the h1) as in the example of "Want", a strange side-effect shows up on the buttons- they aren't clickable anymore! I'm flummoxed. What's going on here? How do I center the title and still keep the buttons working (with flex)?

body {
  max-width: 32em;
  margin: 0 auto;
}

nav {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  height: 2em;
  justify-content: space-between;
  border-bottom: 1px solid gray;
  margin: 20px auto;
}

/* My attempt at keeping h1 absolutely centered on the page width */

h1.want {
  left: 0;
  position: absolute;
  right: 0;
  text-align: center;
  top: 20px;
  padding: 0;
  margin: 0;
}

      <button>Foo</button>

Want

      <button>Bar</button>
      <button>Bas</button>
      <button>Bat</button>
      <button>Bau</button>

  The buttons don't work here!

      <button>Foo</button>

Got this

      <button>Bar</button>
      <button>Bas</button>
      <button>Bat</button>
      <button>Bau</button>

  Buttons work here.

Body:
Like @Phix pointed out in the comment, using position: absolute with left: 0 and right: 0 effectively gives the h1 a 100% width which then covers the associated buttons so they are unreachable. You can prove this by giving that h1 a background color (or better yet - use the dev tools in the browser).

If you simply remove all of the styling for h1.want you get the desired result without resorting to absolute positioning:

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      max-width: 32em;
      margin: 0 auto;
    }

    nav {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: 100%;
      height: 2em;
      justify-content: space-between;
      border-bottom: 1px solid gray;
      margin: 20px auto;
    }
    /* My attempt at keeping h1 absolutely centered on the page width */
    /* h1.want {
      left: 0;
      position: absolute;
      right: 0;
      text-align: center;
      top: 20px;
      padding: 0;
      margin: 0;
    } */
  </style>
</head>

<body>
  <header>
    <nav>
      <div>
        <button>Foo</button>
      </div>
      <div>
        <div>
          <h1 class="want">Want</h1>
        </div>
      </div>
      <div>
        <button>Bar</button>
        <button>Bas</button>
        <button>Bat</button>
        <button>Bau</button>
      </div>
    </nav>
    The buttons don't work here!
    <nav>
      <div>
        <button>Foo</button>
      </div>
      <div>
        <div>
          <h1>Got this</h1>
        </div>
      </div>
      <div>
        <button>Bar</button>
        <button>Bas</button>
        <button>Bat</button>
        <button>Bau</button>
      </div>
    </nav>
    Buttons work here.
  </header>
</body>

</html>