问:
How do I make a bot status that has memberCount on it?
I made a simple discord verify bot, but I want to make the bot status to watching # people verifying (the # is how many people in my server). I see some bots have it, but I don't know how to make it. Here is my current code for the bot status:

```<code>if (Object.keys(this.config.presence).length !== 0) {
        this.user.setPresence({
            game: {
                name: this.config.presence.name,
                type: this.config.presence.type
            },
            status: "online"
        }).catch(console.error);
    }
</code>```

答:
At the first you need set interval command to update member.

You dont need use this.user for this operation. The previus answer method will display only cached users, so its wrong way, because on bot start, you will has no users in this collection.

If you need display members on your own server you can do like this:

Get your guild BY ID

Get property guild.memberCount

Update it every 5 min

client.on('ready', () => {
        setInterval(() => {
          targetGuild = client.guilds.get('GUILD ID HERE')
          if(targetGuild) {
              client.user.setPresence({ game: { name: targetGuild.memberCount + ' people verifying!', type: 'WATCHING' }, status: 'online'  })
                    .then(console.log)
                    .catch(console.error);
          }
    }, 1000 * 60 * 5);

});
```

After bot start, this will update after 5 minutes.

For test you can change  }, 1000 * 60 * 5)  to  }, 1000);

Body:
I made a simple discord verify bot, but I want to make the bot status to watching # people verifying (the # is how many people in my server). I see some bots have it, but I don't know how to make it. Here is my current code for the bot status:

if (Object.keys(this.config.presence).length !== 0) {
        this.user.setPresence({
            game: {
                name: this.config.presence.name,
                type: this.config.presence.type
            },
            status: "online"
        }).catch(console.error);
    }

Body:
At the first you need set interval command to update member.

You dont need use this.user for this operation. The previus answer method will display only cached users, so its wrong way, because on bot start, you will has no users in this collection.

If you need display members on your own server you can do like this:

Get your guild BY ID

Get property guild.memberCount

Update it every 5 min

client.on('ready', () => {
        setInterval(() => {
          targetGuild = client.guilds.get('GUILD ID HERE')
          if(targetGuild) {
              client.user.setPresence({ game: { name: targetGuild.memberCount + ' people verifying!', type: 'WATCHING' }, status: 'online'  })
                    .then(console.log)
                    .catch(console.error);
          }
    }, 1000 * 60 * 5);

});

After bot start, this will update after 5 minutes.

For test you can change  }, 1000 * 60 * 5)  to  }, 1000);


来源: stackexchange

问:
C++ Get name of type in template
I'm writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, which are for the most part not written by programmers, and so need a nice message about why the app failed to load e.g. something like:

Error parsing example.txt. Value ("notaninteger")of [MySectiom]Key is not a valid int

I can work out the file, section and key names from the arguments passed to the template function and member vars in the class, however I'm not sure how to get the name of the type the template function is trying to convert to.

My current code looks like, with specialisations for just plain strings and such:

```<code>template<typename T> T GetValue(const std::wstring &section, const std::wstring &key)
{
    std::map<std::wstring, std::wstring>::iterator it = map[section].find(key);
    if(it == map[section].end())
        throw ItemDoesNotExist(file, section, key)
    else
    {
        try{return boost::lexical_cast<T>(it->second);}
        //needs to get the name from T somehow
        catch(...)throw ParseError(file, section, key, it->second, TypeName(T));
    }
}
</code>```

Id rather not have to make specific overloads for every type that the data files might use, since there are loads of them...

Also I need a solution that does not incur any runtime overhead unless an exception occurs, i.e. a completely compile time solution is what I want since this code is called tons of times and load times are already getting somewhat long.

EDIT: Ok this is the solution I came up with:

I have a types.h containg the following

```<code>#pragma once
template<typename T> const wchar_t *GetTypeName();

#define DEFINE_TYPE_NAME(type, name) \
    template<>const wchar_t *GetTypeName<type>(){return name;}
</code>```

Then I can use the DEFINE_TYPE_NAME macro to in cpp files for each type I need to deal with (eg in the cpp file that defined the type to start with).

The linker is then able to find the appropirate template specialisation as long as it was defined somewhere, or throw a linker error otherwise so that I can add the type.

答:
typeid(uint8_t).name() is nice, but it returns "unsigned char" while you may expect "uint8_t".

This piece of code will return you the appropriate type

```<code>#define DECLARE_SET_FORMAT_FOR(type) \
    if ( typeid(type) == typeid(T) ) \
        formatStr = #type;

