问:
Adding shadows to widgets in Flutter
I was trying to add a border shadow effect to a Container in a way that resembles exactly the same design as in the picture below. My initial idea was of using the CustomPaint class feature to do so. However, it hasn't worked out the way I wanted it to. I would honestly like to know how this can be achieved through the use of the CustomPaint class and I apologize for the code that I've written as I'm still trying to get used to CustomPaint. The code and the pictures are as follows:

This is what I intend to achieve:

This is what I have. You can see that the border goes well beyond where it should be and also, the border at the bottom gets clipped and despite adjusting the bottom padding:

This is the code:

```<code>class ProfilePageState extends State<ProfilePage> {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    final textScale = MediaQuery.of(context).textScaleFactor * 1.2;

    // TODO: implement build
    return Scaffold(
      body: ListView(
        children: [
          Container(
            height: height * 1,
            width: width * 1,
            // color: Colors.red,
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('assets/images/filter.png'),
                    fit: BoxFit.cover)),
            child: Column(
              ......
                Padding(
                  padding: EdgeInsets.only(left: width * 0.035),
                  child: Container(
                    width: double.infinity,
                    height: height * 0.25,
                    padding: EdgeInsets.only(
                      left: width * 0.03,
                      top: height * 0.01,
                      // bottom: height * 0.01
                    ),
                    // color: Colors.yellow,
                    child: ProfilePageFavourite(),    //This here is the widget
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

The ProfilePageFavourite widget:

```<code>class ProfilePageFavouriteState extends State<ProfilePageFavourite> {
  // final List<dynamic> _favouritesList = [

  // ];
  var favourite = false;

  void _onPressed() {
    setState(() => favourite = !favourite);
    print(favourite);
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    final textScale = MediaQuery.of(context).textScaleFactor * 1.2;

    // TODO: implement build
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemBuilder: (context, index) => Stack(
        children: [
          CustomPaint(                    //This is where I try using the CustomPaint class
            painter: OrangePainter(),
            child: Container(
              width: width * 0.75,
              margin: EdgeInsets.only(right: width * 0.09),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.yellow,
                  image: DecorationImage(
                      fit: BoxFit.fitWidth,
                      image: AssetImage('assets/images/pub screen 1 (1).png'))),
            ),
          ),
          Positioned(
            top: height * 0.16,
            child: Container(
              height: height * 0.07,
              width: width * 0.75,
              padding: EdgeInsets.only(top: height * 0.008),
              decoration: BoxDecoration(
                  color: Colors.black38,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20),
                      bottomRight: Radius.circular(20))),
              child: Column(
                children: [
                  Row(
                    // mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: width * 0.05),
                        decoration: BoxDecoration(boxShadow: [
                          BoxShadow(
                              color: Colors.red,
                              blurRadius: 35,
                              spreadRadius: 8,
                              offset: Offset(0, 2))
                        ]),
                        child: Image.asset(
                          'assets/icons/dine.png',
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(
                        width: width * 0.02,
                      ),
                      Text(
                        'Sollicitudin',
                        textScaleFactor: textScale,
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                            shadows: [
                              Shadow(
                                  color: Colors.red,
                                  blurRadius: 10,
                                  offset: Offset(0, 2))
                            ]),
                      )
                    ],
                  ),
                  Container(
                      width: double.infinity,
                      // color: Colors.red,
                      padding: EdgeInsets.only(left: width * 0.118),
                      child: CustomRatingBar(4.5))
                ],
              ),
            ),
          ),
          Positioned(
            left: width * 0.58,
            top: height * 0.01,
            child: Container(
              decoration: BoxDecoration(boxShadow: [
                BoxShadow(
                  color: Colors.pink,
                  blurRadius: 80,
                  spreadRadius: 6,
                )
              ]),
              child: !favourite
                  ? IconButton(
                      onPressed: _onPressed,
                      icon: Icon(
                        Icons.favorite,
                        // color: Color.fromRGBO(247, 180, 230, 0.8),
                        color: Colors.pink,
                        size: 50,
                      ))
                  : IconButton(
                      onPressed: _onPressed,
                      icon: Icon(
                        Icons.favorite_border_outlined,
                        color: Colors.pink,
                        size: 50,
                      )),
            ),
          ),
        ],
      ),
      itemCount: 5,
    );
  }
}
</code>```

The CustomPaint Class

```<code>class OrangePainter extends CustomPainter {
  OrangePainter();

  @override
  void paint(Canvas canvas, Size size) {
    final rrectBorder =
        RRect.fromRectAndRadius(Offset.zero & size, Radius.circular(12));
    final rrectShadow =
        RRect.fromRectAndRadius(Offset(0, 2) & size, Radius.circular(12));

    final shadowPaint = Paint()
      ..color = Colors.lightGreen
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..maskFilter = MaskFilter.blur(BlurStyle.solid, 20);

    canvas.drawRRect(rrectShadow, shadowPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}
</code>```

答: I would like to suggest an alternative approach,  Custom Paint is very expensive to use in applications. You could instead wrap your container in a Card() then add your shadowColor: Colors.lightGreen set the **shape: ** to the same as your Container() and you should get the result you desire

Title: Adding shadows to widgets in Flutter

Body:
I was trying to add a border shadow effect to a Container in a way that resembles exactly the same design as in the picture below. My initial idea was of using the CustomPaint class feature to do so. However, it hasn't worked out the way I wanted it to. I would honestly like to know how this can be achieved through the use of the CustomPaint class and I apologize for the code that I've written as I'm still trying to get used to CustomPaint. The code and the pictures are as follows:

This is what I intend to achieve:

This is what I have. You can see that the border goes well beyond where it should be and also, the border at the bottom gets clipped and despite adjusting the bottom padding:

This is the code:

class ProfilePageState extends State<ProfilePage> {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    final textScale = MediaQuery.of(context).textScaleFactor * 1.2;

    // TODO: implement build
    return Scaffold(
      body: ListView(
        children: [
          Container(
            height: height * 1,
            width: width * 1,
            // color: Colors.red,
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('assets/images/filter.png'),
                    fit: BoxFit.cover)),
            child: Column(
              ......
                Padding(
                  padding: EdgeInsets.only(left: width * 0.035),
                  child: Container(
                    width: double.infinity,
                    height: height * 0.25,
                    padding: EdgeInsets.only(
                      left: width * 0.03,
                      top: height * 0.01,
                      // bottom: height * 0.01
                    ),
                    // color: Colors.yellow,
                    child: ProfilePageFavourite(),    //This here is the widget
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

The ProfilePageFavourite widget:

class ProfilePageFavouriteState extends State<ProfilePageFavourite> {
  // final List<dynamic> _favouritesList = [

  // ];
  var favourite = false;

  void _onPressed() {
    setState(() => favourite = !favourite);
    print(favourite);
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    final textScale = MediaQuery.of(context).textScaleFactor * 1.2;

    // TODO: implement build
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemBuilder: (context, index) => Stack(
        children: [
          CustomPaint(                    //This is where I try using the CustomPaint class
            painter: OrangePainter(),
            child: Container(
              width: width * 0.75,
              margin: EdgeInsets.only(right: width * 0.09),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.yellow,
                  image: DecorationImage(
                      fit: BoxFit.fitWidth,
                      image: AssetImage('assets/images/pub screen 1 (1).png'))),
            ),
          ),
          Positioned(
            top: height * 0.16,
            child: Container(
              height: height * 0.07,
              width: width * 0.75,
              padding: EdgeInsets.only(top: height * 0.008),
              decoration: BoxDecoration(
                  color: Colors.black38,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20),
                      bottomRight: Radius.circular(20))),
              child: Column(
                children: [
                  Row(
                    // mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: width * 0.05),
                        decoration: BoxDecoration(boxShadow: [
                          BoxShadow(
                              color: Colors.red,
                              blurRadius: 35,
                              spreadRadius: 8,
                              offset: Offset(0, 2))
                        ]),
                        child: Image.asset(
                          'assets/icons/dine.png',
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(
                        width: width * 0.02,
                      ),
                      Text(
                        'Sollicitudin',
                        textScaleFactor: textScale,
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                            shadows: [
                              Shadow(
                                  color: Colors.red,
                                  blurRadius: 10,
                                  offset: Offset(0, 2))
                            ]),
                      )
                    ],
                  ),
                  Container(
                      width: double.infinity,
                      // color: Colors.red,
                      padding: EdgeInsets.only(left: width * 0.118),
                      child: CustomRatingBar(4.5))
                ],
              ),
            ),
          ),
          Positioned(
            left: width * 0.58,
            top: height * 0.01,
            child: Container(
              decoration: BoxDecoration(boxShadow: [
                BoxShadow(
                  color: Colors.pink,
                  blurRadius: 80,
                  spreadRadius: 6,
                )
              ]),
              child: !favourite
                  ? IconButton(
                      onPressed: _onPressed,
                      icon: Icon(
                        Icons.favorite,
                        // color: Color.fromRGBO(247, 180, 230, 0.8),
                        color: Colors.pink,
                        size: 50,
                      ))
                  : IconButton(
                      onPressed: _onPressed,
                      icon: Icon(
                        Icons.favorite_border_outlined,
                        color: Colors.pink,
                        size: 50,
                      )),
            ),
          ),
        ],
      ),
      itemCount: 5,
    );
  }
}

The CustomPaint Class

class OrangePainter extends CustomPainter {
  OrangePainter();

  @override
  void paint(Canvas canvas, Size size) {
    final rrectBorder =
        RRect.fromRectAndRadius(Offset.zero & size, Radius.circular(12));
    final rrectShadow =
        RRect.fromRectAndRadius(Offset(0, 2) & size, Radius.circular(12));

    final shadowPaint = Paint()
      ..color = Colors.lightGreen
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..maskFilter = MaskFilter.blur(BlurStyle.solid, 20);

    canvas.drawRRect(rrectShadow, shadowPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}


来源: stackexchange

问:
Using asynchrnous operations related on state of another object
I'm facing a problem with asynchronous operations in Vue. As a C# developer I find async-await pattern more obvious than in js/ts especially with Vue.

I have 2 components (non Vuex approach):

```<code>// App.vue
// ...
async beforeCreated() {
  console.log('connecting')
  await WebSocket.connect(...)
  console.log('connected')
}
</code>```
```<code>// ChildComponent.vue
// ...
async mounted() {
  console.log('invoking')
  await WebSocket.Invoke(...)
  console.log('invoked')
}
</code>```

What I get is

```<code>1. connecting
2. invoking
3. invoked
4. connected
</code>```

So I'm not connected and Invoke fails. I've tried do something like this with Vuex but with no luck. Connecting to WebSocket part is simple: use Action and Mutation but the 'Invoking' part is not obvious.

I've tried to execute something like this but getting undefined

```<code>// ChildComponent.vue
// ...
async mounted() {
  await this.$store.state.moduleA.webSocket.Invoke(...) // moduleA is defined but webSocket is not
}
</code>```

Moreover using Vuex's mutations and actions are illogical since I'm not changing state of any object - just invoking some server-side procedure.

How I should implement this in properly? I'm really stuck with this. I'm using TypeScript if this information is relevant somehow.

Vue code:

App.vue

```<code><template>
      <child-component />
</template>

<script lang="ts">
import ChildComponent from './components/ChildComponent.vue';

export default Vue.extend({
  components: { ChildComponent },
  name: 'App',
  async beforeCreate()  {
    await this.$WebSocket.connect(...)
  }
});
</script>
</code>```

ChildComponent.vue

```<code><template>
  <div>something</div>
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  name: 'ChildComponent',
  async mounted() : Promise<void> {
    await this.$WebSocket.Invoke(...)
  },
})
</script>
</code>```

答:
The only problem here is in async/await misundestanding. It's just an syntax sugar on Promises, so your code equals this.

```<code>beforeCreated() {
  console.log('connecting')
  WebSocket.connect(...).then(() => {
    console.log('connected')
  });
}
</code>```

So the beforeCreate hook exits on await line and Vue instance is going down on next hooks. So in this case you should not rely on Vue hooks. Instead, use Websocket event

```<code>async beforeCreated() {
  Websocket.on('open', () => {
    this.websocketIsOpened = true; // should present in data()
  });
  await WebSocket.connect(...)
},
template: `
...
<ChildComponent v-if="websocketIsOpened" />
or
<ChildComponent v-bind="websocketIsOpened" />
</code>```