template<typename T>
static std::string GetFormatName()
{
    std::string formatStr;

    DECLARE_SET_FORMAT_FOR( uint8_t )
    DECLARE_SET_FORMAT_FOR( int8_t )

    DECLARE_SET_FORMAT_FOR( uint16_t )
    DECLARE_SET_FORMAT_FOR( int16_t )

    DECLARE_SET_FORMAT_FOR( uint32_t )
    DECLARE_SET_FORMAT_FOR( int32_t )

    DECLARE_SET_FORMAT_FOR( float )

    // .. to be exptended with other standard types you want to be displayed smartly

    if ( formatStr.empty() )
    {
        assert( false );
        formatStr = typeid(T).name();
    }

    return formatStr;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C++ Get name of type in template

Body:
I'm writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, which are for the most part not written by programmers, and so need a nice message about why the app failed to load e.g. something like:

Error parsing example.txt. Value ("notaninteger")of [MySectiom]Key is not a valid int

I can work out the file, section and key names from the arguments passed to the template function and member vars in the class, however I'm not sure how to get the name of the type the template function is trying to convert to.

My current code looks like, with specialisations for just plain strings and such:

template<typename T> T GetValue(const std::wstring &section, const std::wstring &key)
{
    std::map<std::wstring, std::wstring>::iterator it = map[section].find(key);
    if(it == map[section].end())
        throw ItemDoesNotExist(file, section, key)
    else
    {
        try{return boost::lexical_cast<T>(it->second);}
        //needs to get the name from T somehow
        catch(...)throw ParseError(file, section, key, it->second, TypeName(T));
    }
}

Id rather not have to make specific overloads for every type that the data files might use, since there are loads of them...

Also I need a solution that does not incur any runtime overhead unless an exception occurs, i.e. a completely compile time solution is what I want since this code is called tons of times and load times are already getting somewhat long.

EDIT: Ok this is the solution I came up with:

I have a types.h containg the following

#pragma once
template<typename T> const wchar_t *GetTypeName();

#define DEFINE_TYPE_NAME(type, name) \
    template<>const wchar_t *GetTypeName<type>(){return name;}

Then I can use the DEFINE_TYPE_NAME macro to in cpp files for each type I need to deal with (eg in the cpp file that defined the type to start with).

The linker is then able to find the appropirate template specialisation as long as it was defined somewhere, or throw a linker error otherwise so that I can add the type.

Body:
typeid(uint8_t).name() is nice, but it returns "unsigned char" while you may expect "uint8_t".

This piece of code will return you the appropriate type

#define DECLARE_SET_FORMAT_FOR(type) \
    if ( typeid(type) == typeid(T) ) \
        formatStr = #type;

template<typename T>
static std::string GetFormatName()
{
    std::string formatStr;

    DECLARE_SET_FORMAT_FOR( uint8_t )
    DECLARE_SET_FORMAT_FOR( int8_t )

    DECLARE_SET_FORMAT_FOR( uint16_t )
    DECLARE_SET_FORMAT_FOR( int16_t )

    DECLARE_SET_FORMAT_FOR( uint32_t )
    DECLARE_SET_FORMAT_FOR( int32_t )

    DECLARE_SET_FORMAT_FOR( float )

    // .. to be exptended with other standard types you want to be displayed smartly

    if ( formatStr.empty() )
    {
        assert( false );
        formatStr = typeid(T).name();
    }

    return formatStr;
}

ContentLicense: CC BY-SA 4.0


问:
How to check for records that are older than today in PHP?
I've set up a timestamp field with extra set to ON UPDATE CURRENT_TIMESTAMP.
It works but I have a question:

I'd like to check for all records which are older than today - how would I do that?

答:
An example query for older than today (before midnight) would be:

```<code>SELECT * FROM my_table WHERE timestamp_column < CURDATE();
</code>```

Check out the MySQL Date/Time Functions for more details. If you want older than last 24 hours, check out fafnirbcrow's answer

Body:
An example query for older than today (before midnight) would be:

SELECT * FROM my_table WHERE timestamp_column < CURDATE();

Check out the MySQL Date/Time Functions for more details. If you want older than last 24 hours, check out fafnirbcrow's answer

ContentLicense: CC BY-SA 3.0


问:
How to append an output that is looping rather than making each loop its own line
I read a few similar questions, but none helped in my situation. I have a loop that goes through a csv file and extracts IPs. I would then like to string these IPs as you see in the code below where 'adding='. How do I get the stringed IPs to append each time they are added rather than make a new line every time?

Code tried:

```<code>for i in x['Agent IP']:
    data = (i)
    adding = {'field': 'ip-address', 'operator': 'is', 'value': str(data)}
    print(adding)
</code>```

Output received:

```<code>{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.1'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.2'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.3'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.4'}
</code>```

I would like the output to append each one with a common in between them like so:

```<code>{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.1'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.2'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.3'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.4'}
</code>```

答:
I think you are looking for a list:</p>

```<code>res = []

for i in x['Agent IP']:
    data = (i)
    adding = {'field': 'ip-address', 'operator': 'is', 'value': str(data)}
    res.append(adding)

print(res)
</code>```

Body:
I read a few similar questions, but none helped in my situation. I have a loop that goes through a csv file and extracts IPs. I would then like to string these IPs as you see in the code below where 'adding='. How do I get the stringed IPs to append each time they are added rather than make a new line every time?

Code tried:

for i in x['Agent IP']:
    data = (i)
    adding = {'field': 'ip-address', 'operator': 'is', 'value': str(data)}
    print(adding)

Output received:

{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.1'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.2'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.3'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.4'}

I would like the output to append each one with a common in between them like so:

{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.1'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.2'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.3'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.4'}

Body:
I think you are looking for a list:

res = []

for i in x['Agent IP']:
    data = (i)
    adding = {'field': 'ip-address', 'operator': 'is', 'value': str(data)}
    res.append(adding)

print(res)


问:
Checking the content of an array with comparison operators, concerning a specified order
I need a function which checks an array with integers. The integers have to be either in ascending order or in descending order. That depends from case to case.

I have figured out the following solution:

const areVersionNumbersInExpectedOrder = (aNums, sExpectedOrder = "ascending") => {
            let passed = false;

            if (sExpectedOrder === "ascending") {
                if (aNums[0] < aNums[1] && aNums[1] < aNums[2]) {
                    passed = true;
                }
            } else if (sExpectedOrder === "descending") {
                if (aNums[0] > aNums[1] && aNums[1] > aNums[2]) {
                    passed = true;
                }
            }

            return passed
        };

        const versionNumbersAscending = [1, 2, 3];
        console.log(
            `Result ascending order: ${areVersionNumbersInExpectedOrder(versionNumbersAscending, "ascending")}`);

        const versionNumbersDescending = [3, 2, 1];
        console.log(
            `Result descending order: ${areVersionNumbersInExpectedOrder(versionNumbersDescending, "descending")}`);```

Basically it works for me, but it is ugly. Especially the nested ifs.

Is there are better way to solve the task?

答:
You could take a shorter approach with every and a callback depending on the expected order.

const areVersionNumbersInExpectedOrder = (aNums, sExpectedOrder = "ascending") => {
    const
        order = {
            ascending: (b, i, { [i - 1]: a }) => !i || a  !i || a > b
        };

    return aNums.every(order[sExpectedOrder]);
};

console.log(areVersionNumbersInExpectedOrder([1, 2, 3], "ascending"));
console.log(areVersionNumbersInExpectedOrder([3, 2, 1], "descending"));```

Body:
I need a function which checks an array with integers. The integers have to be either in ascending order or in descending order. That depends from case to case.

I have figured out the following solution:

const areVersionNumbersInExpectedOrder = (aNums, sExpectedOrder = "ascending") => {
            let passed = false;

            if (sExpectedOrder === "ascending") {
                if (aNums[0] < aNums[1] && aNums[1] < aNums[2]) {
                    passed = true;
                }
            } else if (sExpectedOrder === "descending") {
                if (aNums[0] > aNums[1] && aNums[1] > aNums[2]) {
                    passed = true;
                }
            }

            return passed
        };

        const versionNumbersAscending = [1, 2, 3];
        console.log(
            `Result ascending order: ${areVersionNumbersInExpectedOrder(versionNumbersAscending, "ascending")}`);

        const versionNumbersDescending = [3, 2, 1];
        console.log(
            `Result descending order: ${areVersionNumbersInExpectedOrder(versionNumbersDescending, "descending")}`);

Basically it works for me, but it is ugly. Especially the nested ifs.

Is there are better way to solve the task?

Body:
You could take a shorter approach with every and a callback depending on the expected order.

const areVersionNumbersInExpectedOrder = (aNums, sExpectedOrder = "ascending") => {
    const
        order = {
            ascending: (b, i, { [i - 1]: a }) => !i || a < b,
            descending: (b, i, { [i - 1]: a }) => !i || a > b
        };

    return aNums.every(order[sExpectedOrder]);
};

console.log(areVersionNumbersInExpectedOrder([1, 2, 3], "ascending"));
console.log(areVersionNumbersInExpectedOrder([3, 2, 1], "descending"));


答: instead of printing it out you can make a list and append it so at the beginning of your code you can call information = list() and right where your print function is you can call information.append(adding) and at the end of the file you can call print(information)

Title: How to append an output that is looping rather than making each loop its own line


问:
Ignite create user with full privileges(Jdbc thin client)
I am stuck on creating user with full privileges.

I have created a user with name shubh. but dont know how to grant all privileges.

And want to drop the default user (user = ignite , password = ignite) privileges.

Please suggest.

答:
Have you tried the following:

```<code>DROP USER "ignite";
</code>```

As for privileges, we don't have granular permissions in Apache Ignite yet, so if you have user it can access all tables.

Body:
Have you tried the following:

DROP USER "ignite";

As for privileges, we don't have granular permissions in Apache Ignite yet, so if you have user it can access all tables.


问:
Kotlin - custom Exception as data class?
In Kotlin, it's extremely easy to create custom exceptions. Below is a sample that accepts code as an argument:

class PortraitRequestFailedException(val code: Int) : RuntimeException()

The code contains the http response error code returned from the server. The problem is, when that exception is reported generically by a logger, like Timber.e(exception, "Error loading portrait cover photo url"), the code is lost in the output:

```<code>2020-02-14 13:50:59.886 15942-16232 E/PortraitManager$watchCoverPhotoUrl: Error loading portrait cover photo url
    com.example.data.PortraitManager$PortraitRequestFailedException
        at com.example.data.PortraitManager$loadCoverPhotoUrl$1.call(PortraitManager.kt:139)

</code>```

Of course I could add a when exception is PortraitRequestFailedException clause and handle specifically that particular error, but I don't want that (especially that all exceptions in Kotlin are unchecked and I may not be aware what type to expect).

I've found an easy way to pass the code to a RuntimeException as the message parameter:

class PortraitRequestFailedException(val code: Int) : RuntimeException(code.toString())

```<code>2020-02-14 13:40:32.878 430-857 E/PortraitManager$watchCoverPhotoUrl: Error loading portrait cover photo url
    com.example.data.PortraitManager$PortraitRequestFailedException: 403
        at com.example.data.PortraitManager$loadCoverPhotoUrl$1.call(PortraitManager.kt:139)
</code>```

But that approach looks a bit too verbose to me (I need to reference the code in the parent class constructor), and it will just print PortraitRequestFailedException: 403, not telling what 403 refers to (imagine having more than one argument here).

So I came up with an idea of defining my custom exception as a data class:

data class PortraitRequestFailedException(val code: Int) : RuntimeException()

Since data classes in Kotlin have an auto-generated toString() method in a form of PortraitRequestFailedException(code=403), such notation has all the advantages I want, without added verbosity or boilerplate code. The log is the following:

```<code>E/PortraitManager$watchCoverPhotoUrl: Error loading portrait cover photo url
    PortraitRequestFailedException(code=403)
        at com.example.data.PortraitManager$loadCoverPhotoUrl$1.call(PortraitManager.kt:139)

</code>```

Do you see any drawbacks of such an approach? Are there any dangers of handling exceptions as data classes?

答:
I'd slightly lean for manually overriding toString() yourself as that's the only thing you need of a data class.
But overall it works, and has no significant drawbacks, really.

Body:
In Kotlin, it's extremely easy to create custom exceptions. Below is a sample that accepts code as an argument:

class PortraitRequestFailedException(val code: Int) : RuntimeException()

The code contains the http response error code returned from the server. The problem is, when that exception is reported generically by a logger, like Timber.e(exception, "Error loading portrait cover photo url"), the code is lost in the output:

2020-02-14 13:50:59.886 15942-16232 E/PortraitManager$watchCoverPhotoUrl: Error loading portrait cover photo url
    com.example.data.PortraitManager$PortraitRequestFailedException
        at com.example.data.PortraitManager$loadCoverPhotoUrl$1.call(PortraitManager.kt:139)

Of course I could add a when exception is PortraitRequestFailedException clause and handle specifically that particular error, but I don't want that (especially that all exceptions in Kotlin are unchecked and I may not be aware what type to expect).

I've found an easy way to pass the code to a RuntimeException as the message parameter:

class PortraitRequestFailedException(val code: Int) : RuntimeException(code.toString())

2020-02-14 13:40:32.878 430-857 E/PortraitManager$watchCoverPhotoUrl: Error loading portrait cover photo url
    com.example.data.PortraitManager$PortraitRequestFailedException: 403
        at com.example.data.PortraitManager$loadCoverPhotoUrl$1.call(PortraitManager.kt:139)

But that approach looks a bit too verbose to me (I need to reference the code in the parent class constructor), and it will just print PortraitRequestFailedException: 403, not telling what 403 refers to (imagine having more than one argument here).

So I came up with an idea of defining my custom exception as a data class:

data class PortraitRequestFailedException(val code: Int) : RuntimeException()

Since data classes in Kotlin have an auto-generated toString() method in a form of PortraitRequestFailedException(code=403), such notation has all the advantages I want, without added verbosity or boilerplate code. The log is the following:

E/PortraitManager$watchCoverPhotoUrl: Error loading portrait cover photo url
    PortraitRequestFailedException(code=403)
        at com.example.data.PortraitManager$loadCoverPhotoUrl$1.call(PortraitManager.kt:139)

Do you see any drawbacks of such an approach? Are there any dangers of handling exceptions as data classes?


问:
vue-form-generator & vue-multiselect: can't remove tags, duplicates them
I am using vue-form-generator with the field vueMultiselect (integration of vue-multiselect).

Adding tags works well, however deleting tags fails (clicking on x icon):

nothing happens when trying to delete the first existing tag

if you add a tag and try to delete it, a input event is emitted which duplicates tags

For instance:

Starts with Vue.js

Click x on Vue.js ==> tag remains, (BROKEN)

Add Rails.js ==>  Vue.js, Rails.js (OK)

Click x on Rails.js ==> Vue.js, Vue.js, Rails.js (BROKEN)

Here is a link to reproduce the problem

Q: Is this failing because I misconfigured vueMultiselect (eg some options I need to set to prevent this behaviour)?

If not I'll just raise it as a bug

Versions:

Vue = 2.5.17

vue-multiSelect = 2.1.2

vue-form-generator = 2.3.4

答:
Check out this codepen maybe this will help you.

Fiddle - https://jsfiddle.net/73ufp4ys/

According to this Github issue it's simply because the trackBy option was missing.


问:
Terraform dynamic blocks with nested list
I need to create an escalation policy in Pagerduty using Terraform. I want to dynamically create rule blocks and then within them target blocks with values from rule. I am not sure how to make the second call inside target block to make it dynamic.
I have a list of teams within a list.

```<code>locals {
  teams = [
    [data.pagerduty_schedule.ce_ooh_schedule.id, data.pagerduty_schedule.pi_office_hours_schedule.id],
    [data.pagerduty_schedule.delivery_managers_schedule.id]
  ]
}

resource "pagerduty_escalation_policy" "policy" {

    name = var.policy_name
    num_loops = var.num_loops
    teams = [var.policy_teams]

    dynamic "rule" {
      for_each = local.teams
      escalation_delay_in_minutes = var.escalation_delay
      dynamic "target" {
         for_each = ??????
         content {
            type = var.target_type
            id = ??????
         }
       }
    }
}
</code>```

???? are the points I'm not sure about.

I need to create a rule for each item in a list(so [team1, team2] and [escalation_team]) and then for each item within those lists I need to create a target for each of the teams(so rule 1 will have two targets - team1 and team2 and rule 2 will have one target which is escalation_team).

Any idea how I could approach this?

I'm using TF v0.12.20

Here's my config after updating:

```<code>resource "pagerduty_escalation_policy" "policy" {
name      = var.policy_name
  num_loops = var.num_loops
  teams     = [var.policy_teams]

  dynamic "rule" {
    for_each = local.teams
    escalation_delay_in_minutes = var.escalation_delay

    dynamic "target" {
      for_each = rule.value
      content {
        type = var.target_type
        id   = target.value
      }
    }
  }
}
</code>```

Edit: Changed locals.teams to local.teams

答:
If I'm reading your question correctly, I believe you want something like the following

```<code>resource "pagerduty_escalation_policy" "policy" {
  name      = var.policy_name
  num_loops = var.num_loops
  teams     = [var.policy_teams]

  dynamic "rule" {
    for_each = locals.teams
    content {
      escalation_delay_in_minutes = var.escalation_delay

      dynamic "target" {
        for_each = rule.value
        content {
          type = var.target_type
          id   = target.value
        }
      }
    }
  }
}
</code>```

Note the following

Each dynamic block must have a matching content block

dynamic blocks introduce new names that have .key and .value which can be used to access properties of what's being looped over.

I can't actually run this so if it's still wrong let me know and I'll update.

Body:
I need to create an escalation policy in Pagerduty using Terraform. I want to dynamically create rule blocks and then within them target blocks with values from rule. I am not sure how to make the second call inside target block to make it dynamic.
I have a list of teams within a list.

locals {
  teams = [
    [data.pagerduty_schedule.ce_ooh_schedule.id, data.pagerduty_schedule.pi_office_hours_schedule.id],
    [data.pagerduty_schedule.delivery_managers_schedule.id]
  ]
}

resource "pagerduty_escalation_policy" "policy" {

    name = var.policy_name
    num_loops = var.num_loops
    teams = [var.policy_teams]

    dynamic "rule" {
      for_each = local.teams
      escalation_delay_in_minutes = var.escalation_delay
      dynamic "target" {
         for_each = ??????
         content {
            type = var.target_type
            id = ??????
         }
       }
    }
}

???? are the points I'm not sure about.

I need to create a rule for each item in a list(so [team1, team2] and [escalation_team]) and then for each item within those lists I need to create a target for each of the teams(so rule 1 will have two targets - team1 and team2 and rule 2 will have one target which is escalation_team).

Any idea how I could approach this?

I'm using TF v0.12.20

Here's my config after updating:

resource "pagerduty_escalation_policy" "policy" {
name      = var.policy_name
  num_loops = var.num_loops
  teams     = [var.policy_teams]

  dynamic "rule" {
    for_each = local.teams
    escalation_delay_in_minutes = var.escalation_delay

    dynamic "target" {
      for_each = rule.value
      content {
        type = var.target_type
        id   = target.value
      }
    }
  }
}

Edit: Changed locals.teams to local.teams

Body:
If I'm reading your question correctly, I believe you want something like the following

resource "pagerduty_escalation_policy" "policy" {
  name      = var.policy_name
  num_loops = var.num_loops
  teams     = [var.policy_teams]

  dynamic "rule" {
    for_each = locals.teams
    content {
      escalation_delay_in_minutes = var.escalation_delay

      dynamic "target" {
        for_each = rule.value
        content {
          type = var.target_type
          id   = target.value
        }
      }
    }
  }
}

Note the following

Each dynamic block must have a matching content block

dynamic blocks introduce new names that have .key and .value which can be used to access properties of what's being looped over.

I can't actually run this so if it's still wrong let me know and I'll update.


问:
attr_protected equivalent for Rails 6? gem protected_attributes needs activemodel < 5.0 and hence is not compatible for rails 6
Searching for an 'attr_protected' equivalent for Rails 6

gem protected_attributes which served the purpose from rails 4 onwards, needs activemodel < 5.0 and hence is not solving for rails 6.

Any alternatives or better solution for achieving the behavior?

答:
Have you try this gem

```<code>gem 'protected_attributes_continued'
</code>```

This gem adds the class methods attr_accessible and attr_protected to declare white or black lists of attributes.

More info click here

Body:
Have you try this gem

gem 'protected_attributes_continued'

This gem adds the class methods attr_accessible and attr_protected to declare white or black lists of attributes.

More info click here


问:
WPF: Update cell value in row of main DataGrid when sum of values in column of sub DataGrid change
I have a main DataGrid (bound to ObservableCollection<MainItem>) with another sub DataGrid  defined in the RowDetailsTemplate (bound to ObservableCollection<SubItem>).  The MainItem.Total property is just a derived value that returns SubItems.Sum(s => s.Amount).  This works great upon displaying the grids.

Yet, when a value in the Amount column is changed and SubItem.Amountupdated, though the MainItem.Total value is correct (it is just a derived value), the main grid doesn't refresh to show the new value.  If I force MainDataGrid.Items.Refresh() (for example, in MainDataGrid_SelectedCellsChanged), the main grid then displays the value now in MainItem.Total.  So, this works but it smells since it is such a brute force method refreshing all visible rows in the main grid.  [NOTE: This situation is similar to the article Update single row in a WPF Datagrid but I'm already using an ObservableCollection.]

I expect this behavior is because the change occurred in ObservableCollection<SubItem> not in ObservableCollection<MainItem> so it doesn't know about it?  But I haven't found an event to raise that informs the main grid that the contents of the bound MainItem.Total has been updated.

[NOTE: The code below is a self-contained sample in case someone wants to build this and try it.  It is based on the same situation in my real project.]

XAML:

```<code><Window x:Class="WpfAppDataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfAppDataGrid"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="100" />
        </Grid.ColumnDefinitions>
        <DataGrid x:Name="MainDataGrid" Grid.Column="0"
                  ItemsSource="{Binding MainItems}"
                  RowDetailsVisibilityMode="VisibleWhenSelected"
                  SelectedCellsChanged="MainDataGrid_SelectedCellsChanged"
                  AutoGenerateColumns="False"
                  CanUserSortColumns="True"
                  CanUserAddRows="True"
                  CanUserDeleteRows="True"
                  RowBackground="AliceBlue"
                  HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch"
                  Margin="10,10,10,10">
            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <DataGrid x:Name="SubDataGrid" ItemsSource="{Binding SubItems}"
                              CellEditEnding="SubDataGrid_CellEditEnding"
                              AutoGenerateColumns="False"
                              CanUserAddRows="True"
                              CanUserDeleteRows="True"
                              RowBackground="Bisque">
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="Candidate" Binding="{Binding Candidate}" />
                            <DataGridTextColumn Header="Primary" Binding="{Binding Primary}" />
                            <DataGridTextColumn Header="Amount" Binding="{Binding Amount, StringFormat=\{0:N2\}}" />
                            <DataGridTextColumn Header="Previous" Binding="{Binding Previous}" />
                            <DataGridTextColumn Header="Party" Binding="{Binding Party}" />
                        </DataGrid.Columns>
                    </DataGrid>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Voter" Binding="{Binding Voter}" />
                <DataGridTemplateColumn Header="Date" Width="100" SortMemberPath="Date" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding RecordedDate, StringFormat=\{0:MM/dd/yyyy\}}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <DatePicker SelectedDate="{Binding RecordedDate}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Status" Binding="{Binding Status}" />
                <DataGridTextColumn Header="Auto" Binding="{Binding Total, StringFormat=\{0:N2\}}" IsReadOnly="True" >
                    <DataGridTextColumn.CellStyle>
                        <Style>
                            <Setter Property="TextBlock.TextAlignment" Value="Right" />
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
        <StackPanel Grid.Column="1" Margin="10,10,10,10">
            <Button Content="Refresh" Click="Button_Click" />
        </StackPanel>
    </Grid>
</Window>
</code>```

View code-behind:

```<code>using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace WpfAppDataGrid
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        enum SubDataGridColumn
        {
            Candidate,
            Primary,
            Amount,
            Previous,
            Party
        }

        private static MainViewModel vm = new MainViewModel();
        private static bool subAmountChanged = false;

        public MainWindow()
        {
            DataContext = vm;
            InitializeComponent();
        }

        private void SubVerifyEdit(SubItem sub, int column, string txt)
        {
            switch ((SubDataGridColumn)column)
            {
                case SubDataGridColumn.Candidate:
                    if (sub.Candidate != txt)
                        sub.Candidate = txt;
                    break;
                case SubDataGridColumn.Primary:
                    if (sub.Primary != txt)
                        sub.Primary = txt;
                    break;
                case SubDataGridColumn.Amount:
                    var amount = decimal.Parse(txt);
                    if (sub.Amount != amount)
                    {
                        sub.Amount = amount;
                        subAmountChanged = true;
                    }
                    break;
                case SubDataGridColumn.Party:
                    if (sub.Party != txt)
                        sub.Primary = txt;
                    break;
                case SubDataGridColumn.Previous:
                    if (sub.Previous != txt)
                        sub.Previous = txt;
                    break;
                default:
                    break;
            }
        }

        private void SubDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            var sub = (SubItem)e.Row.Item;
            var column = e.Column.DisplayIndex;
            var dep = (DependencyObject)e.EditingElement;
            if (dep is TextBox)
            {
                SubVerifyEdit(sub, column, ((TextBox)dep).Text);
            }
            else if (dep is ComboBox)
            {
                SubVerifyEdit(sub, column, ((ComboBox)dep).SelectedItem.ToString());
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MainDataGrid.Items.Refresh();
        }

        private void MainDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            if (subAmountChanged)
            {
                //var main = (MainItem)MainDataGrid.CurrentItem;
                //var sum = main.SubItems.Sum(s => s.Amount);
                //var manual = main.ManualTotal;
                //var auto = main.AutoTotal;

                //var dep = (DependencyProperty)MainDataGrid.CurrentItem;
                //MainDataGrid.CoerceValue(dep);
                MainDataGrid.Items.Refresh();
                subAmountChanged = false;
            }
        }
    }
}
</code>```

ViewModel:

```<code>using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;

namespace WpfAppDataGrid
{
    public class MainViewModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        public MainViewModel()
        {
            MainItems = new ObservableCollection<MainItem>();

            MainItems.Add(new MainItem("Thomas", DateTime.Now, "Unsure"));
            MainItems[0].SubItems.Add(new SubItem("Roberts", "NH", 27.46m, "Senator", "Republican"));

            MainItems.Add(new MainItem("Arthur", DateTime.Now, "No worries"));
            MainItems[1].SubItems.Add(new SubItem("Johnson", "IA", 47.5m, "Representative", "Republican"));
            MainItems[1].SubItems.Add(new SubItem("Butegieg", "CA", 76.42m, "Senator", "Democrat"));
            MainItems[1].SubItems.Add(new SubItem("Warren", "SC", 14.5m, "Governor", "Democrat"));

            MainItems.Add(new MainItem("Cathy", DateTime.Now, "What now"));
            MainItems[2].SubItems.Add(new SubItem("Biden", "WI", 1456.98m, "Mayor", "Democrat"));

            MainItems.Add(new MainItem("Jonathan", DateTime.Now, "Got this"));
            MainItems[3].SubItems.Add(new SubItem("Foobar", "MI", 5672.3m, "None", "Republican"));
            MainItems[3].SubItems.Add(new SubItem("Sanders", "ME", 1.45m, "Senator", "Democrat"));

            MainItems.Add(new MainItem("Roger", DateTime.Now, "Still undecided"));
            MainItems[4].SubItems.Add(new SubItem("Wakemeyer", "AK", 56m, "Police Chief", "Democrat"));
            MainItems[4].SubItems.Add(new SubItem("Trump", "FL", 982.34m, "Businessman", "Republican"));
        }

        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private ObservableCollection<MainItem> mainItems;
        public ObservableCollection<MainItem> MainItems
        {
            get { return mainItems; }
            set
            {
                mainItems = value;
                NotifyPropertyChanged();
            }
        }
    }
}
</code>```

MainItem class:

```<code>using System;
using System.Collections.ObjectModel;
using System.Linq;

namespace WpfAppDataGrid
{
    public class MainItem
    {
        public MainItem() { }

        public MainItem(string voter, DateTime date, string status)
        {
            Voter = voter;
            RecordedDate = date;
            Status = status;
        }

        public string Voter { get; set; }
        public DateTime RecordedDate { get; set; }
        public string Status { get; set; }
        public decimal Total { get { return SubItems.Sum(s => s.Amount); } }
        public ObservableCollection<SubItem> SubItems { get; set; } = new ObservableCollection<SubItem>();
    }
}
</code>```

SubItem class:

```<code>namespace WpfAppDataGrid
{
    public class SubItem
    {
        public SubItem() { }

        public SubItem(string candidate, string primary, decimal amount, string previous, string party)
        {
            Candidate = candidate;
            Primary = primary;
            Amount = amount;
            Previous = previous;
            Party = party;
        }

        public string Candidate { get; set; }
        public string Primary { get; set; }
        public decimal Amount { get; set; }
        public string Previous { get; set; }
        public string Party { get; set; }
    }
}
</code>```

答:
Both MainItem and SubItem should implement INotifyPropertyChanged.

The latter should raise the PropertyChanged event whenever the Amount property is changed and the MainItem class then needs to subscribe to the PropertyChanged event for all SubItem objects in SubItems and raise the PropertyChanged event for the Total property whenever any of them is changed:

```<code>public class MainItem : INotifyPropertyChanged
{
    public MainItem()
    {
        SubItems.CollectionChanged += SubItems_CollectionChanged;
    }

    public MainItem(string voter, DateTime date, string status)
    {
        Voter = voter;
        RecordedDate = date;
        Status = status;
        SubItems.CollectionChanged += SubItems_CollectionChanged;
    }

    private void SubItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach (object subItem in e.NewItems)
            {
                (subItem as INotifyPropertyChanged).PropertyChanged
                    += new PropertyChangedEventHandler(item_PropertyChanged);
                item_PropertyChanged(sub, new PropertyChangedEventArgs(nameof(Total)));
            }
        }

        if (e.OldItems != null)
        {
            foreach (object country in e.OldItems)
            {
                item_PropertyChanged(sub, new PropertyChangedEventArgs(nameof(Total)));
                (subItem as INotifyPropertyChanged).PropertyChanged
                    -= new PropertyChangedEventHandler(item_PropertyChanged);
            }
        }
    }

    private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        NotifyPropertyChanged(e.PropertyName);
    }

    public string Voter { get; set; }
    public DateTime RecordedDate { get; set; }
    public string Status { get; set; }
    public decimal Total { get { return SubItems.Sum(s => s.Amount); } }
    public ObservableCollection<SubItem> SubItems { get; set; } = new ObservableCollection<SubItem>();

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Body:
I have a main DataGrid (bound to ObservableCollection<MainItem>) with another sub DataGrid  defined in the RowDetailsTemplate (bound to ObservableCollection<SubItem>).  The MainItem.Total property is just a derived value that returns SubItems.Sum(s => s.Amount).  This works great upon displaying the grids.

Yet, when a value in the Amount column is changed and SubItem.Amountupdated, though the MainItem.Total value is correct (it is just a derived value), the main grid doesn't refresh to show the new value.  If I force MainDataGrid.Items.Refresh() (for example, in MainDataGrid_SelectedCellsChanged), the main grid then displays the value now in MainItem.Total.  So, this works but it smells since it is such a brute force method refreshing all visible rows in the main grid.  [NOTE: This situation is similar to the article Update single row in a WPF Datagrid but I'm already using an ObservableCollection.]

I expect this behavior is because the change occurred in ObservableCollection<SubItem> not in ObservableCollection<MainItem> so it doesn't know about it?  But I haven't found an event to raise that informs the main grid that the contents of the bound MainItem.Total has been updated.

[NOTE: The code below is a self-contained sample in case someone wants to build this and try it.  It is based on the same situation in my real project.]

XAML:

<Window x:Class="WpfAppDataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfAppDataGrid"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="100" />
        </Grid.ColumnDefinitions>
        <DataGrid x:Name="MainDataGrid" Grid.Column="0"
                  ItemsSource="{Binding MainItems}"
                  RowDetailsVisibilityMode="VisibleWhenSelected"
                  SelectedCellsChanged="MainDataGrid_SelectedCellsChanged"
                  AutoGenerateColumns="False"
                  CanUserSortColumns="True"
                  CanUserAddRows="True"
                  CanUserDeleteRows="True"
                  RowBackground="AliceBlue"
                  HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch"
                  Margin="10,10,10,10">
            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <DataGrid x:Name="SubDataGrid" ItemsSource="{Binding SubItems}"
                              CellEditEnding="SubDataGrid_CellEditEnding"
                              AutoGenerateColumns="False"
                              CanUserAddRows="True"
                              CanUserDeleteRows="True"
                              RowBackground="Bisque">
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="Candidate" Binding="{Binding Candidate}" />
                            <DataGridTextColumn Header="Primary" Binding="{Binding Primary}" />
                            <DataGridTextColumn Header="Amount" Binding="{Binding Amount, StringFormat=\{0:N2\}}" />
                            <DataGridTextColumn Header="Previous" Binding="{Binding Previous}" />
                            <DataGridTextColumn Header="Party" Binding="{Binding Party}" />
                        </DataGrid.Columns>
                    </DataGrid>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Voter" Binding="{Binding Voter}" />
                <DataGridTemplateColumn Header="Date" Width="100" SortMemberPath="Date" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding RecordedDate, StringFormat=\{0:MM/dd/yyyy\}}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <DatePicker SelectedDate="{Binding RecordedDate}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Status" Binding="{Binding Status}" />
                <DataGridTextColumn Header="Auto" Binding="{Binding Total, StringFormat=\{0:N2\}}" IsReadOnly="True" >
                    <DataGridTextColumn.CellStyle>

                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
        <StackPanel Grid.Column="1" Margin="10,10,10,10">
            <Button Content="Refresh" Click="Button_Click" />
        </StackPanel>
    </Grid>
</Window>

View code-behind:

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace WpfAppDataGrid
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        enum SubDataGridColumn
        {
            Candidate,
            Primary,
            Amount,
            Previous,
            Party
        }

        private static MainViewModel vm = new MainViewModel();
        private static bool subAmountChanged = false;

        public MainWindow()
        {
            DataContext = vm;
            InitializeComponent();
        }

        private void SubVerifyEdit(SubItem sub, int column, string txt)
        {
            switch ((SubDataGridColumn)column)
            {
                case SubDataGridColumn.Candidate:
                    if (sub.Candidate != txt)
                        sub.Candidate = txt;
                    break;
                case SubDataGridColumn.Primary:
                    if (sub.Primary != txt)
                        sub.Primary = txt;
                    break;
                case SubDataGridColumn.Amount:
                    var amount = decimal.Parse(txt);
                    if (sub.Amount != amount)
                    {
                        sub.Amount = amount;
                        subAmountChanged = true;
                    }
                    break;
                case SubDataGridColumn.Party:
                    if (sub.Party != txt)
                        sub.Primary = txt;
                    break;
                case SubDataGridColumn.Previous:
                    if (sub.Previous != txt)
                        sub.Previous = txt;
                    break;
                default:
                    break;
            }
        }

        private void SubDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            var sub = (SubItem)e.Row.Item;
            var column = e.Column.DisplayIndex;
            var dep = (DependencyObject)e.EditingElement;
            if (dep is TextBox)
            {
                SubVerifyEdit(sub, column, ((TextBox)dep).Text);
            }
            else if (dep is ComboBox)
            {
                SubVerifyEdit(sub, column, ((ComboBox)dep).SelectedItem.ToString());
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MainDataGrid.Items.Refresh();
        }

        private void MainDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            if (subAmountChanged)
            {
                //var main = (MainItem)MainDataGrid.CurrentItem;
                //var sum = main.SubItems.Sum(s => s.Amount);
                //var manual = main.ManualTotal;
                //var auto = main.AutoTotal;

                //var dep = (DependencyProperty)MainDataGrid.CurrentItem;
                //MainDataGrid.CoerceValue(dep);
                MainDataGrid.Items.Refresh();
                subAmountChanged = false;
            }
        }
    }
}

ViewModel:

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;

namespace WpfAppDataGrid
{
    public class MainViewModel : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        public MainViewModel()
        {
            MainItems = new ObservableCollection<MainItem>();

            MainItems.Add(new MainItem("Thomas", DateTime.Now, "Unsure"));
            MainItems[0].SubItems.Add(new SubItem("Roberts", "NH", 27.46m, "Senator", "Republican"));

            MainItems.Add(new MainItem("Arthur", DateTime.Now, "No worries"));
            MainItems[1].SubItems.Add(new SubItem("Johnson", "IA", 47.5m, "Representative", "Republican"));
            MainItems[1].SubItems.Add(new SubItem("Butegieg", "CA", 76.42m, "Senator", "Democrat"));
            MainItems[1].SubItems.Add(new SubItem("Warren", "SC", 14.5m, "Governor", "Democrat"));

            MainItems.Add(new MainItem("Cathy", DateTime.Now, "What now"));
            MainItems[2].SubItems.Add(new SubItem("Biden", "WI", 1456.98m, "Mayor", "Democrat"));

            MainItems.Add(new MainItem("Jonathan", DateTime.Now, "Got this"));
            MainItems[3].SubItems.Add(new SubItem("Foobar", "MI", 5672.3m, "None", "Republican"));
            MainItems[3].SubItems.Add(new SubItem("Sanders", "ME", 1.45m, "Senator", "Democrat"));

            MainItems.Add(new MainItem("Roger", DateTime.Now, "Still undecided"));
            MainItems[4].SubItems.Add(new SubItem("Wakemeyer", "AK", 56m, "Police Chief", "Democrat"));
            MainItems[4].SubItems.Add(new SubItem("Trump", "FL", 982.34m, "Businessman", "Republican"));
        }

        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private ObservableCollection<MainItem> mainItems;
        public ObservableCollection<MainItem> MainItems
        {
            get { return mainItems; }
            set
            {
                mainItems = value;
                NotifyPropertyChanged();
            }
        }
    }
}

MainItem class:

using System;
using System.Collections.ObjectModel;
using System.Linq;

namespace WpfAppDataGrid
{
    public class MainItem
    {
        public MainItem() { }

        public MainItem(string voter, DateTime date, string status)
        {
            Voter = voter;
            RecordedDate = date;
            Status = status;
        }

        public string Voter { get; set; }
        public DateTime RecordedDate { get; set; }
        public string Status { get; set; }
        public decimal Total { get { return SubItems.Sum(s => s.Amount); } }
        public ObservableCollection<SubItem> SubItems { get; set; } = new ObservableCollection<SubItem>();
    }
}

SubItem class:

namespace WpfAppDataGrid
{
    public class SubItem
    {
        public SubItem() { }

        public SubItem(string candidate, string primary, decimal amount, string previous, string party)
        {
            Candidate = candidate;
            Primary = primary;
            Amount = amount;
            Previous = previous;
            Party = party;
        }

        public string Candidate { get; set; }
        public string Primary { get; set; }
        public decimal Amount { get; set; }
        public string Previous { get; set; }
        public string Party { get; set; }
    }
}

Body:
Both MainItem and SubItem should implement INotifyPropertyChanged.

The latter should raise the PropertyChanged event whenever the Amount property is changed and the MainItem class then needs to subscribe to the PropertyChanged event for all SubItem objects in SubItems and raise the PropertyChanged event for the Total property whenever any of them is changed:

public class MainItem : INotifyPropertyChanged
{
    public MainItem()
    {
        SubItems.CollectionChanged += SubItems_CollectionChanged;
    }

    public MainItem(string voter, DateTime date, string status)
    {
        Voter = voter;
        RecordedDate = date;
        Status = status;
        SubItems.CollectionChanged += SubItems_CollectionChanged;
    }

    private void SubItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach (object subItem in e.NewItems)
            {
                (subItem as INotifyPropertyChanged).PropertyChanged
                    += new PropertyChangedEventHandler(item_PropertyChanged);
                item_PropertyChanged(sub, new PropertyChangedEventArgs(nameof(Total)));
            }
        }

        if (e.OldItems != null)
        {
            foreach (object country in e.OldItems)
            {
                item_PropertyChanged(sub, new PropertyChangedEventArgs(nameof(Total)));
                (subItem as INotifyPropertyChanged).PropertyChanged
                    -= new PropertyChangedEventHandler(item_PropertyChanged);
            }
        }
    }

    private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        NotifyPropertyChanged(e.PropertyName);
    }

    public string Voter { get; set; }
    public DateTime RecordedDate { get; set; }
    public string Status { get; set; }
    public decimal Total { get { return SubItems.Sum(s => s.Amount); } }
    public ObservableCollection<SubItem> SubItems { get; set; } = new ObservableCollection<SubItem>();

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}


问:
How do I solve the staircase problem on Hacker rank
So, I'm trying to do the staircase problem in hacker rank, I'm trying to achieve it with C

The problem : https://www.hackerrank.com/challenges/staircase/problem

```<code>int i,j,k;
for(i=0;i<n;i++)
{
    for(j=i;j<n;j++)
    {
        printf(" ");
    }
    for(k=0;k<=i;k++)
    {
        printf("#");
    }
    printf("\n");
}
</code>```

}

But all the test cases are failing for the following code, any input would be really helpful :)

答:
I don't know how would you solve, but I would do this:</p>

```<code>#include <stdio.h>