In second variant you probably need an immediate watcher in child component on this prop to call Invoke method

ContentLicense: CC BY-SA 4.0

Body:
I'm facing a problem with asynchronous operations in Vue. As a C# developer I find async-await pattern more obvious than in js/ts especially with Vue.

I have 2 components (non Vuex approach):

// App.vue
// ...
async beforeCreated() {
  console.log('connecting')
  await WebSocket.connect(...)
  console.log('connected')
}

// ChildComponent.vue
// ...
async mounted() {
  console.log('invoking')
  await WebSocket.Invoke(...)
  console.log('invoked')
}

What I get is

1. connecting
2. invoking
3. invoked
4. connected

So I'm not connected and Invoke fails. I've tried do something like this with Vuex but with no luck. Connecting to WebSocket part is simple: use Action and Mutation but the 'Invoking' part is not obvious.

I've tried to execute something like this but getting undefined

// ChildComponent.vue
// ...
async mounted() {
  await this.$store.state.moduleA.webSocket.Invoke(...) // moduleA is defined but webSocket is not
}

Moreover using Vuex's mutations and actions are illogical since I'm not changing state of any object - just invoking some server-side procedure.

How I should implement this in properly? I'm really stuck with this. I'm using TypeScript if this information is relevant somehow.

Vue code:

App.vue

<template>
      <child-component />
</template>

ChildComponent.vue

<template>

something

</template>

Body:
The only problem here is in async/await misundestanding. It's just an syntax sugar on Promises, so your code equals this.

beforeCreated() {
  console.log('connecting')
  WebSocket.connect(...).then(() => {
    console.log('connected')
  });
}

So the beforeCreate hook exits on await line and Vue instance is going down on next hooks. So in this case you should not rely on Vue hooks. Instead, use Websocket event

async beforeCreated() {
  Websocket.on('open', () => {
    this.websocketIsOpened = true; // should present in data()
  });
  await WebSocket.connect(...)
},
template: `
...
<ChildComponent v-if="websocketIsOpened" />
or
<ChildComponent v-bind="websocketIsOpened" />

In second variant you probably need an immediate watcher in child component on this prop to call Invoke method


问:
aws opensearch custom plugin
i am new to aws opensearch,
is it possible to write custom plugin as we use to do for opeansearch
sample : https://logz.io/blog/opensearch-plugins/

Thanks in advance

答: Unfortunately, AWS managed Opensearch service does not allow to install additional plugins.</p>

Title: aws opensearch custom plugin


问:
assign an ID in each object of array
I have a use case whereby sequential numbers need to be displayed in a table of data in the UI of an app, beginning at 1.  The app is built using Vue and Buefy for the UI component library.  Here is a screenshot of some sample data in such a table:

This needs to have a third column added and should display 1 in the first row and 2 in the second row.

I looked in the Buefy docs to see if their table component has built-in capability to do this but didn't see anything that fit.  If that is the case, the data passed to the table component will need to provide it.

Since the format of the data passed to the table component is an array of objects I was thinking there might be a way to use each object's index, incremented by 1, for this purpose.  But I'm not sure how to get this:

```<code>const data = [
    { color: 'blue', size: 'large', height: 'tall' },
    { color: 'green', size: 'medium', height: 'short' },
    { color: 'purple', size: 'small', height: 'average' }
];
</code>```

to be this:

```<code>const data = [
    { id: '1', color: 'blue', size: 'large', height: 'tall' },
    { id: '2', color: 'green', size: 'medium', height: 'short' },
    { id: '3', color: 'purple', size: 'small', height: 'average' }
];
</code>```

I tried the following but it does not give the desired outcome:

```<code>console.log([...data, ...Object.keys(data)];
</code>```

How can the desired end result be achieved?  I'm looking for a simple approach, if possible.

Also, I was concerned about what happens if an element gets removed from the original array of objects...would that mess up the sequential numbering that's based on the index number?  I tested that situation by executing data.splice(0,1); but examining the results in the console, the objects appear to get re-indexed and therefore it shouldn't be an issue.  Unless someone knows otherwise.

答:
If I understood you correctly try with index:

new Vue({
  el: '#demo',
  data() {
    return {
      items: [
        { color: 'blue', size: 'large', height: 'tall' },
        { color: 'green', size: 'medium', height: 'short' },
        { color: 'purple', size: 'small', height: 'average' }
      ]
    }
  },
  methods: {
    del(i) {
      this.items.splice(i, 1)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="(item, i) in items" :key="i">
    <div>{{ i+1 }} - {{ item.color }}</div>
    <button @click="del(i)">delete</button>
  </div>
</div></code>```

Title: assign an ID in each object of array

Body:
I have a use case whereby sequential numbers need to be displayed in a table of data in the UI of an app, beginning at 1.  The app is built using Vue and Buefy for the UI component library.  Here is a screenshot of some sample data in such a table:

This needs to have a third column added and should display 1 in the first row and 2 in the second row.

I looked in the Buefy docs to see if their table component has built-in capability to do this but didn't see anything that fit.  If that is the case, the data passed to the table component will need to provide it.

Since the format of the data passed to the table component is an array of objects I was thinking there might be a way to use each object's index, incremented by 1, for this purpose.  But I'm not sure how to get this:

const data = [
    { color: 'blue', size: 'large', height: 'tall' },
    { color: 'green', size: 'medium', height: 'short' },
    { color: 'purple', size: 'small', height: 'average' }
];

to be this:

const data = [
    { id: '1', color: 'blue', size: 'large', height: 'tall' },
    { id: '2', color: 'green', size: 'medium', height: 'short' },
    { id: '3', color: 'purple', size: 'small', height: 'average' }
];

I tried the following but it does not give the desired outcome:

console.log([...data, ...Object.keys(data)];

How can the desired end result be achieved?  I'm looking for a simple approach, if possible.

Also, I was concerned about what happens if an element gets removed from the original array of objects...would that mess up the sequential numbering that's based on the index number?  I tested that situation by executing data.splice(0,1); but examining the results in the console, the objects appear to get re-indexed and therefore it shouldn't be an issue.  Unless someone knows otherwise.

Body:
If I understood you correctly try with index:

new Vue({
  el: '#demo',
  data() {
    return {
      items: [
        { color: 'blue', size: 'large', height: 'tall' },
        { color: 'green', size: 'medium', height: 'short' },
        { color: 'purple', size: 'small', height: 'average' }
      ]
    }
  },
  methods: {
    del(i) {
      this.items.splice(i, 1)
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="(item, i) in items" :key="i">
    <div>{{ i+1 }} - {{ item.color }}</div>
    <button @click="del(i)">delete</button>
  </div>
</div>


问:
im a new learner and cant figure out why my code is not working
I have just recently got into coding and have chosen to learn JavaScript as my first language. I have written up code for a Rock, Paper, Scissors game but the wrong outputs come out when I run it? for example I would put my answer as scissors and the computer would choose rock and the game will come out as a tie.

const getUserChoice = userInput => {
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return userInput
  } else {
    return 'Error!'
  }
}

var getComputerChoice = () => {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock'
      break;
    case 1:
      return 'paper'
      break;
    case 2:
      return 'scissors'
      break;
  }
};

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return 'its a tie!';
  };
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'computer won';
    } else {
      return 'user won';
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'scissors') {
      return 'computer won';
    } else {
      return 'user won'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'computer won';
    } else {
      return 'user won'
    }
  }
};