int main()
{
    int n = 4;
    for (int i = n; i > 0; i--) {
        printf("%*s", i - 1 , ""); // print i - 1 number of spaces
        for (int j = n - i + 1; j > 0; j--)
            printf("#"); // printing n - i + 1 number of '#'
        printf("\n");
    }
    return 0;
}
</code>```

Body:
So, I'm trying to do the staircase problem in hacker rank, I'm trying to achieve it with C

The problem : https://www.hackerrank.com/challenges/staircase/problem

int i,j,k;
for(i=0;i<n;i++)
{
    for(j=i;j<n;j++)
    {
        printf(" ");
    }
    for(k=0;k<=i;k++)
    {
        printf("#");
    }
    printf("\n");
}

}

But all the test cases are failing for the following code, any input would be really helpful :)

Body:
I don't know how would you solve, but I would do this:

#include <stdio.h>

int main()
{
    int n = 4;
    for (int i = n; i > 0; i--) {
        printf("%*s", i - 1 , ""); // print i - 1 number of spaces
        for (int j = n - i + 1; j > 0; j--)
            printf("#"); // printing n - i + 1 number of '#'
        printf("\n");
    }
    return 0;
}


问:
SQL select only last entry of date from a calculated field
Hey I'm trying to visualize a past 30 days trend as a line graph in metabase and therefore have to query the data in a right way.

The table looks like this:

```<code>    DATE                          SCORE
September 7, 2019, 12:00 AM         3
September 7, 2019, 12:00 AM         4
September 8, 2019, 12:00 AM         9
September 9, 2019, 12:00 AM         10
</code>```

I tried this query which calculates the NPS and the rolling sum over the last 30 rows.

```<code>select DATE,
        CASE
            WHEN SCORE <= 6 THEN '-1'
            WHEN SCORE <= 8 THEN '0'
            WHEN SCORE > 8 THEN '1'
        END AS NPS
        ,SUM(NPS) OVER(ORDER BY DATE ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) AS NPSTotal
FROM Table;
</code>```

Which looks like this

```<code>    DATE                          NPS    NPSTotal
September 7, 2019, 12:00 AM         -1    -1
September 7, 2019, 12:00 AM         -1    -2
September 8, 2019, 12:00 AM         1     -1
September 9, 2019, 12:00 AM         1      0
</code>```

However, if I want to plot the results in metabase and put the date on the x-axis it naturally aggregates the NPSTotal, giving me a -3 for the 7 September instead of -2. I think the result of my query should look like this.

```<code>    DATE                        NPSTotal
September 7, 2019, 12:00 AM       -2
September 8, 2019, 12:00 AM       -1
September 9, 2019, 12:00 AM        0
</code>```

So I need two things:
1. Sum the NPS over the date of the column and all votes from the last 30 days instead of rows.
2. The output should give out only one NPSTotal entry per date, which should be the last value.

Would be happy if somebody has a solution for this.

答:
If you want one row per date, then use aggregation.  That would seem to be:

```<code>SELECT DATE, MIN(NPSTotal) as NPSTotal
FROM (SELECT DATE,
             (CASE WHEN SCORE <= 6 THEN '-1'
                   WHEN SCORE <= 8 THEN '0'
                   WHEN SCORE > 8 THEN '1'
              END) AS NPS,
             SUM(NPS) OVER (ORDER BY DATE ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) AS NPSTotal
     FROM Table
    ) t
GROUP BY DATE;
</code>```

It is unclear how to resolve ties in your data.  This uses MIN().

Body:
Hey I'm trying to visualize a past 30 days trend as a line graph in metabase and therefore have to query the data in a right way.

The table looks like this:

    DATE                          SCORE
September 7, 2019, 12:00 AM         3
September 7, 2019, 12:00 AM         4
September 8, 2019, 12:00 AM         9
September 9, 2019, 12:00 AM         10

I tried this query which calculates the NPS and the rolling sum over the last 30 rows.

select DATE,
        CASE
            WHEN SCORE <= 6 THEN '-1'
            WHEN SCORE <= 8 THEN '0'
            WHEN SCORE > 8 THEN '1'
        END AS NPS
        ,SUM(NPS) OVER(ORDER BY DATE ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) AS NPSTotal
FROM Table;

Which looks like this

    DATE                          NPS    NPSTotal
September 7, 2019, 12:00 AM         -1    -1
September 7, 2019, 12:00 AM         -1    -2
September 8, 2019, 12:00 AM         1     -1
September 9, 2019, 12:00 AM         1      0

However, if I want to plot the results in metabase and put the date on the x-axis it naturally aggregates the NPSTotal, giving me a -3 for the 7 September instead of -2. I think the result of my query should look like this.

    DATE                        NPSTotal
September 7, 2019, 12:00 AM       -2
September 8, 2019, 12:00 AM       -1
September 9, 2019, 12:00 AM        0

So I need two things:
1. Sum the NPS over the date of the column and all votes from the last 30 days instead of rows.
2. The output should give out only one NPSTotal entry per date, which should be the last value.

Would be happy if somebody has a solution for this.

Body:
If you want one row per date, then use aggregation.  That would seem to be:

SELECT DATE, MIN(NPSTotal) as NPSTotal
FROM (SELECT DATE,
             (CASE WHEN SCORE <= 6 THEN '-1'
                   WHEN SCORE <= 8 THEN '0'
                   WHEN SCORE > 8 THEN '1'
              END) AS NPS,
             SUM(NPS) OVER (ORDER BY DATE ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) AS NPSTotal
     FROM Table
    ) t
GROUP BY DATE;

It is unclear how to resolve ties in your data.  This uses MIN().


问:
MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms
I am trying to create a fullstack app reading the following tutorial:

https://medium.com/javascript-in-plain-english/full-stack-mongodb-react-node-js-express-js-in-one-simple-app-6cc8ed6de274

I followed all steps and then tried to run:

```<code>node server.js
</code>```

But I got the following error:

MongoDB connection error: MongoTimeoutError: Server selection timed
  out after 30000 ms
      at Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9)
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7) {   name: 'MongoTimeoutError',   reason: Error: connect ETIMEDOUT
  99.80.11.208:27017
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1128:14) {
      name: 'MongoNetworkError',
      [Symbol(mongoErrorContextSymbol)]: {}   },   [Symbol(mongoErrorContextSymbol)]: {} } (node:42892)
  UnhandledPromiseRejectionWarning: MongoTimeoutError: Server selection
  timed out after 30000 ms
      at Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9)
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7)

My code at server.js is as follows:

```<code>const mongoose = require('mongoose');
const router = express.Router();

// this is our MongoDB database
const dbRoute =
    'mongodb+srv://user:<password>@cluster0-3zrv8.mongodb.net/test?retryWrites=true&w=majority';

mongoose.Promise = global.Promise;

// connects our back end code with the database
mongoose.connect(dbRoute,
    {   useNewUrlParser: true,
        useUnifiedTopology: true
    });

let db = mongoose.connection;

db.once('open', () => console.log('connected to the database'));
</code>```

Any suggestions?

答: Are you using any Antivirus, Firewall, VPN or on the restricted network (e.g. work/commercial Wi-Fi/LAN connection)? Then try to turn it off/reconnect to a different network. Some IPs/connections might be blocked by the administrator of a network that you're using or simply antivirus might have firewall policies. Even though if you have 0.0.0.0 in your IP Address at the MongoDB Atlas.

Body:
I am trying to create a fullstack app reading the following tutorial:

https://medium.com/javascript-in-plain-english/full-stack-mongodb-react-node-js-express-js-in-one-simple-app-6cc8ed6de274

I followed all steps and then tried to run:

node server.js

But I got the following error:

MongoDB connection error: MongoTimeoutError: Server selection timed
  out after 30000 ms
      at Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9)
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7) {   name: 'MongoTimeoutError',   reason: Error: connect ETIMEDOUT
  99.80.11.208:27017
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1128:14) {
      name: 'MongoNetworkError',
      [Symbol(mongoErrorContextSymbol)]: {}   },   [Symbol(mongoErrorContextSymbol)]: {} } (node:42892)
  UnhandledPromiseRejectionWarning: MongoTimeoutError: Server selection
  timed out after 30000 ms
      at Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9)
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7)

My code at server.js is as follows:

const mongoose = require('mongoose');
const router = express.Router();

// this is our MongoDB database
const dbRoute =
    'mongodb+srv://user:<password>@cluster0-3zrv8.mongodb.net/test?retryWrites=true&w=majority';

mongoose.Promise = global.Promise;

// connects our back end code with the database
mongoose.connect(dbRoute,
    {   useNewUrlParser: true,
        useUnifiedTopology: true
    });

let db = mongoose.connection;

db.once('open', () => console.log('connected to the database'));

Any suggestions?


问:
Angular Typescript filtering object array not working
I am trying to filter an array of objects based on value. Of the following console.log, only the first on is giving the expected result:

```<code>console.log('log1: ', sf);
console.log('log2: ', sf.filter(f => true));
console.log('log3: ', sf.filter(f => f.Specification.FormSelector === 'app-g-form'));
console.log('log4: ', sf.findIndex(f => f.Specification.FormSelector.includes('app-g-form')));
</code>```

The results of the above is:

For log2, log3 and log4 I was expecting the console output to be the same as that for log1. The output log1 shows that sf does contain valid data.

答:
Thanks for the comments.

I may have got this working.  I was setting parts of the array with:

```<code>const sf1: GSubForm = {Specification: this.detailSpecification};
this.specification.SubForms.push(sf1);
</code>```

The above code was placed an observable I was using to get data from an API.  After setting the data, I set the SubForms array.  After moving the code out of the observable and placing directly in ngOnInit(){} everything is working.

Not sure why one way works and not the other, but I'm happy it is moving forward.

Body:
I am trying to filter an array of objects based on value. Of the following console.log, only the first on is giving the expected result:

console.log('log1: ', sf);
console.log('log2: ', sf.filter(f => true));
console.log('log3: ', sf.filter(f => f.Specification.FormSelector === 'app-g-form'));
console.log('log4: ', sf.findIndex(f => f.Specification.FormSelector.includes('app-g-form')));

The results of the above is:

For log2, log3 and log4 I was expecting the console output to be the same as that for log1. The output log1 shows that sf does contain valid data.

Body:
Thanks for the comments.

I may have got this working.  I was setting parts of the array with:

const sf1: GSubForm = {Specification: this.detailSpecification};
this.specification.SubForms.push(sf1);

The above code was placed an observable I was using to get data from an API.  After setting the data, I set the SubForms array.  After moving the code out of the observable and placing directly in ngOnInit(){} everything is working.

Not sure why one way works and not the other, but I'm happy it is moving forward.


问:
Magento htaccess Rewrite and Redirect
On a Magento based ecommerce site I am trying to remove index.php from URLs as well as 301 redirect non-www to www.

Default URL: www.example.com/index.php/super-cool-product.html

Desired Product URL: www.example.com/super-cool-product.html

Also 301 redirecting non-www to www:

example.com/super-cool-product.html

to:

www.example.com/super-cool-product.html

As well as:

www.example.com/index.html

to:

www.example.com

This is what I currently have:

```<code>RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301]

RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.rejuvahealth.com/$1 [R=301,NC,L]

RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ http://www.rejuvahealth.com/$1 [R=301,NC,L]
</code>```

答:
To 301 redirect index.html:

```<code>Options +FollowSymLinks
RewriteEngine on
redirect 301 /index.html http://www.example.co.uk/
</code>```

If you configure your Base URLs correctly, Magento should automatically redirect to the www. version.

For index.php rewrites, go to Configuration > Web > Use Web Server Rewrites and change to 'Yes'.

Now open your htaccess and change this line:

```<code>#RewriteBase /magento/
</code>```

to this:

```<code>RewriteBase /
</code>```

Assuming that your Magento folder is on the root. Be careful when using web rewrites though and ensure you back up before making any changes.

Title: Magento htaccess Rewrite and Redirect

Body:
On a Magento based ecommerce site I am trying to remove index.php from URLs as well as 301 redirect non-www to www.

Default URL: www.example.com/index.php/super-cool-product.html

Desired Product URL: www.example.com/super-cool-product.html

Also 301 redirecting non-www to www:

example.com/super-cool-product.html

to:

www.example.com/super-cool-product.html

As well as:

www.example.com/index.html

to:

www.example.com

This is what I currently have:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301]

RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.rejuvahealth.com/$1 [R=301,NC,L]

RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ http://www.rejuvahealth.com/$1 [R=301,NC,L]

Body:
To 301 redirect index.html:

Options +FollowSymLinks
RewriteEngine on
redirect 301 /index.html http://www.example.co.uk/

If you configure your Base URLs correctly, Magento should automatically redirect to the www. version.

For index.php rewrites, go to Configuration > Web > Use Web Server Rewrites and change to 'Yes'.

Now open your htaccess and change this line:

#RewriteBase /magento/

to this:

RewriteBase /

Assuming that your Magento folder is on the root. Be careful when using web rewrites though and ensure you back up before making any changes.


答:
how about something like this:

const isSortedAscending = (v, i, a) => i === 0 || v >= a[i - 1];
const isSortedDescending = (v, i, a) => i === 0 || v <= a[i - 1];

const versionNumbersAscending = [1, 2, 3];
console.log(`Result ascending order: %o`, versionNumbersAscending.every(isSortedAscending));

const versionNumbersDescending = [3, 2, 1];
console.log(`Result descending order: %o`, versionNumbersDescending.every(isSortedDescending));

const versionNumbersAscending2 = [1, 2, 3, 3, 4, 5, 6, 6, 6, 7, 8, 9];
console.log(`arbitrary length arrays: %o`, versionNumbersAscending2.every(isSortedAscending));

console.log(`should fail: %o`, [1, 2, 3, 2, 4, 5].every(isSortedAscending));```

Title: Checking the content of an array with comparison operators, concerning a specified order

Body:
I need a function which checks an array with integers. The integers have to be either in ascending order or in descending order. That depends from case to case.

I have figured out the following solution:

const areVersionNumbersInExpectedOrder = (aNums, sExpectedOrder = "ascending") => {
            let passed = false;

            if (sExpectedOrder === "ascending") {
                if (aNums[0] < aNums[1] && aNums[1] < aNums[2]) {
                    passed = true;
                }
            } else if (sExpectedOrder === "descending") {
                if (aNums[0] > aNums[1] && aNums[1] > aNums[2]) {
                    passed = true;
                }
            }

            return passed
        };

        const versionNumbersAscending = [1, 2, 3];
        console.log(
            `Result ascending order: ${areVersionNumbersInExpectedOrder(versionNumbersAscending, "ascending")}`);

        const versionNumbersDescending = [3, 2, 1];
        console.log(
            `Result descending order: ${areVersionNumbersInExpectedOrder(versionNumbersDescending, "descending")}`);

Basically it works for me, but it is ugly. Especially the nested ifs.

Is there are better way to solve the task?


问:
Using Kafka for syncing data between two microservices
I am trying to use kakfa to sync data for two microservices A & B.

A stages some data for a group of employees in a company in a database table. Then end user will trigger an event from UI to A's backend service where it will send kakfa message(s) to a topic B is subscribed to.

B then takes the data either from a message or from a staged table, validates it and persist to its own database table.

Questions I have are..

Employees can range from 10 to 1000s per company, and there could be multiple companies trying to sync the data at certain time of the year. So performance is a concern. What would be a good way to divide the load? meaning.. should I design the message to be at employee level? This would mean there could be thousands of messages although design wise it would be the simplest. Or should it be at a company level? or group of employees within a company? Microservice is not doing much processing and persisting to the table.. Would it able to handle the load? What would be the limiting factor?

Data we are handling is JSON stored in DB. Would it be better to have a staging table and look up from B using some sort of primary key in the message? or is having all the data within a message be fine? JSON is not that big per employee data, but if aggregated to a group of employee let's say 100s, it may be 10-100 Kilobytes. Are we buying much from looking up data from the table?