const playGame = () => {
  console.log(`player chose ${getUserChoice('scissors')}`);
  console.log(`computer chose ${getComputerChoice()}`);
  console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
}
playGame();```

答:
Maybe there are more issues, but here are some of them:

Each time you execute getComputerChoice you get a different value because a random value is picked inside:

```<code>  console.log(`player chose ${getUserChoice('scissors')}`);
  console.log(`computer chose ${getComputerChoice()}`);
  console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
</code>```

So you must instead call and store in variables:

```<code>  let playerChose = getUserChoice('scissors');
  let computerChose = getComputerChoice();
  let winner = determineWinner(playerChose, computerChose);
  console.log(`player chose ${playerChose}`);
  console.log(`computer chose ${computerChose}`);
  console.log(winner);
</code>```

You can do it without variables, but be sure not invoking getComputerChoice several times.

Also userInput should be between parenthesis at:

```<code>const getUserChoice = (userInput) => {
</code>```

Body:
Maybe there are more issues, but here are some of them:

Each time you execute getComputerChoice you get a different value because a random value is picked inside:

  console.log(`player chose ${getUserChoice('scissors')}`);
  console.log(`computer chose ${getComputerChoice()}`);
  console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));

So you must instead call and store in variables:

  let playerChose = getUserChoice('scissors');
  let computerChose = getComputerChoice();
  let winner = determineWinner(playerChose, computerChose);
  console.log(`player chose ${playerChose}`);
  console.log(`computer chose ${computerChose}`);
  console.log(winner);

You can do it without variables, but be sure not invoking getComputerChoice several times.

Also userInput should be between parenthesis at:

const getUserChoice = (userInput) => {


问:
Avoiding loops in Microsoft change notifications
I am trying to build a chat app which changes it's online status whenever a user's Microsoft presence changes. And I also do the reverse when a user changes his presence on my chat app using the setPresence api.

So I tried subscribing to the user's presence. I received a change notification and it is of the following structure:

```<code>{
  "value": [
    {
      "id": "lsgTZMr9KwAAA",
      "subscriptionId":"{subscription_guid}",
      "subscriptionExpirationDateTime":"2016-03-19T22:11:09.952Z",
      "clientState":"secretClientValue",
      "changeType":"created",
      "resource":"users/{user_guid}@{tenant_guid}/messages/{long_id_string}",
      "tenantId": "84bd8158-6d4d-4958-8b9f-9d6445542f95",
      "resourceData":
      {
        "Availability":"Busy,
        "Activity":"InACall"
        "id":"{long_id_string}"
      }
    }
  ]
}
</code>```

This change notification has the user availability and activity, but it does not specify which app triggered this presence change. This results in the following loop:

My app changing teams presence -> teams sending me a webhook -> my app changing teams presence because of the webhook -> teams sending me a webhook and so on.

One simple fix would be to not change teams presence if both the app have the same presence. But my app does not have a one to one mapping for every presence value in teams. So it might set ,say, away for multiple states of my app. So when the away webhook arrives, I don't know for which state away was sent. Also while changing states in quick succession in my app, it does not allow me to accurately verify if both app states are in sync.

Is there any possibilities to avoid such loops in change notification webhooks?

答:
My advice would be to not use the presence data in the webhook, but rather when a webhook is triggered go and get the data from graph again.  This will avoid any issues you might get with webhooks coming out of order.

Your app will have to manage state and decide what to do with it, but it sounds like you shouldn't update the presence state in your app unless it really is a change in presence to avoid infinite loops.

Body:
I am trying to build a chat app which changes it's online status whenever a user's Microsoft presence changes. And I also do the reverse when a user changes his presence on my chat app using the setPresence api.

So I tried subscribing to the user's presence. I received a change notification and it is of the following structure:

{
  "value": [
    {
      "id": "lsgTZMr9KwAAA",
      "subscriptionId":"{subscription_guid}",
      "subscriptionExpirationDateTime":"2016-03-19T22:11:09.952Z",
      "clientState":"secretClientValue",
      "changeType":"created",
      "resource":"users/{user_guid}@{tenant_guid}/messages/{long_id_string}",
      "tenantId": "84bd8158-6d4d-4958-8b9f-9d6445542f95",
      "resourceData":
      {
        "Availability":"Busy,
        "Activity":"InACall"
        "id":"{long_id_string}"
      }
    }
  ]
}

This change notification has the user availability and activity, but it does not specify which app triggered this presence change. This results in the following loop:

My app changing teams presence -> teams sending me a webhook -> my app changing teams presence because of the webhook -> teams sending me a webhook and so on.

One simple fix would be to not change teams presence if both the app have the same presence. But my app does not have a one to one mapping for every presence value in teams. So it might set ,say, away for multiple states of my app. So when the away webhook arrives, I don't know for which state away was sent. Also while changing states in quick succession in my app, it does not allow me to accurately verify if both app states are in sync.

Is there any possibilities to avoid such loops in change notification webhooks?


问:
Can't get data from ZenMoney API (OAuth2)
I am not good in AOuth2, so I am using ready for work specific library for ZenMoney:
https://github.com/Felixoid/python-zenmoney

Here you can see the "simplest way to start":

```<code>oauth = OAuth2('ge9e572374ec89f3a1562e4*******', '2d14e80****', '***tin@nes.ru', 'x3bTm***')
api = Request(oauth.token)
diff = api.diff(Diff(**{'serverTimestamp': 1}))
</code>```

(I have hidden my credentials above)

After that, according to description in library, I can use "diff" to get data from API (https://github.com/zenmoney/ZenPlugins/wiki/ZenMoney-API#principles)

But all that I got is:

```<code>diff

> <diff.Diff at 0x171fcfd92e0>
</code>```

Calling attributes show me the same:

```<code>diff.transaction

> [<transaction.Transaction at 0x171fd0fe670>,
 <transaction.Transaction at 0x171fd0fe6a0>,
 <transaction.Transaction at 0x171fd0fe6d0>,
 <transaction.Transaction at 0x171fd0fe700>,
 <transaction.Transaction at 0x171fd0fe730>,
 <transaction.Transaction at 0x171fd0fe760>,
 <transaction.Transaction at 0x171fd0fe790>,
 <transaction.Transaction at 0x171fd0fe7c0>,
 <transaction.Transaction at 0x171fd0fe7f0>,
 <transaction.Transaction at 0x171fd0fe820>,
 <transaction.Transaction at 0x171fd0fe850>,
 <transaction.Transaction at 0x171fd0fe880>,
 <transaction.Transaction at 0x171fd0fe8b0>,
 <transaction.Transaction at 0x171fd0fe8e0>,
...
</code>```

After diving in the code behind the library, I still dont know how to get data in json format or something like this

As I said above, I have never deal with AOuth2, but I was working with REST API, so may be this question can be obvious and I am doing something fundamentally wrong

答:
You can use this construction for example (get yestarday's transaction):</p>
```<code>import sys
from unidecode import unidecode
from datetime import date, timedelta
from zenmoney import *

yesterday=date.today()- timedelta(days=1)
yesterday=yesterday.strftime('%Y-%m-%d')

oauth = OAuth2('xxx', 'xxx', 'xxx', 'xxx')
api = Request(oauth.token)
#diff = api.diff(Diff(**{'serverTimestamp': 0}))
diff = api.diff(Diff(**{'serverTimestamp': 1}))

zen_transaction = ZenObject.to_dict(diff.transaction)
zen_transaction = sorted(zen_transaction, key=lambda k: k['date'])
for item in zen_transaction:
    if item['date']==yesterday:
        print(item)
</code>```

Body:
I am not good in AOuth2, so I am using ready for work specific library for ZenMoney:
https://github.com/Felixoid/python-zenmoney

Here you can see the "simplest way to start":

oauth = OAuth2('ge9e572374ec89f3a1562e4*******', '2d14e80****', '***tin@nes.ru', 'x3bTm***')
api = Request(oauth.token)
diff = api.diff(Diff(**{'serverTimestamp': 1}))

(I have hidden my credentials above)

After that, according to description in library, I can use "diff" to get data from API (https://github.com/zenmoney/ZenPlugins/wiki/ZenMoney-API#principles)

But all that I got is:

diff

> <diff.Diff at 0x171fcfd92e0>

Calling attributes show me the same:

diff.transaction

> [<transaction.Transaction at 0x171fd0fe670>,
 <transaction.Transaction at 0x171fd0fe6a0>,
 <transaction.Transaction at 0x171fd0fe6d0>,
 <transaction.Transaction at 0x171fd0fe700>,
 <transaction.Transaction at 0x171fd0fe730>,
 <transaction.Transaction at 0x171fd0fe760>,
 <transaction.Transaction at 0x171fd0fe790>,
 <transaction.Transaction at 0x171fd0fe7c0>,
 <transaction.Transaction at 0x171fd0fe7f0>,
 <transaction.Transaction at 0x171fd0fe820>,
 <transaction.Transaction at 0x171fd0fe850>,
 <transaction.Transaction at 0x171fd0fe880>,
 <transaction.Transaction at 0x171fd0fe8b0>,
 <transaction.Transaction at 0x171fd0fe8e0>,
...

After diving in the code behind the library, I still dont know how to get data in json format or something like this

As I said above, I have never deal with AOuth2, but I was working with REST API, so may be this question can be obvious and I am doing something fundamentally wrong

Body:
You can use this construction for example (get yestarday's transaction):

import sys
from unidecode import unidecode
from datetime import date, timedelta
from zenmoney import *

yesterday=date.today()- timedelta(days=1)
yesterday=yesterday.strftime('%Y-%m-%d')

oauth = OAuth2('xxx', 'xxx', 'xxx', 'xxx')
api = Request(oauth.token)
#diff = api.diff(Diff(**{'serverTimestamp': 0}))
diff = api.diff(Diff(**{'serverTimestamp': 1}))

zen_transaction = ZenObject.to_dict(diff.transaction)
zen_transaction = sorted(zen_transaction, key=lambda k: k['date'])
for item in zen_transaction:
    if item['date']==yesterday:
        print(item)


问:
How to grab the last non empty row?

So here's the scenario. In this case i will start at row 2 as starting point. in Column B, i want to record row of the last non empty A column. For example : the first data in B column is 2 which is the very first row then in the next row it will keep that '2' as long as the A column is empty until i reach a value (1) in the A column. When it reach the next non empty row in A column (row 7), then value in B now will keep that value (7) and it will keep that value all the way down until it reach the next non empty row in A , which is row 15. etc. Hope i can explain it clearly.

for now i only use basic formula in B2 cell :

```<code>=if( A2<>1,  min( row(A2), indirect( "b" & (row(A2) -1)  ) ) ,  row( A2) )
</code>```

and then copy it down to other cells in B column. It works. But i'm just want to convert this into arrayformula() and got no luck. Does anyone know how to make this works using arrayformula ?

Title: How to grab the last non empty row?

Body:
So here's the scenario. In this case i will start at row 2 as starting point. in Column B, i want to record row of the last non empty A column. For example : the first data in B column is 2 which is the very first row then in the next row it will keep that '2' as long as the A column is empty until i reach a value (1) in the A column. When it reach the next non empty row in A column (row 7), then value in B now will keep that value (7) and it will keep that value all the way down until it reach the next non empty row in A , which is row 15. etc. Hope i can explain it clearly.

for now i only use basic formula in B2 cell :

=if( A2<>1,  min( row(A2), indirect( "b" & (row(A2) -1)  ) ) ,  row( A2) )

and then copy it down to other cells in B column. It works. But i'm just want to convert this into arrayformula() and got no luck. Does anyone know how to make this works using arrayformula ?

Body:
use:

=INDEX(VLOOKUP(ROW(A2:A), {2; FILTER(ROW(A3:A), A3:A<>"")}, 1, 1))


问:
TypeError when adding multiple widgets to layout using SimpleGui
(answered]
I'm learning SimpleGui and when adding multiple widgets to the layout the system gives me a TypeError. Here is my code for the layout

```<code>layout = [
[sg.Text("I have no idea what i am doing")]

[sg.Text("i wanna make games and stuff")]
]
</code>```

I'm using version 3.10.0 of python if that helps

答:
You're missing a comma between your two lists:

```<code>layout = [
    [sg.Text("I have no idea what i am doing")],
    [sg.Text("i wanna make games and stuff")]
]
</code>```

The error you get (TypeError: list indices must be integers or slices, not Text) is because the python interpreter thinks you're trying to index into the first list with your second list.

Body:
(answered]
I'm learning SimpleGui and when adding multiple widgets to the layout the system gives me a TypeError. Here is my code for the layout

layout = [
[sg.Text("I have no idea what i am doing")]

[sg.Text("i wanna make games and stuff")]
]

I'm using version 3.10.0 of python if that helps

Body:
You're missing a comma between your two lists:

layout = [
    [sg.Text("I have no idea what i am doing")],
    [sg.Text("i wanna make games and stuff")]
]

The error you get (TypeError: list indices must be integers or slices, not Text) is because the python interpreter thinks you're trying to index into the first list with your second list.


问:
how to get characters with accent from NSEvent
When I press ^ or ` and then a or e I get only a or e instead of â or é.

This is my code:

```<code>- (void) keyDown:(NSEvent*)event
{
  NSString* str = [event characters];
}
</code>```

How do I solve this?

答: keyDown: only gives the characters for the key you currently are pressing down.  Characters that take more than one keystroke show up as a separate keyDown: call for each keystroke.  If you want to see typed characters instead of individual keypresses, override -insertText: instead.</p>

ContentLicense: CC BY-SA 3.0

Body:
When I press ^ or ` and then a or e I get only a or e instead of â or é.

This is my code:

- (void) keyDown:(NSEvent*)event
{
  NSString* str = [event characters];
}

How do I solve this?


问:
How to deal with recurring events using the google calendar API?
I'm using the Google Calendar API and nodejs. I have an app that allows patients to book appointments with doctors. But first, I check the doctor's calendar to make sure they do not have appointments at this time. How can I tell if an event is recurring? Does it show up multiple times when I make a list API call or only once?</p>

答:
When you have a recurrent event the ID changes a lot. For example, a regular event ID would look like 3qoortuglk75k7fjhgmd9k2enn, but the event ID from a recurrent event would be like 3qoortuglk75k7fjhgmd9k2enn_20220217T160000Z. If you see it has additional information related to the date and time. You could try to use something like that to recognize if the event is recurrent or not.

When listing events with the API you also have the request parameter singleEvents. You could use it to list only single events and compare them to the full list of events to see which ones are recurrent events.


问:
issues with external memory devices in linux
Hello Running ubuntu mate when I try to drag and drop a file into an external media
such as an external drive or a usb stick I get the error message the destination directory is read only.Any Ideas?</p>

答:
This happens when we are working with memory cards with adapter that has read/write switch on them. You haven't said which type of storage you are using. With SSD and other device this problems mostly never occurs. It happens with Switched pendrive/cards which has read/write switch. Or you can check with lsusb for further detection.
Sometimes some application snippets require special permissions for drives too. It would be great if you add some logs.


问:
Illustrator script (or action) to make 1 random layer visible per group
Similar to this question but with adobe Illustrator: Photoshop action to make 1 random layer visible within each group

I want to use an illustrator script (or action) to generate images that are composed of a random sampling of grouped layers.

With in each of the 12 groups, I want to make 1 layer per group visible.

Export the visible layers as an svg. Bonus points if I can change the file format.

Repeat the process n times

I know this is similar to the code linked above though I want to be able to use illustrator instead of photoshop if possible.

答:
It could be something like this:

function main() {
    var doc = app.activeDocument;

    // hide all items
    var i = doc.pageItems.length;
    while(i--) doc.pageItems[i].hidden = true;

    // show one random item on every layer
    var i = doc.layers.length;
    while(i--) {
        var items = doc.layers[i].pageItems;
        var index = Math.round(Math.random()*(items.length-1));
        items[index].hidden = false;
    }

    // save svg
    var counter = 0;
    var file = File(Folder.desktop + '/' + counter + '.svg') ;
    while (file.exists) {
        file = File(Folder.desktop + '/' + counter++ + '.svg');
    }
    doc.exportFile(file, ExportType.SVG);

    // save png
    var counter = 0;
    var file = File(Folder.desktop + '/' + counter + '.png') ;
    while (file.exists) {
        file = File(Folder.desktop + '/' + counter++ + '.png');
    }
    var options = new ExportOptionsPNG24();
    options.artBoardClipping = true;
    doc.exportFile(file, ExportType.PNG24, options);
}

// repeat the script N times
var n = 3;
while(n--) main();
```

It hides all the page items, shows one random item on every layer, and saves the document as SVG and PNG in the desktop folder.

Body:
It could be something like this:

function main() {
    var doc = app.activeDocument;

    // hide all items
    var i = doc.pageItems.length;
    while(i--) doc.pageItems[i].hidden = true;

    // show one random item on every layer
    var i = doc.layers.length;
    while(i--) {
        var items = doc.layers[i].pageItems;
        var index = Math.round(Math.random()*(items.length-1));
        items[index].hidden = false;
    }

    // save svg
    var counter = 0;
    var file = File(Folder.desktop + '/' + counter + '.svg') ;
    while (file.exists) {
        file = File(Folder.desktop + '/' + counter++ + '.svg');
    }
    doc.exportFile(file, ExportType.SVG);

    // save png
    var counter = 0;
    var file = File(Folder.desktop + '/' + counter + '.png') ;
    while (file.exists) {
        file = File(Folder.desktop + '/' + counter++ + '.png');
    }
    var options = new ExportOptionsPNG24();
    options.artBoardClipping = true;
    doc.exportFile(file, ExportType.PNG24, options);
}

// repeat the script N times
var n = 3;
while(n--) main();

It hides all the page items, shows one random item on every layer, and saves the document as SVG and PNG in the desktop folder.


问:
Does google pub/sub have concept of partition like kafka?
What is the partition strategy if n subscriber is sharing 1 subscriptions for a topic in google pub/sub?

Is it round robin? Or does each subscriber guarantee to have a set of key if there is no rebalancing?

答:
You can create several subscriptions on a same topic with a filter on the message attributes to only select a subset of messages.

You can't set partition based on the subscribers of a same subscription.


答:
Every time you call getComputerChoice you'll get a different value, you could save the values in a variable with the const keyword.

const playGame = () => {
  // It would be nice if you request this to the user, with prompt
  const userChoice = getUserChoice('scissors');

  // Save the random value
  const computerChoice = getComputerChoice();

  console.log(`player chose ${userChoice}`);
  console.log(`computer chose ${computerChoice}`);

  // This will work
  console.log(determineWinner(userChoice, computerChoice));
}

playGame();
```

More on prompt here

Title: im a new learner and cant figure out why my code is not working

Body:
I have just recently got into coding and have chosen to learn JavaScript as my first language. I have written up code for a Rock, Paper, Scissors game but the wrong outputs come out when I run it? for example I would put my answer as scissors and the computer would choose rock and the game will come out as a tie.

const getUserChoice = userInput => {
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return userInput
  } else {
    return 'Error!'
  }
}

var getComputerChoice = () => {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock'
      break;
    case 1:
      return 'paper'
      break;
    case 2:
      return 'scissors'
      break;
  }
};

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return 'its a tie!';
  };
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'computer won';
    } else {
      return 'user won';
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'scissors') {
      return 'computer won';
    } else {
      return 'user won'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'computer won';
    } else {
      return 'user won'
    }
  }
};

const playGame = () => {
  console.log(`player chose ${getUserChoice('scissors')}`);
  console.log(`computer chose ${getComputerChoice()}`);
  console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
}
playGame();

Body:
Every time you call getComputerChoice you'll get a different value, you could save the values in a variable with the const keyword.

const playGame = () => {
  // It would be nice if you request this to the user, with prompt
  const userChoice = getUserChoice('scissors');

  // Save the random value
  const computerChoice = getComputerChoice();

  console.log(`player chose ${userChoice}`);
  console.log(`computer chose ${computerChoice}`);

  // This will work
  console.log(determineWinner(userChoice, computerChoice));
}

playGame();

More on prompt here


问:
Django 'http://localhost:8000' has been blocked by CORS policy
I have an error on the server  (local host is OK)

from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried the following (followed this page How can I enable CORS on Django REST Framework)

```<code>pip install django-cors-headers

# Added at the top of MIDDLEWARE
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',

# Added after allowed hosts
CORS_ORIGIN_ALLOW_ALL=True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
</code>```

After the changes below I have

You can see the error in browser developer's mode VM87:5553 crbug/1173575, non-JS module files deprecated.

How can I fix the error?

答:
My solution:

```<code>sudo vim /etc/nginx/sites-available/default
sudo service nginx restart
</code>```

Changed file

```<code>server{
    server_name www.api.site.ru api.site.ru;

    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,X-token' always;
    if ($request_method = 'OPTIONS') {
        return 204;
    }

    location / {
         proxy_pass http://127.0.0.1:8000;
         proxy_set_header Host $host;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-Proto $scheme;
         proxy_set_header X-Forwarded-Proto https;
         proxy_set_header X-Forwarded-Protocol  $scheme;

         proxy_headers_hash_max_size 512;
         proxy_headers_hash_bucket_size 128;
    }

    access_log /var/log/nginx/ar_access.log;
    error_log /var/log/nginx/ar_error.log;

    listen 80; # managed by Certbot

}
</code>```

Body:
I have an error on the server  (local host is OK)

from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried the following (followed this page How can I enable CORS on Django REST Framework)

pip install django-cors-headers

# Added at the top of MIDDLEWARE
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',

# Added after allowed hosts
CORS_ORIGIN_ALLOW_ALL=True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True

After the changes below I have

You can see the error in browser developer's mode VM87:5553 crbug/1173575, non-JS module files deprecated.

How can I fix the error?

Body:
My solution:

sudo vim /etc/nginx/sites-available/default
sudo service nginx restart

Changed file

server{
    server_name www.api.site.ru api.site.ru;

    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,X-token' always;
    if ($request_method = 'OPTIONS') {
        return 204;
    }

    location / {
         proxy_pass http://127.0.0.1:8000;
         proxy_set_header Host $host;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-Proto $scheme;
         proxy_set_header X-Forwarded-Proto https;
         proxy_set_header X-Forwarded-Protocol  $scheme;

         proxy_headers_hash_max_size 512;
         proxy_headers_hash_bucket_size 128;
    }

    access_log /var/log/nginx/ar_access.log;
    error_log /var/log/nginx/ar_error.log;

    listen 80; # managed by Certbot

}


问:
How important is it to check for malloc failures?
Is always protecting mallocs important? By protecting I mean:

```<code>char *test_malloc = malloc(sizeof(char) * 10000);

if (!test_malloc)
  exit(EXIT_FAILURE);
</code>```

I mean, in electronic devices, I don't doubt it's essential.
But in programs I'm running on my own machine that I'm sure my allocation size will be positive and that the size will not be astronomical.
Some people say, "Ah imagine there’s not enough memory in your computer at this moment."

答:
It is important to check for error conditions? Absolutely!

Now when it comes to malloc you might find, that some implementations of the C standard library – the glibc for example – will never return NULL and instead abort, due to the assumption that if allocating memory fails, a program won't be able to recover from that. IMHO that assumption is ill founded. But it places malloc in that weird groups of function where, even if you properly implement out-of-memory condition handling that works without requesting any more memory, your program is still being crashed.

That being said: You should definitely check for error conditions, for the sole reason you might run your program in an environment that gives you a chance to properly react to them.

Body:
Is always protecting mallocs important? By protecting I mean:

char *test_malloc = malloc(sizeof(char) * 10000);

if (!test_malloc)
  exit(EXIT_FAILURE);

I mean, in electronic devices, I don't doubt it's essential.
But in programs I'm running on my own machine that I'm sure my allocation size will be positive and that the size will not be astronomical.
Some people say, "Ah imagine there’s not enough memory in your computer at this moment."


问:
Using Powershell v1 to Remove Script from webpages
My website has been hacked, with the effect being the addition of a script (vbScript, I think) just before the /body tag on certain pages. I can select all of the pages which are targeted using

```<code>$files=get-childitem . -recurse -include $a |  where {$_.LastWriteTime -gt
[datetime]::parse("08/14/2011")}
</code>```

where $a is an array of file specs. I would like to run each of these files through a get-content|-replace|set-content pipeline, but I can't get the -replace arguments right. Basically, I want to replace everything between the  and  tags, including the tags, with blank space or an HTML comment. I'm pretty sure this can be solved with regex, but I just can't get it right - something like:

```<code>foreach ($f in $files)
{(get-content $f)|foreach-object {$_ -replace "<script>\w+</script>","<!--Script Replaced-->"}|set-content $f}
</code>```

Thanks in advance,

Eric F

答:
Disclaimer: Regex is not HTML parser. You will run into corner cases.

The script tags are probably multiline, so you want to:

1) Get all the lines of the file ( get-content and piping it like you have done will only process line-by-line )

2) Use a regex that can replace / process over multiple line ( the regex you have used will only look within a single line)

So you can try something like below for getting the content and replacing the tags:

```<code>$content = [System.IO.File]::ReadAllText($f)
$content -replace "(?s)<script>.+?</script>","" | out-file $f
</code>```

Body:
My website has been hacked, with the effect being the addition of a script (vbScript, I think) just before the /body tag on certain pages. I can select all of the pages which are targeted using

$files=get-childitem . -recurse -include $a |  where {$_.LastWriteTime -gt
[datetime]::parse("08/14/2011")}

where $a is an array of file specs. I would like to run each of these files through a get-content|-replace|set-content pipeline, but I can't get the -replace arguments right. Basically, I want to replace everything between the  and  tags, including the tags, with blank space or an HTML comment. I'm pretty sure this can be solved with regex, but I just can't get it right - something like:

foreach ($f in $files)
{(get-content $f)|foreach-object {$_ -replace "",""}|set-content $f}

Thanks in advance,

Eric F

Body:
Disclaimer: Regex is not HTML parser. You will run into corner cases.

The script tags are probably multiline, so you want to:

1) Get all the lines of the file ( get-content and piping it like you have done will only process line-by-line )

2) Use a regex that can replace / process over multiple line ( the regex you have used will only look within a single line)

So you can try something like below for getting the content and replacing the tags:

$content = [System.IO.File]::ReadAllText($f)
$content -replace "(?s)<script>.+?</script>","" | out-file $f


问:
How to combine 3 TIFF images into 1 PNG image with python?
I have 1 tif image for each RGB colour channel, and I would like to combine the 3 images to make a single RGB image with all 3 channels in png format using python. I have tried several experiments using the PIL library but I can't get it.

I uploaded 3 sample images to Google Drive here. Does anyone know how to do this?

答:
The answer depends on what you are really trying to achieve...

If you want an accurate merge of the 3 channels, you should probably use the tifffile module to understand the floating point values in your input files and accurately represent them in your output files. In fact, gdal would probably be even better as it understands the GeoTIFF tags in your file. PIL is unable to handle RGB float32 images.

If you want something that vaguely allows some sort of approximate visualisation as a PNG, you will need to do some work to scale your values to something sensible (but not accurate) because PNG cannot represent float data like your images contain.

Here is a more accurate merge of your channels with tifffile:

```<code>from tifffile import imread, imwrite
import numpy as np

r = imread('r.tif')
g = imread('g.tif')
b = imread('b.tif')
RGB = np.dstack((r,g,b))
imwrite('result.tif', RGB)
</code>```

With PIL you would use Image.merge() but your data is float, so you will need to convert it to uint8/uint16 first to get something you can store in a PNG:

```<code>from PIL import Image
import numpy as np

# Open images
red   = Image.open('red_channel.tif')
green = Image.open('green_channel.tif')
blue  = Image.open('blue_channel.tif')

# Convert PIL Images to Numpy arrays
npRed   = np.array(red)
npGreen = np.array(green)
npBlue  = np.array(blue)

# Get rid of the pesky -3.4e+38 marker for out-of-bounds pixels
npRed[npRed < 0]     = 0
npBlue[npBlue < 0]   = 0
npGreen[npGreen < 0] = 0

# Find maximum across all channels for scaling
max = np.max([npRed,npGreen,npBlue])

# Scale all channels equally to range 0..255 to fit in a PNG (could use 65,535 and np.uint16 instead)
R = (npRed * 255/max).astype(np.uint8)
G = (npGreen * 255/max).astype(np.uint8)
B = (npBlue * 255/max).astype(np.uint8)

# Build a PNG
RGB = np.dstack((R,G,B))
Image.fromarray(RGB).save('result.png')
</code>```

Body:
The answer depends on what you are really trying to achieve...

If you want an accurate merge of the 3 channels, you should probably use the tifffile module to understand the floating point values in your input files and accurately represent them in your output files. In fact, gdal would probably be even better as it understands the GeoTIFF tags in your file. PIL is unable to handle RGB float32 images.

If you want something that vaguely allows some sort of approximate visualisation as a PNG, you will need to do some work to scale your values to something sensible (but not accurate) because PNG cannot represent float data like your images contain.

Here is a more accurate merge of your channels with tifffile:

from tifffile import imread, imwrite
import numpy as np

r = imread('r.tif')
g = imread('g.tif')
b = imread('b.tif')
RGB = np.dstack((r,g,b))
imwrite('result.tif', RGB)

With PIL you would use Image.merge() but your data is float, so you will need to convert it to uint8/uint16 first to get something you can store in a PNG:

from PIL import Image
import numpy as np

# Open images
red   = Image.open('red_channel.tif')
green = Image.open('green_channel.tif')
blue  = Image.open('blue_channel.tif')

# Convert PIL Images to Numpy arrays
npRed   = np.array(red)
npGreen = np.array(green)
npBlue  = np.array(blue)

# Get rid of the pesky -3.4e+38 marker for out-of-bounds pixels
npRed[npRed < 0]     = 0
npBlue[npBlue < 0]   = 0
npGreen[npGreen < 0] = 0

# Find maximum across all channels for scaling
max = np.max([npRed,npGreen,npBlue])

# Scale all channels equally to range 0..255 to fit in a PNG (could use 65,535 and np.uint16 instead)
R = (npRed * 255/max).astype(np.uint8)
G = (npGreen * 255/max).astype(np.uint8)
B = (npBlue * 255/max).astype(np.uint8)

# Build a PNG
RGB = np.dstack((R,G,B))
Image.fromarray(RGB).save('result.png')


问:
JSON-LD framing specify ordering of rdfs
```<code>@prefix emp: <http://example.com/employee/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

emp:hasName rdf:type rdfs:Property .

emp:dateOfBirth  rdf:type rdfs:Property ;
    rdf:after emp:passportNumber .

emp:passportNumber rdf:type rdfs:Property .
</code>```

Given the above Turtle RDF model, I want to generate the following JSON-LD:

```<code>"@graph": [
    {
        "@id": "emp:hasName",
        "@type": "rdfs:Property"
    },
    {
        "@id": "emp:passportNumber",
        "@type": "rdfs:Property"
    },
    {
        "@id": "emp:dateOfBirth",
        "@type": "rdfs:Property",
    }
]
</code>```

Notice that emp:dateOfBirth is ordered after emp:passportNumber in the list as I specified rdf:after "emp:passportNumber" in the model.

How could I accomplish this via JSON-LD Framing?

Is it safe to rely on the order in which these rdfs are declared in, as most RDF->JSON-LD libs seem to preserve the ordering (despite the specs defining them as unordered)?

I do not want to explicitly define an exhaustive ordered list in the RDF model as the list would be huge and only a few RDFs need to be ordered (eg. I do not care where emp:hasName is).

答: The JSON-LD algorithms will optionally sort keys in an object, not not sort objects themselves. One way you might be able to do this is using an id map, so that the subject IRIs of the different RDFS terms were then used as the keys of this map. For that, they would all need to be a value of some other entity. One trick for doing this is to use rdfs:isDefinedBy as a reverse property, so that the ontology itself appears as the top-level object with reverse relationships to the terms it defines. Combining a reverse property with an id map would make the object value have subject IRIs as keys, which could then be ordered.

Body:
@prefix emp: <http://example.com/employee/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

emp:hasName rdf:type rdfs:Property .

emp:dateOfBirth  rdf:type rdfs:Property ;
    rdf:after emp:passportNumber .

emp:passportNumber rdf:type rdfs:Property .

Given the above Turtle RDF model, I want to generate the following JSON-LD:

"@graph": [
    {
        "@id": "emp:hasName",
        "@type": "rdfs:Property"
    },
    {
        "@id": "emp:passportNumber",
        "@type": "rdfs:Property"
    },
    {
        "@id": "emp:dateOfBirth",
        "@type": "rdfs:Property",
    }
]

Notice that emp:dateOfBirth is ordered after emp:passportNumber in the list as I specified rdf:after "emp:passportNumber" in the model.

How could I accomplish this via JSON-LD Framing?

Is it safe to rely on the order in which these rdfs are declared in, as most RDF->JSON-LD libs seem to preserve the ordering (despite the specs defining them as unordered)?

I do not want to explicitly define an exhaustive ordered list in the RDF model as the list would be huge and only a few RDFs need to be ordered (eg. I do not care where emp:hasName is).


问:
recaptcha in a non-productive environment (is it worth it?)
I wonder what is the most appropriate way to automate the following captcha in a non-productive environment (if necessary). Take a look:

a)Making use of a boot that allows you to obtain a user token from our
session to be able to enter it through automation

b)Using the click() method on the appropriate elements

c)Using: document.getElementById("recaptchamsg").required = false;

d) None, recaptcha must be disabled for the test to skip this step

Is it necessary at all? And in a production environment? What would it be the right thing to do?

答:
Well, if possible, recaptcha must definitively be disabled for the test to skip this step.

If it is not possible you will have to pass it with Selenium. How to do that depends on the type or recaptcha you have on your application, not every kind of it can be passed with Selenium.


问:
deleted automatically telegram bot
I created a telegram robot that forwards video files by selecting Start. And I want them to be deleted automatically after 1 hour. Can anyone help me?

```<code>context.bot.sendDocument(chat_id=update.message.chat_id, document='https://t.me/mychanel/2',caption="1")
context.bot.sendDocument(chat_id=update.message.chat_id, document='https://t.me/mychanel/3',caption="2")
context.bot.sendDocument(chat_id=update.message.chat_id, document='https://t.me/mycha
</code>```

nel/4',caption="3")

how can I delete auto those?

答:
You can do
message =context.bot.sendDocument(chat_id=update.message.chat_id, document='https://t.me/mychanel/2',caption="1")

And save the message.message_id with a timestamp in a data structure, list or dict, after that you can schedule a periodic thread that do
bot.delte_message(message_id,chat_id) on the expired videos

Title: deleted automatically telegram bot

Body:
I created a telegram robot that forwards video files by selecting Start. And I want them to be deleted automatically after 1 hour. Can anyone help me?

context.bot.sendDocument(chat_id=update.message.chat_id, document='https://t.me/mychanel/2',caption="1")
context.bot.sendDocument(chat_id=update.message.chat_id, document='https://t.me/mychanel/3',caption="2")
context.bot.sendDocument(chat_id=update.message.chat_id, document='https://t.me/mycha

nel/4',caption="3")

how can I delete auto those?


问:
Is the MySQL procedure in this Minecraft plugin correct?
To get an idea of what the basic structure looks like, I downloaded a money system including MySQL from Spigot and looked at the code.

```<code>public static boolean playerExists(String uuid) {
    try {
      ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
      if (rs.next())
        return (rs.getString("UUID") != null);
      return false;
    } catch (SQLException e) {
      e.printStackTrace();
      return false;
    }
}

public static void createPlayer(String uuid) {
    if (!playerExists(uuid))
      Simplecoinsystem.mysql.update("INSERT INTO CoinData (UUID, COINS) VALUES ('" + uuid +
          "', '" + Simplecoinsystem.getInstance().getConfig().getInt("startcoins") + "');");
}

public static Integer getCoins(String uuid) {
    Integer i = Integer.valueOf(0);
    if (playerExists(uuid)) {
      try {
        ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
        if (rs.next())
          Integer.valueOf(rs.getInt("COINS"));
        i = Integer.valueOf(rs.getInt("COINS"));
      } catch (SQLException e) {
        e.printStackTrace();
      }
    } else {
      createPlayer(uuid);
    }
    return i;
}

public static void setCoins(String uuid, Integer coins) {
    if (playerExists(uuid)) {
      Simplecoinsystem.mysql.update("UPDATE CoinData SET COINS= '" + coins + "' WHERE UUID= '" + uuid + "';");
    } else {
      createPlayer(uuid);
    }
}
</code>```

Am I correct that it is actually impractical to create a new entry with the uuid of the non-existent player after each query of the coins if the player does not exist?

Wouldn't this make it possible to flood the database with thousands of unnecessary entries by issuing, for example, a "/money (player)" command as an evil player/admin?

Couldn't I just ask when entering the server if the uuid is already stored and if not, just enter it? This way there would only be entries from players who have already been on the server before. Whether this needs great server performance, I'm not sure.

This is my first own MySQL class.

```<code>public class MySQL {

    private String host, database, user, password;
    private int port;

    private Connection con;

    public MySQL(String host, int port, String database, String user, String password) {
        this.host = host;
        this.port = port;
        this.database = database;
        this.user = user;
        this.password = password;

        connect();
    }

    public void connect() {
        try {
            con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", user, password);
            System.out.println("&cDie MySQL Verbindung wurde erfolgreich aufgebaut!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        try {
            if(this.con != null) {
                this.con.close();
                System.out.println("§cDie MySQL Verbindung wurde erfolgreich beendet!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(String query) {
        try {
            Statement st = con.createStatement();
            st.executeUpdate(query);
            st.close();
        } catch (Exception e) {
            e.printStackTrace();
            connect();
        }
    }

    public ResultSet qry(String query) {
        ResultSet rs = null;

        try {
            Statement st = con.createStatement();
            rs = st.executeQuery(query);
        } catch (Exception e) {
            e.printStackTrace();
            connect();
        }
        return rs;
    }

    public Connection getConnection() {
        return this.con;
    }

}
</code>```

Except for this part, both MySQL classes are built relatively the same.
This is the part that is in the MySQL class of the Spigot plugin.

答:
What do you say? Is it ok with the try/catch function? @Elikill58

```<code>public Connection getConnection() {
    try {
        if(con == null || con.isClosed()) {
            connect();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return con;
}
</code>```

edit:

```<code>public Connection getConnection_one() throws SQLException {
    if(con == null || con.isClosed()) {
        connect();
        return con;
    } else {
        return con;
    }
}
</code>```

Body:
To get an idea of what the basic structure looks like, I downloaded a money system including MySQL from Spigot and looked at the code.

public static boolean playerExists(String uuid) {
    try {
      ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
      if (rs.next())
        return (rs.getString("UUID") != null);
      return false;
    } catch (SQLException e) {
      e.printStackTrace();
      return false;
    }
}

public static void createPlayer(String uuid) {
    if (!playerExists(uuid))
      Simplecoinsystem.mysql.update("INSERT INTO CoinData (UUID, COINS) VALUES ('" + uuid +
          "', '" + Simplecoinsystem.getInstance().getConfig().getInt("startcoins") + "');");
}

public static Integer getCoins(String uuid) {
    Integer i = Integer.valueOf(0);
    if (playerExists(uuid)) {
      try {
        ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
        if (rs.next())
          Integer.valueOf(rs.getInt("COINS"));
        i = Integer.valueOf(rs.getInt("COINS"));
      } catch (SQLException e) {
        e.printStackTrace();
      }
    } else {
      createPlayer(uuid);
    }
    return i;
}

public static void setCoins(String uuid, Integer coins) {
    if (playerExists(uuid)) {
      Simplecoinsystem.mysql.update("UPDATE CoinData SET COINS= '" + coins + "' WHERE UUID= '" + uuid + "';");
    } else {
      createPlayer(uuid);
    }
}

Am I correct that it is actually impractical to create a new entry with the uuid of the non-existent player after each query of the coins if the player does not exist?

Wouldn't this make it possible to flood the database with thousands of unnecessary entries by issuing, for example, a "/money (player)" command as an evil player/admin?

Couldn't I just ask when entering the server if the uuid is already stored and if not, just enter it? This way there would only be entries from players who have already been on the server before. Whether this needs great server performance, I'm not sure.

This is my first own MySQL class.

public class MySQL {

    private String host, database, user, password;
    private int port;

    private Connection con;

    public MySQL(String host, int port, String database, String user, String password) {
        this.host = host;
        this.port = port;
        this.database = database;
        this.user = user;
        this.password = password;

        connect();
    }

    public void connect() {
        try {
            con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", user, password);
            System.out.println("&cDie MySQL Verbindung wurde erfolgreich aufgebaut!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        try {
            if(this.con != null) {
                this.con.close();
                System.out.println("§cDie MySQL Verbindung wurde erfolgreich beendet!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(String query) {
        try {
            Statement st = con.createStatement();
            st.executeUpdate(query);
            st.close();
        } catch (Exception e) {
            e.printStackTrace();
            connect();
        }
    }

    public ResultSet qry(String query) {
        ResultSet rs = null;

        try {
            Statement st = con.createStatement();
            rs = st.executeQuery(query);
        } catch (Exception e) {
            e.printStackTrace();
            connect();
        }
        return rs;
    }

    public Connection getConnection() {
        return this.con;
    }

}

Except for this part, both MySQL classes are built relatively the same.
This is the part that is in the MySQL class of the Spigot plugin.

Body:
What do you say? Is it ok with the try/catch function? @Elikill58

public Connection getConnection() {
    try {
        if(con == null || con.isClosed()) {
            connect();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return con;
}

edit:

public Connection getConnection_one() throws SQLException {
    if(con == null || con.isClosed()) {
        connect();
        return con;
    } else {
        return con;
    }
}


问:
How to mask subsequences of string with a pattern string
I have a main string that looks like this:

```<code>my_main <- "ABCDEFGHIJ"
</code>```

What I want to do is to sequentially mask at every position with another pattern string:

```<code>my_pattern <- "x*x" # the length could be varied from 1 up to length of my_main
</code>```

Every character that overlap with * will be kept, other will be replaced with x.

The final result is a vector of strings that contain these:

```<code>xBxDEFGHIJ
AxCxEFGHIJ
ABxDxFGHIJ
ABCxExGHIJ
ABCDxFxHIJ
ABCDExGxIJ
ABCDEFxHxJ
ABCDEFGxIx
</code>```

Next if the pattern is

```<code>my_pattern <- "xx**x"
</code>```

The result would be:

```<code>xxCDxFGHIJ
AxxDExGHIJ
ABxxEFxHIJ
ABCxxFGxIJ
ABCDxxGHxJ
ABCDExxHIx
</code>```

How can I achieve that?

答:
Here is Ruby code that produces the desired result. I am presenting it in the event that a reader wishes to convert it to R, possibly with modification, of course.

You should be able to read the code even if you don't know Ruby, as long as you understand that:

'abc'.size returns 3;

0..8 is a range of integers between 0 and 8, inclusive;

'abc' << 'd' returns 'abcd';

7.modulo(3) returns 1;

'abcd'[2] returns 'c', 2 being an index; and

s == 'x' ? 'x' : my_main[j] reads, "if the string s (which will be 'x' or '*') equals 'x'  return 'x', else return the character of my_main at index j.

The Ruby code (somewhat simplified from what would normally be written) is as follows.

```<code>def doit(my_main, my_pattern)
  msz = my_main.size
  psz = my_pattern.size
  (0..msz-psz).map do |i|
    s = ''
    (0..msz-1).each do |j|
      s << (my_pattern[(j-i).modulo(msz)] == 'x' ? 'x' : my_main[j])
    end
    s
  end
end
</code>```

Body:
I have a main string that looks like this:

my_main <- "ABCDEFGHIJ"

What I want to do is to sequentially mask at every position with another pattern string:

my_pattern <- "x*x" # the length could be varied from 1 up to length of my_main

Every character that overlap with * will be kept, other will be replaced with x.

The final result is a vector of strings that contain these:

xBxDEFGHIJ
AxCxEFGHIJ
ABxDxFGHIJ
ABCxExGHIJ
ABCDxFxHIJ
ABCDExGxIJ
ABCDEFxHxJ
ABCDEFGxIx

Next if the pattern is

my_pattern <- "xx**x"

The result would be:

xxCDxFGHIJ
AxxDExGHIJ
ABxxEFxHIJ
ABCxxFGxIJ
ABCDxxGHxJ
ABCDExxHIx

How can I achieve that?

Body:
Here is Ruby code that produces the desired result. I am presenting it in the event that a reader wishes to convert it to R, possibly with modification, of course.

You should be able to read the code even if you don't know Ruby, as long as you understand that:

'abc'.size returns 3;

0..8 is a range of integers between 0 and 8, inclusive;

'abc' << 'd' returns 'abcd';

7.modulo(3) returns 1;

'abcd'[2] returns 'c', 2 being an index; and

s == 'x' ? 'x' : my_main[j] reads, "if the string s (which will be 'x' or '*') equals 'x'  return 'x', else return the character of my_main at index j.

The Ruby code (somewhat simplified from what would normally be written) is as follows.

def doit(my_main, my_pattern)
  msz = my_main.size
  psz = my_pattern.size
  (0..msz-psz).map do |i|
    s = ''
    (0..msz-1).each do |j|
      s << (my_pattern[(j-i).modulo(msz)] == 'x' ? 'x' : my_main[j])
    end
    s
  end
end


问:
Best index/document structure for ElasticSearch/OpenSearch
I'm new to ElasticSearch/OpenSearch and I'm trying to figure out the best way to organize indices and document structure for my use case. I would like to render some stats from my application on a dashboard, so I plan to send some important events from my application to ElasticSearch/OpenSearch directly.

I've analyzed the application and decided that I would have the following events (documents):

{
  "type": "api.request",
  "method": "{method-name}",
  "timestamp": "{timestamp}"
}
```
<p>Based on <code>api.request</code> event I would like to know how many API requests are performed in some specific time range, e.g. RPS.</p>
<pre class="lang-json prettyprint-override"><code>{
  "type": "page.rendered",
  "name": "{page-name}",
  "duration": "{render-duration}",
  "timestamp": "{timestamp}"
}
</code>```

Based on page.rendered event I would like to know what pages are accessed by the users the most and how fast the pages are getting rendered, e.g. I would like to know if some pages are slow to render so I would be able to optimize their performance.

[
  {
    "type": "user.created",
    "userId": "{uuidv4}",
    "timestamp": "{timestamp}"
  },
  {
    "type": "user.invited",
    "userId": "{uuidv4}",
    "referrerId": "{uuidv4}",
    "timestamp": "{timestamp}"
  }
]
```
<p>Based on <code>user.created</code> and <code>user.invited</code> events I would like to know how many users are registered and invited each day, how many users are invited and how many users are registered directly without invitation.</p>
<pre class="lang-json prettyprint-override"><code>{
  "type": "user.invitation-failed",
  "userId": "{uuidv4}",
  "error": "{error-name}",
  "timestamp": "{timestamp}"
}
</code>```

Based on user.invitation-failed event I would like to know what causing invitations to fail (there are various reason for this), so I would like to see a percentage for each error name.

{
  "type": "user.photo-uploaded",
  "userId": "{uuidv4}",
  "photoId": "{uuidv4}",
  "timestamp": "{timestamp}"
}
```

Based on user.photo-uploaded event (and similar) I would like to know how many objects are getting created by users (total per day and per individual user).

How should I organize indices to store these events, so I can easily query them to extract the information that I'm interested in? Should I create a separate index for each event type? Should I group some events together? Or should I even use a single index for all of these events? Is my document structure correct or should I change it to something else?

What should be my reasoning in order to figure this out?

答:
This schema should work ok in general, and you can start with putting all events in one index. Import or create some fake data, index it and try to get the results you need with ES aggregations. As the dataset grows, you'll see the bottlenecks and resolve them.

They only caveat to take care of now would be to make sure you store all the fields that are used for aggregations as keyword.

Body:
I'm new to ElasticSearch/OpenSearch and I'm trying to figure out the best way to organize indices and document structure for my use case. I would like to render some stats from my application on a dashboard, so I plan to send some important events from my application to ElasticSearch/OpenSearch directly.

I've analyzed the application and decided that I would have the following events (documents):

{
  "type": "api.request",
  "method": "{method-name}",
  "timestamp": "{timestamp}"
}

Based on api.request event I would like to know how many API requests are performed in some specific time range, e.g. RPS.

{
  "type": "page.rendered",
  "name": "{page-name}",
  "duration": "{render-duration}",
  "timestamp": "{timestamp}"
}

Based on page.rendered event I would like to know what pages are accessed by the users the most and how fast the pages are getting rendered, e.g. I would like to know if some pages are slow to render so I would be able to optimize their performance.

[
  {
    "type": "user.created",
    "userId": "{uuidv4}",
    "timestamp": "{timestamp}"
  },
  {
    "type": "user.invited",
    "userId": "{uuidv4}",
    "referrerId": "{uuidv4}",
    "timestamp": "{timestamp}"
  }
]

Based on user.created and user.invited events I would like to know how many users are registered and invited each day, how many users are invited and how many users are registered directly without invitation.

{
  "type": "user.invitation-failed",
  "userId": "{uuidv4}",
  "error": "{error-name}",
  "timestamp": "{timestamp}"
}

Based on user.invitation-failed event I would like to know what causing invitations to fail (there are various reason for this), so I would like to see a percentage for each error name.

{
  "type": "user.photo-uploaded",
  "userId": "{uuidv4}",
  "photoId": "{uuidv4}",
  "timestamp": "{timestamp}"
}

Based on user.photo-uploaded event (and similar) I would like to know how many objects are getting created by users (total per day and per individual user).

How should I organize indices to store these events, so I can easily query them to extract the information that I'm interested in? Should I create a separate index for each event type? Should I group some events together? Or should I even use a single index for all of these events? Is my document structure correct or should I change it to something else?

What should be my reasoning in order to figure this out?


答:
Does it show up multiple times when I made a list API call or only once?

By default, it'll come up only once. You'll need to include the singleEvents parameter and set it to true for the reoccurring events that are reoccurring to show up in the API response (otherwise only the first time the reoccurring event was scheduled will be included).

```<code>calendar.events.list({ calendarId: theCalendarId, singleEvents: true })
</code>```

Title: How to deal with recurring events using the google calendar API?

Body: I'm using the Google Calendar API and nodejs. I have an app that allows patients to book appointments with doctors. But first, I check the doctor's calendar to make sure they do not have appointments at this time. How can I tell if an event is recurring? Does it show up multiple times when I make a list API call or only once?

Body:
Does it show up multiple times when I made a list API call or only once?

By default, it'll come up only once. You'll need to include the singleEvents parameter and set it to true for the reoccurring events that are reoccurring to show up in the API response (otherwise only the first time the reoccurring event was scheduled will be included).

calendar.events.list({ calendarId: theCalendarId, singleEvents: true })


问:
Filter out records that exceed certain count
was hoping someone could advise on the following problem.

I have a table similar to below and am trying to filter out all IDs that have the same subject and date (not just dedupe but remove complete) from my output.

ID
Date
Subject
Type

abc
1/22/22
Welcome>
Email

def
1/23/22
Offer!
Call

xyz
1/22/22
Welcome>
Email

So in the example above we would want to remove both rows with subject, "Welcome>"

I am able to write a query that shows me the count of IDs per subject and date, but stuck finding a way to remove these from my final output.

```<code>  select distinct
  activitydate,
  name,
  subject,
  count (id)
  from activity
  where activity.activitydate between X and Y'
  and type IN ('Email')
  group by 1,2,3
  having count (id) > 30
  order by count (id) desc
</code>```

Please let me know if any further details are needed and thank you in advance!

答:
If you want to remove the rows where the COUNT by ID and SUBJECT is > 1 then you can do some thing like this.

-- untested

```<code>SELECT * FROM activity
WHERE (ID,SUBJECT) NOT IN
(SELECT ID,SUBJECT FROM activity
GROUP BY ID, SUBJECT HAVING COUNT(*) > 1)
</code>```

Body:
was hoping someone could advise on the following problem.

I have a table similar to below and am trying to filter out all IDs that have the same subject and date (not just dedupe but remove complete) from my output.

ID
Date
Subject
Type

abc
1/22/22
Welcome>
Email

def
1/23/22
Offer!
Call

xyz
1/22/22
Welcome>
Email

So in the example above we would want to remove both rows with subject, "Welcome>"

I am able to write a query that shows me the count of IDs per subject and date, but stuck finding a way to remove these from my final output.

  select distinct
  activitydate,
  name,
  subject,
  count (id)
  from activity
  where activity.activitydate between X and Y'
  and type IN ('Email')
  group by 1,2,3
  having count (id) > 30
  order by count (id) desc

Please let me know if any further details are needed and thank you in advance!

Body:
If you want to remove the rows where the COUNT by ID and SUBJECT is > 1 then you can do some thing like this.

-- untested

SELECT * FROM activity
WHERE (ID,SUBJECT) NOT IN
(SELECT ID,SUBJECT FROM activity
GROUP BY ID, SUBJECT HAVING COUNT(*) > 1)


问:
How do "Graceful Shutdowns" work when max instances = 1?
https://cloud.google.com/run/docs/reference/container-contract

The container instance then receives a
SIGTERM signal indicating the start of a 10 second period before being
shut down (with a SIGKILL signal). During this period, the container
instance is allocated CPU and billed. If the container instance does
not catch the SIGTERM signal, it is immediately shut down.

A: If I have maximum instances set to one, what happens when a new request arrives to the Cloud Run proxy after my container process catches a SIGTERM and is in the "10 second shutdown period"?

I assume that the HTTP request would wait until the shutdown completes, and then Cloud Run will boot a new fresh container to process the HTTP request?

Is this guaranteed?

I ask because my container assumes that it is the only process mutating a network
resource, and two containers would create a race condition (or processing one more HTTP request after the SIGTERM event).

https://cloud.google.com/blog/topics/developers-practitioners/graceful-shutdowns-cloud-run-deep-dive

However, you might sometimes receive this signal before your container
will be shut down due to underlying infrastructure reasons and your
container might still have in-flight connections. The graceful
termination is therefore not always guaranteed.

B: How common would this be? Do containers always get a SIGTERM?

Could I just wait until http_requests_outstanding = 0 AND SIGTERM_has_been_triggered to run my shutdown code (at which point no further HTTP requests will be forwarded to the instance)?

答:
If you received the SIGTERM, that means your container is out of the routable traffic. If a new request comes in, a new instance is created and the request routed to this one.

The SIGTERM is sent most of the time, when the autoscaler choose to offload the instance. However, sometimes, and it's totally fine, the underlying infrastructure doesn't choose to shut down, it's shutdown (case of outage, server physical failure, CPU disruption,... all those kinds of real/physical world issues). That time, the SIGTERM might not be sent.


问:
react-router-dom useParams() inside class component
I'm trying to load a details view based on a react-router-dom route that should grab the URL parameter (id) and use that to further populate the component.

My route looks like /task/:id and my component loads fine, until I try to grab the :id from the URL like so:

```<code>import React from "react";
import { useParams } from "react-router-dom";

class TaskDetail extends React.Component {
    componentDidMount() {
        let { id } = useParams();
        this.fetchData(id);
    }

    fetchData = id => {
        // ...
    };

    render() {
        return <div>Yo</div>;
    }
}

export default TaskDetail;
</code>```

This triggers the following error and I'm unsure where to correctly implement useParams().

```<code>Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
</code>```

The docs only show examples based on functional components, not class based.

答:
SmujMaiku is rigth!!! His answer works perfectly. This is how work today with react-router v6

```<code>enter code here

   import React ,{Component} from 'react'
   import {  useParams } from "react-router-dom";
  import PokeDescription from '../components/PokeDescription'

 class PokeInfoConteiner extends Component{

 render(){

    let urlPokemon= "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/"

    const {idPokemon} = this.props.params
    console.log(idPokemon)

    return(

        <div>
            <PokeDescription pokeImage={`${urlPokemon}${idPokemon}.png?raw=true`}/>
            <p>{}</p>

        </div>

    )

}
</code>```

}

```<code>   export default (props) => (
        <PokeInfoConteiner
            {...props}
            params={useParams()}
   />)
</code>```

Body:
I'm trying to load a details view based on a react-router-dom route that should grab the URL parameter (id) and use that to further populate the component.

My route looks like /task/:id and my component loads fine, until I try to grab the :id from the URL like so:

import React from "react";
import { useParams } from "react-router-dom";

class TaskDetail extends React.Component {
    componentDidMount() {
        let { id } = useParams();
        this.fetchData(id);
    }

    fetchData = id => {
        // ...
    };

    render() {
        return
Yo
;
    }
}

export default TaskDetail;

This triggers the following error and I'm unsure where to correctly implement useParams().

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

The docs only show examples based on functional components, not class based.

Body:
SmujMaiku is rigth!!! His answer works perfectly. This is how work today with react-router v6

enter code here

   import React ,{Component} from 'react'
   import {  useParams } from "react-router-dom";
  import PokeDescription from '../components/PokeDescription'

 class PokeInfoConteiner extends Component{

 render(){

    let urlPokemon= "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/"

    const {idPokemon} = this.props.params
    console.log(idPokemon)

    return(

        <div>
            <PokeDescription pokeImage={`${urlPokemon}${idPokemon}.png?raw=true`}/>
            <p>{}</p>

        </div>

    )

}

}

   export default (props) => (
        <PokeInfoConteiner
            {...props}
            params={useParams()}
   />)


问:
Variable in JavaScript, why putting `var` does not work?
When I put var in front of method and url (var method, and var url) the code does not work.

function intervalcheck(theObject) {
  var xmlhttp = new XMLHttpRequest(),
    method = 'POST',
    url = 'https://thekmui.com/payb/payresult/result.php';

  xmlhttp.open(method, url, true);
  xmlhttp.onload = function () {
```

答:
Take a look at here:

```<code>var xmlhttp = new XMLHttpRequest(),
    method = 'POST',
</code>```

You are putting ','(comma) after each line. Either you leave it empty and browser handle the rest. Or you can put ';' semi-colon like this:

```<code> var xmlhttp = new XMLHttpRequest();
    method = 'POST';
</code>```

Otherwise the code will produce a massive error.
You may follow this post as well:
Send POST data using XMLHttpRequest

Body:
Take a look at here:

var xmlhttp = new XMLHttpRequest(),
    method = 'POST',

You are putting ','(comma) after each line. Either you leave it empty and browser handle the rest. Or you can put ';' semi-colon like this:

 var xmlhttp = new XMLHttpRequest();
    method = 'POST';

Otherwise the code will produce a massive error.
You may follow this post as well:
Send POST data using XMLHttpRequest