We need to be able to track the status/errors, so that end user is aware of any issues and perform action to correct data and/or try resync. Some approach I thought of was creating a table, call it BATCH_JOB and BATCH_TASK table to keep track of request at the job level (UI event for a group of employees as mentioned which trigger the resync process) and task (employee level). Or would there be a cleaner approach?

Any help/tips of design would be appreciated.

答:
What would be a good way to divide the load?

The short answer is using custom partitioning schemes with a reasonably large number of partitions. Say 100.

Or you can create a topic per company, depending on if you are using different record schemas per topic

Are we buying much from looking up data from the table?

Well, you cannot query a topic as easily as a table, so that's the benefit... You could also use a KTable and interactive queries

Data we are handling is JSON stored in DB

I assume you're not just putting one BLOB column into the database (and you've not clarified what database you're using either).

Personally, I'd suggest you use Avro and Kafka Connect to sink topics into databases. That's the recommended solution for such a task within the Kafka APIs without introducing other projects like Spark or writing your own database code

We need to be able to track the status/errors, so that end user is aware of any issues and perform action to correct data

Tables could work, but if you can write records to a table, you can also write events to another Kafka topic and get "notifications" from that


答:
```<code>SELECT *
FROM {your_table}
WHERE {time_stamp_field} < CURDATE()
</code>```

Or, you could do

```<code>SELECT *
FROM  {your_table}
WHERE {time_stamp_field} <= DATE_SUB( CURDATE(), INTERVAL 1 DAY )
</code>```

So if CURDATE() returns 2011-05-16, DATE_SUB( CURDATE(), INTERVAL 1 DAY ) evaluates to 2011-05-15.

Title: How to check for records that are older than today in PHP?

Body:
I've set up a timestamp field with extra set to ON UPDATE CURRENT_TIMESTAMP.
It works but I have a question:

I'd like to check for all records which are older than today - how would I do that?

Body:
SELECT *
FROM {your_table}
WHERE {time_stamp_field} < CURDATE()

Or, you could do

SELECT *
FROM  {your_table}
WHERE {time_stamp_field} <= DATE_SUB( CURDATE(), INTERVAL 1 DAY )

So if CURDATE() returns 2011-05-16, DATE_SUB( CURDATE(), INTERVAL 1 DAY ) evaluates to 2011-05-15.


问:
Is there a command to use in SQL to extract data based on a date within the data?
I'm am trying to set up an auto report that will generate bi-weekly, therefore, I don't want all the date included in the prior extract to be included in the next extract.

```<code>SELECT request_id, request_date
FROM request_table_1
WHERE ???
</code>```

Unfiltered data:

```<code>Request ID  Request Date
1       12/19/2019 10:21:31 PM
2       12/23/2019 10:22:26 PM
3       12/26/2019 10:21:58 PM
4       12/30/2019 10:23:20 PM
5       1/2/2020 10:21:11 PM
6       1/6/2020 10:23:27 PM
7       1/9/2020 10:21:13 PM
8       1/16/2020 10:22:07 PM
9       1/20/2020 10:22:25 PM
10      1/23/2020 10:21:30 PM
11      1/27/2020 10:20:56 PM
12      1/30/2020 10:25:55 PM
13      2/3/2020 10:25:18 PM
14      2/6/2020 10:21:57 PM
15      2/10/2020 10:21:43 PM
16      2/13/2020 10:32:11 PM
</code>```

What can I put under WHERE so that the report only extracts the requests that were generated withing the past 14 days from the current date?

答:
Something like this:</p>

```<code>where date_column >= trunc(sysdate) - 14
</code>```

Body:
I'm am trying to set up an auto report that will generate bi-weekly, therefore, I don't want all the date included in the prior extract to be included in the next extract.

SELECT request_id, request_date
FROM request_table_1
WHERE ???

Unfiltered data:

Request ID  Request Date
1       12/19/2019 10:21:31 PM
2       12/23/2019 10:22:26 PM
3       12/26/2019 10:21:58 PM
4       12/30/2019 10:23:20 PM
5       1/2/2020 10:21:11 PM
6       1/6/2020 10:23:27 PM
7       1/9/2020 10:21:13 PM
8       1/16/2020 10:22:07 PM
9       1/20/2020 10:22:25 PM
10      1/23/2020 10:21:30 PM
11      1/27/2020 10:20:56 PM
12      1/30/2020 10:25:55 PM
13      2/3/2020 10:25:18 PM
14      2/6/2020 10:21:57 PM
15      2/10/2020 10:21:43 PM
16      2/13/2020 10:32:11 PM

What can I put under WHERE so that the report only extracts the requests that were generated withing the past 14 days from the current date?

Body:
Something like this:

where date_column >= trunc(sysdate) - 14


问:
How to place a catagory between two ranges?
im looking to place a category based off two numbers and two ranges. For example i have my isotope data

1

from this data i want to determine the pollution source based on these two ranges

eg the inputs are the isotope data 15N and 18O and the output is source or in some cases multiple sources if ranges overlap.

so for example if 15N is 4 and 18O is 22 then the source is Nitrate Fertilizer

Sorry if my explanation is confusing!

答:
You can try following array formula:

```<code>{=IFERROR(INDEX($A$3:$A$9;AGGREGATE(15;6;((ROW($A$3:$A$9)-ROW($A$2))/(($I3>=$B$3:$B$9)*($I3<=$C$3:$C$9)*($J3>=$D$3:$D$9)*($J3<=$E$3:$E$9)));COLUMNS($K$1:K$1)));"")}
</code>```

Array formula after editing is confirmed by pressing ctrl + shift + enter

Replace semicolons with comma if needed.

If more than three sources are possible, the formula should be copied further to the right

Body:
You can try following array formula:

{=IFERROR(INDEX($A$3:$A$9;AGGREGATE(15;6;((ROW($A$3:$A$9)-ROW($A$2))/(($I3>=$B$3:$B$9)*($I3<=$C$3:$C$9)*($J3>=$D$3:$D$9)*($J3<=$E$3:$E$9)));COLUMNS($K$1:K$1)));"")}

Array formula after editing is confirmed by pressing ctrl + shift + enter

Replace semicolons with comma if needed.

If more than three sources are possible, the formula should be copied further to the right


问:
Python how to delete a specific value from a dictionary key with multiple values?
I have a dictionary with multiple values per key and each value has two elements (possibly more). I would like to iterate over each value-pair for each key and delete those values-pairs that meet some criteria. Here for instance I would like to delete the second value pair for the key A; that is: ('Ok!', '0'):

```<code>myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
</code>```

to:

```<code>myDict = {'A': [('Yes!', '8')], 'B': [('No!', '2')]}
</code>```

I can iterate over the dictionary by key or value, but can't figure out how I delete a specific value.

答:
You can also do like this:

```<code>myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
del myDict['A'][1]
print(myDict)
</code>```

Explanation :

myDict['A'] - It will grab the Value w.r.t Key A

myDict['A'][1] - It will grab first index tuple

del myDict['A'][1] - now this will delete that tuple

Body:
I have a dictionary with multiple values per key and each value has two elements (possibly more). I would like to iterate over each value-pair for each key and delete those values-pairs that meet some criteria. Here for instance I would like to delete the second value pair for the key A; that is: ('Ok!', '0'):

myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}

to:

myDict = {'A': [('Yes!', '8')], 'B': [('No!', '2')]}

I can iterate over the dictionary by key or value, but can't figure out how I delete a specific value.

Body:
You can also do like this:

myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
del myDict['A'][1]
print(myDict)

Explanation :

myDict['A'] - It will grab the Value w.r.t Key A

myDict['A'][1] - It will grab first index tuple

del myDict['A'][1] - now this will delete that tuple


问:
How to pop up a window using just the git bash command? [Windows 10]
Does anybody know which command should I use for git bash terminal to pop up a window?

Let's say I changed my directory to Documents from ~ and I just want a single command that will help me load up the Documents folder visuals in the screen without having me to click the mouse.

Also I wonder which git bash command lets the windows 10 to return all the running process.

答:
What you are looking for is probably

```<code>explorer .
</code>```

It will open the windows file explorer in the current directory.
You can't however use

```<code>explorer /home
</code>```

As explorer expects only windows-style paths.

Body:
What you are looking for is probably

explorer .

It will open the windows file explorer in the current directory.
You can't however use

explorer /home

As explorer expects only windows-style paths.


问:
Python while loop with input function and multiple condition checks
I am solving the following problem, and came across the situation where I'm unable to define either decision operators or the while loop properly.

The task:

Customers get a monthly discount depending on the length of contract they take out as shown below:

3 – 6 months        2% discount

7 – 12 months       5% discount

over 12 months      10% discount

The program should ask users for their name and the monthly cost of their game package. It should then ask them to enter the contract length they would like. The maximum contract length is 18 months. The program should finally display the entered details and the final cost of the package with the discount applied.

```<code>contract_length = 0
final_cost = 0

#prompt the user to enter their name
user_name = input("What is your name? ")

#prompt the user to enter monthly cost for the game package
package_cost = float(input("Monthly cost of your game package: "))

while contract_length > 0 and contract_length <= 18:

    #prompt the user to enter the contract length
    contract_length = int(input("Enter the contract length you would like: "))

    #selection statement to calculate final cost
    if contract_length > 12:
        discount = (package_cost * 0.1)
        final_cost = format(package_cost - discount,".2f")

    elif contract_length > 6:
        discount = (package_cost * 0.05)
        final_cost = format(package_cost - discount, ".2f")

    elif contract_length >= 3:
        discount = (package_cost * 0.02)
        final_cost = format(package_cost - discount, ".2f")
    else:
        print("Invalid entry")

#display results
print("Name " +user_name)
print("Package Cost £",str(package_cost))
print("Months in Contract " , str(contract_length))
print("The final cost is £",str(final_cost))
</code>```

Error I am having

```<code>What is your name? Jhon
Monthly cost of your game package: 35.12
Name Jhon
Package Cost £ 35.12
Months in Contract  0
The final cost is £ 0
>>>
</code>```

I even tried "and" to "or" but with or operator it's start repeating the input function under while loop. Any help? Thanks.

答:
Here is another solution:

contract_length = 0
final_cost = 0
package_cost = 0
user_name = None

while not user_name:
    user_name = input("What is your name? ")

while package_cost <= 0:
    package_cost = input("Monthly cost of your game package: ")
    if not package_cost.isdigit():
        package_cost = 0
    package_cost = float(package_cost)

while not (3 <= contract_length <= 18):
    contract_length = input("Enter the contract length you would like: ")
    if not contract_length.isdigit():
        contract_length = 0
    contract_length = int(contract_length)

if contract_length > 12:
    discount = 0.1
elif contract_length > 6:
    discount = 0.05
elif contract_length >= 3:
    discount = 0.02
else:
    discount = 0

final_cost = package_cost - (package_cost * discount)

print("Name", user_name)
print("Package Cost £", format(package_cost, ".2f"))
print("Months in Contract", contract_length)
print("The final cost is £", format(final_cost, ".2f"))
```

Body:
I am solving the following problem, and came across the situation where I'm unable to define either decision operators or the while loop properly.

The task:

Customers get a monthly discount depending on the length of contract they take out as shown below:

3 – 6 months        2% discount

7 – 12 months       5% discount

over 12 months      10% discount

The program should ask users for their name and the monthly cost of their game package. It should then ask them to enter the contract length they would like. The maximum contract length is 18 months. The program should finally display the entered details and the final cost of the package with the discount applied.

contract_length = 0
final_cost = 0

#prompt the user to enter their name
user_name = input("What is your name? ")

#prompt the user to enter monthly cost for the game package
package_cost = float(input("Monthly cost of your game package: "))

while contract_length > 0 and contract_length <= 18:

    #prompt the user to enter the contract length
    contract_length = int(input("Enter the contract length you would like: "))

    #selection statement to calculate final cost
    if contract_length > 12:
        discount = (package_cost * 0.1)
        final_cost = format(package_cost - discount,".2f")

    elif contract_length > 6:
        discount = (package_cost * 0.05)
        final_cost = format(package_cost - discount, ".2f")

    elif contract_length >= 3:
        discount = (package_cost * 0.02)
        final_cost = format(package_cost - discount, ".2f")
    else:
        print("Invalid entry")

#display results
print("Name " +user_name)
print("Package Cost £",str(package_cost))
print("Months in Contract " , str(contract_length))
print("The final cost is £",str(final_cost))

Error I am having

What is your name? Jhon
Monthly cost of your game package: 35.12
Name Jhon
Package Cost £ 35.12
Months in Contract  0
The final cost is £ 0
>>>

I even tried "and" to "or" but with or operator it's start repeating the input function under while loop. Any help? Thanks.


问:
Fastlane doesn't work after updating to macOS Catalina [using Fishshell]
"The file '/usr/local/bin/fastlane' specified the interpreter '/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby', which is not an executable command."</p>

答:
Managed to fix it by:

1.) sudo gem install fastlane -NV

After this, try running your fastlane commands. In my case they didn't work but the output did suggest to run the next commands:

2.) sudo gem install bundler:2.0.2

3.) bundle update --bundler

And now I'm running it using:

bundle exec fastlane your_lane
(instead of fastlane your_lane)


问:
SQL to select specific rows from a Teradata table

I have a Teradata table with information about job runs. The attached image shows information stored in table.
There are multiple entries for each job in a day. I am in the process of automating job status based on the start and end time. I want to pick start_time of job V1S0 and end_time of job V5S0 highlighted in red from this table(the job highlighted in yellow run in a single batch). Can someone share SQL to do this.

Thanks  in advance

答:
Do a GROUP BY. Use case expressions to do conditional aggregation, to get  V1S0 start and V5SO end.

```<code>select batch,
       min(case when job_name = 'V1S0' then start_time end),
       max(case when job_name = 'V5S0' then end_time end)
from tablename
where batch = <some batch identifier>
group by batch
</code>```

Body:
Do a GROUP BY. Use case expressions to do conditional aggregation, to get  V1S0 start and V5SO end.

select batch,
       min(case when job_name = 'V1S0' then start_time end),
       max(case when job_name = 'V5S0' then end_time end)
from tablename
where batch = <some batch identifier>
group by batch


问:
How to change text color of TextFormField according to theme
I want to change inputted text color as per the current theme, as text color is not a part of InputDecorationTheme.

As of now the only possible way to change inputted text color is to give style to TextFormField but that also not work when theme gets changed + in that way I need to repeat the similar code for each of my text field available in the app.

答:
You seem to be looking in the InputDecorationTheme instead of the TextTheme.

The color property you are looking for should be textTheme.body1.color as in:

```<code>Theme.of(context).textTheme.body1.color
</code>```

If not this one, it should be another of the textTheme properties.

Body:
You seem to be looking in the InputDecorationTheme instead of the TextTheme.

The color property you are looking for should be textTheme.body1.color as in:

Theme.of(context).textTheme.body1.color

If not this one, it should be another of the textTheme properties.


问:
Attachment should be ther in the form and my email is working , But i want to send an email without attchment in the same form. So how to do that
My email is working but needs to send without attachment. Everything is working properly. cannot delete the attachment. Sometimes need to send with attachment too.</p>

```<code>    Dim smtpserver As New SmtpClient
    Dim mail As New MailMessage()
    smtpserver.Credentials = New Net.NetworkCredential(TextBox4.Text, TextBox5.Text)
    smtpserver.Port = 587
    smtpserver.Host = "smtp.gmail.com"
    mail = New MailMessage
    mail.From = New MailAddress(TextBox4.Text)
    mail.To.Add(TextBox1.Text)
    mail.Subject = TextBox2.Text
    mail.Body = TextBox3.Text
    Dim attach As New Attachment(TextBox6.Text)
    mail.Attachments.Add(attach)
        smtpserver.EnableSsl = True
    Try
        smtpserver.Send(mail)
        MsgBox("Email Sent")
    Catch ex As SmtpException
        MsgBox("Its an Error")
    End Try
</code>```

答:
If looks like your attachment is in TextBox6.Text.  If so, just check it contains something (or better still contains something valid) and only add the attachment if it does.

Something like this

```<code>    If Not String.IsNullorWhitepace(TextBox6.Text) Then
        Dim attach As New Attachment(TextBox6.Text)
        mail.Attachments.Add(attach)
    End If
</code>```

Body:
My email is working but needs to send without attachment. Everything is working properly. cannot delete the attachment. Sometimes need to send with attachment too.

    Dim smtpserver As New SmtpClient
    Dim mail As New MailMessage()
    smtpserver.Credentials = New Net.NetworkCredential(TextBox4.Text, TextBox5.Text)
    smtpserver.Port = 587
    smtpserver.Host = "smtp.gmail.com"
    mail = New MailMessage
    mail.From = New MailAddress(TextBox4.Text)
    mail.To.Add(TextBox1.Text)
    mail.Subject = TextBox2.Text
    mail.Body = TextBox3.Text
    Dim attach As New Attachment(TextBox6.Text)
    mail.Attachments.Add(attach)
        smtpserver.EnableSsl = True
    Try
        smtpserver.Send(mail)
        MsgBox("Email Sent")
    Catch ex As SmtpException
        MsgBox("Its an Error")
    End Try

Body:
If looks like your attachment is in TextBox6.Text.  If so, just check it contains something (or better still contains something valid) and only add the attachment if it does.

Something like this

    If Not String.IsNullorWhitepace(TextBox6.Text) Then
        Dim attach As New Attachment(TextBox6.Text)
        mail.Attachments.Add(attach)
    End If


问:
Postfix screwing up email headers!
I've set up a local dev environment on snow leopard, and have set postfix up to send email via my isp mail server.

I eventually got postfix to work after much frustration, but now when my emails send the header information is bunged up!

I'm using the following php code:

```
$email = "me@mydomain";
$subject = "Email tester";
$body = "Simple test";
$header = "From: me@mydomain \r\n";
$header .= "MIME-VERSION: 1.0\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$phpversion = phpversion();
$header .= "X-Mailer: PHP v$phpversion\r\n";
mail($email,$subject,$body,$header);

echo "message sent!";
```

The To: and Subject: headers display as they should, in the header!, but the rest display in the email body. This makes the email look like the from field in email client is empty.

I've tried a variety of php scripts, some very simple, but its the same thing, headers always displaying in the email body.

I'm thinking it could be a postfix problem, but not sure, anyone encountered this type of problem before?

答:
Use PHP_EOL instead of \r\n in *additional_headers*, i.e. $header in your example. PHP_EOL will substitute the newline correspondingly to the OS you are running on.

Also, message should contain LN only i.e. \n. This is accordingly to PHP documentation.
Each line should be separated with a LF (\n). Lines should not be larger than 70 characters.

Make sure you meet both of criterias in your script - I've tried to achieve it and finally got it working with the default configuration of Postfix.

Title: Postfix screwing up email headers!

Body:
I've set up a local dev environment on snow leopard, and have set postfix up to send email via my isp mail server.

I eventually got postfix to work after much frustration, but now when my emails send the header information is bunged up!

I'm using the following php code:

$email = "me@mydomain";
$subject = "Email tester";
$body = "Simple test";
$header = "From: me@mydomain \r\n";
$header .= "MIME-VERSION: 1.0\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$phpversion = phpversion();
$header .= "X-Mailer: PHP v$phpversion\r\n";
mail($email,$subject,$body,$header);

echo "message sent!";

The To: and Subject: headers display as they should, in the header!, but the rest display in the email body. This makes the email look like the from field in email client is empty.

I've tried a variety of php scripts, some very simple, but its the same thing, headers always displaying in the email body.

I'm thinking it could be a postfix problem, but not sure, anyone encountered this type of problem before?


问:
border only half the side of a div

In the  html div shown above I want a border on only some of the right-side of the div, however border-right sets a border for the whole side.

I have seen many other questions on this topic but the only working answers I have found require using a second div, but I want to know if this can be done without a second div, i.e: by editing the css properties of this div only.

答:
By using pseudo code you can achieve your desire result, please have a look

.wrap{
 height: 100px;
 width: 100px;
 position: relative;
 background: yellow;
}
.wrap::after {
    content: '';
    height: 50px;
    width: 2px;
    position: absolute;
    right: -1px;
    background: black;
    top: 50%;
    transform: translate(0, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">lorem</div></code>```

Title: border only half the side of a div

Body:
By using pseudo code you can achieve your desire result, please have a look

.wrap{
 height: 100px;
 width: 100px;
 position: relative;
 background: yellow;
}
.wrap::after {
    content: '';
    height: 50px;
    width: 2px;
    position: absolute;
    right: -1px;
    background: black;
    top: 50%;
    transform: translate(0, -50%);
}

<div class="wrap">lorem</div>


答: WHERE request_date BETWEEN DATEADD(WEEK, -2, CURRENT_TIMESTAMP) AND CURRENT_TIMESTAMP

Title: Is there a command to use in SQL to extract data based on a date within the data?