问:
Why is my data not rendering from this.state?
I've been trying to get an array to come over into react and then display it on the browser. The data is coming over, but for some reason I cannot display it.

ReactJs:

```<code>import React, { Component } from "react";

export default class RegisterPage extends Component {
    constructor(props){
        super(props);
        this.state = {

        };

        this.getPlayers();
    }

    getPlayers() {
        fetch('/draft/get-players')
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                players: data,
            });
        });
    }

    render(){
        return (<h1>{this.state.players[0].name}</h1>)
    }
}
</code>```

I initially was trying to .map this into multiple lines of HTML, but through troubleshooting learned that I'm not even able to get a single element out of the array.

JSON from /draft/get-players:

```<code>[
    {
        "id": 1,
        "name": "Aidan Hutchinson",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Michigan",
        "age": "SR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 2,
        "name": "Aidan Hutchinson",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Michigan",
        "age": "SR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 3,
        "name": "Kayvon Thidobeaux",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Oregon",
        "age": "SOPH",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 4,
        "name": "Kyle Hamilton",
        "position": "S",
        "EstimatedRound": 1,
        "college": "Notre Dame",
        "age": "JR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 5,
        "name": "Ikem Ekwonu",
        "position": "OL",
        "EstimatedRound": 1,
        "college": "NC State",
        "age": "SOPH",
        "TakenRound": null,
        "TakenPick": null
    }
]
</code>```

答:
I figured out the issue.

The page was rendering before the data was fetched, so when the page rendered it threw an error because 'this.state.players' was empty.

I fixed this by creating the element with the intial render knowing it would be empty, but when the state changes it updates to element. The element contains the JSX which will then render with my information.

Code:

```<code>import React, { Component } from "react";

export default class RegisterPage extends Component {
    constructor(props){
        super(props);
        this.state = {
            players:[],
         }

        this.getPlayers();
    }

    getPlayers() {
        fetch('/draft/get-players')
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                players: data,
            });
        });
    }

    render(){
        let players = this.state.players.map((player)=>{
            return(
                <div>
                    {player.name}
                </div>
            );
        }
        );
        return (
            <div>
                {players}
            </div>)
    }
}
</code>```

This SO thread helped me solve this.
Create elements dynamically within React component

Body:
I've been trying to get an array to come over into react and then display it on the browser. The data is coming over, but for some reason I cannot display it.

ReactJs:

import React, { Component } from "react";

export default class RegisterPage extends Component {
    constructor(props){
        super(props);
        this.state = {

        };

        this.getPlayers();
    }

    getPlayers() {
        fetch('/draft/get-players')
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                players: data,
            });
        });
    }

    render(){
        return (
{this.state.players[0].name}
)
    }
}

I initially was trying to .map this into multiple lines of HTML, but through troubleshooting learned that I'm not even able to get a single element out of the array.

JSON from /draft/get-players:

[
    {
        "id": 1,
        "name": "Aidan Hutchinson",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Michigan",
        "age": "SR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 2,
        "name": "Aidan Hutchinson",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Michigan",
        "age": "SR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 3,
        "name": "Kayvon Thidobeaux",
        "position": "EDGE",
        "EstimatedRound": 1,
        "college": "Oregon",
        "age": "SOPH",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 4,
        "name": "Kyle Hamilton",
        "position": "S",
        "EstimatedRound": 1,
        "college": "Notre Dame",
        "age": "JR",
        "TakenRound": null,
        "TakenPick": null
    },
    {
        "id": 5,
        "name": "Ikem Ekwonu",
        "position": "OL",
        "EstimatedRound": 1,
        "college": "NC State",
        "age": "SOPH",
        "TakenRound": null,
        "TakenPick": null
    }
]

Body:
I figured out the issue.

The page was rendering before the data was fetched, so when the page rendered it threw an error because 'this.state.players' was empty.

I fixed this by creating the element with the intial render knowing it would be empty, but when the state changes it updates to element. The element contains the JSX which will then render with my information.

Code:

import React, { Component } from "react";

export default class RegisterPage extends Component {
    constructor(props){
        super(props);
        this.state = {
            players:[],
         }

        this.getPlayers();
    }

    getPlayers() {
        fetch('/draft/get-players')
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                players: data,
            });
        });
    }

    render(){
        let players = this.state.players.map((player)=>{
            return(
                <div>
                    {player.name}
                </div>
            );
        }
        );
        return (
            <div>
                {players}
            </div>)
    }
}

This SO thread helped me solve this.
Create elements dynamically within React component


来源: stackexchange

问:
Convert written out date (DD.MMMM.YYYY at hh:mm apm) string into date value
Unfortunately, the Google-Sheets sync extension saves the timestamp as a string. (Example: February 6, 2022 at 11:40 pm). Is there any way of automatically converting this automatically to an actual date? I tried the usual date conversion formulas but they dont work. Maybe a work-around?</p>

答:
Suppose that your string-dates are in A2:A.

Place the following formula into the Row-2 cell of any other open column (e.g., B2):

=IF(A2:A="",,DATEVALUE(REGEXEXTRACT(A2:A,"^(.+),\s"))+REGEXEXTRACT(A2:A,"\d+:.+$"))

ContentLicense: CC BY-SA 4.0


问:
Keep changing text in same place C# console
I am creating a quiz with a timer. After asking for the number of questions they want to answer and the time for answering the questions, I would like to show a timer that keeps counting down on the same line. Below the timer I would like to show all the quiz questions.

However every time a question is asked, the timer appears on the new line.

I have already tried following this question, but it doesn't fix my problem. How can I update the current line in a C# Windows Console App?

```<code>public class GamePlay
{
    private static int _secondPassed;
    private static int _timeForAnswering;
    private static bool _isTimerFinished;

    private static void Timing()
    {
        Timer timer = new Timer(TimerCallback, null, 0, 1000);
        Console.ReadKey();
    }

    private static void TimerCallback(Object o)
    {
        if (_secondPassed >= _timeForAnswering)
        {
            _isTimerFinished = true;
        }
        else
        {
            _isTimerFinished = false;
            _secondPassed++;
            Console.Write($"\rYou have {_timeForAnswering - _secondPassed} seconds left.");
        }
    }

    public static async Task PlayGame(int numberOfQuestions, int timeForAnswering)
    {
        _timeForAnswering = timeForAnswering;
        Random random = new Random();
        await Task.Run(() => Timing());
        for (int q = 1; q < numberOfQuestions + 1; q++)
        {
            if (_isTimerFinished)
            {
                Console.WriteLine();
                Console.WriteLine("Game Over!");
                break;
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine(/* Ask Question */);
                // Get Answer
                double usersAnswer = Console.ReadLine();
            }
        }
    }
}
</code>```

答:
Console.SetCursorPosition is the way to go. With that you can modify any line in the Console.

https://learn.microsoft.com/de-de/dotnet/api/system.console.setcursorposition?view=net-6.0

Body:
I am creating a quiz with a timer. After asking for the number of questions they want to answer and the time for answering the questions, I would like to show a timer that keeps counting down on the same line. Below the timer I would like to show all the quiz questions.

However every time a question is asked, the timer appears on the new line.

I have already tried following this question, but it doesn't fix my problem. How can I update the current line in a C# Windows Console App?

public class GamePlay
{
    private static int _secondPassed;
    private static int _timeForAnswering;
    private static bool _isTimerFinished;

    private static void Timing()
    {
        Timer timer = new Timer(TimerCallback, null, 0, 1000);
        Console.ReadKey();
    }

    private static void TimerCallback(Object o)
    {
        if (_secondPassed >= _timeForAnswering)
        {
            _isTimerFinished = true;
        }
        else
        {
            _isTimerFinished = false;
            _secondPassed++;
            Console.Write($"\rYou have {_timeForAnswering - _secondPassed} seconds left.");
        }
    }

    public static async Task PlayGame(int numberOfQuestions, int timeForAnswering)
    {
        _timeForAnswering = timeForAnswering;
        Random random = new Random();
        await Task.Run(() => Timing());
        for (int q = 1; q < numberOfQuestions + 1; q++)
        {
            if (_isTimerFinished)
            {
                Console.WriteLine();
                Console.WriteLine("Game Over!");
                break;
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine(/* Ask Question */);
                // Get Answer
                double usersAnswer = Console.ReadLine();
            }
        }
    }
}


问:
passing std::plus as an argument
How do I pass std::plus as an argument across functions?

```<code>#include<functional>
#include<iostream>

template < class T, typename F >
T fn(T a, T b, F f)
{
        return f<T>()(a,b);
}

template<class T>
struct X
{
    template < typename F>
    T foo(T a, T b, F f)
    {
        return fn<T, F>(a,b,f);
    }
};

int main()
{
    int a = 1;
    int b = 1;
    X<int> f;
    std::cout<< f.foo(a,b, std::plus<int>);
    return 0;
}
</code>```

https://onlinegdb.com/g5NZc2x9V

main.cpp:7:21: error: expected primary-expression before ‘)’ token

答:
std::plus<int> is a type, not an object or function. So you cannot pass it to a function. You can however create an object of that type and pass that:

```<code>std::cout<< f.foo(a,b, std::plus<int>{});
</code>```

Then in the call

```<code>return f<T>()(a,b);
</code>```

the template arguments and first () make no sense. f is not a template, it is an object whose operator() you want to call, so:

```<code>return f(a,b);
</code>```

Title: passing std::plus as an argument

Body:
How do I pass std::plus as an argument across functions?

#include<functional>
#include<iostream>

template < class T, typename F >
T fn(T a, T b, F f)
{
        return f<T>()(a,b);
}

template<class T>
struct X
{
    template < typename F>
    T foo(T a, T b, F f)
    {
        return fn<T, F>(a,b,f);
    }
};

int main()
{
    int a = 1;
    int b = 1;
    X<int> f;
    std::cout<< f.foo(a,b, std::plus<int>);
    return 0;
}

https://onlinegdb.com/g5NZc2x9V

main.cpp:7:21: error: expected primary-expression before ‘)’ token

Body:
std::plus<int> is a type, not an object or function. So you cannot pass it to a function. You can however create an object of that type and pass that:

std::cout<< f.foo(a,b, std::plus<int>{});

Then in the call

return f<T>()(a,b);

the template arguments and first () make no sense. f is not a template, it is an object whose operator() you want to call, so:

return f(a,b);


问:
Transpose a tibble
I have this tibble:

```<code>tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)
</code>```

I want to transpose it into this tibble:

```<code>tibble(Cor = c("a,b","b,c"),
       Linear = c("x1","x3"),
       Rank = c("x2","x4")
)
</code>```

Is there a tidyverse simple command to do so?

答:
A faster approach is just using the R base function t() after a pipe %>%

```<code>df = tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)
df_t = df %>% t()
df_t
    [,1]     [,2]
Cor "Linear" "Rank"
a,b "x1"     "x2"
b,c "x3"     "x4"
</code>```

Title: Transpose a tibble

Body:
I have this tibble:

tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)

I want to transpose it into this tibble:

tibble(Cor = c("a,b","b,c"),
       Linear = c("x1","x3"),
       Rank = c("x2","x4")
)

Is there a tidyverse simple command to do so?

Body:
A faster approach is just using the R base function t() after a pipe %>%

df = tibble(Cor = c("Linear", "Rank"),
       `a,b` =  c("x1","x2"),
       `b,c` = c("x3","x4")
)
df_t = df %>% t()
df_t
    [,1]     [,2]
Cor "Linear" "Rank"
a,b "x1"     "x2"
b,c "x3"     "x4"


问:
Why the background of a texture gets black if the alpha channel gets changed in the fragment shader?
I have the following texture which has transparency and it renders okay.

I want to fade this texture by changing the displayed alpha channel of each pixel, so I wrote this on the fragment shader

```<code>void main()
{
  fragColor = texture(uTexture, texturePosition);
  fragColor.a = uAlpha;
}
</code>```

This works as expected, except now where the texture is transparent it renders like it's behind something that is black

I'm missing something? Why adding an alpha channel changes the background of the texture to black?

答:
I found a solution, but I don't understand why this works

```<code>void main()
{
  fragColor = texture(uTexture, texturePosition);
  fragColor *= vec4(uAlpha);
}
</code>```

Body:
I have the following texture which has transparency and it renders okay.

I want to fade this texture by changing the displayed alpha channel of each pixel, so I wrote this on the fragment shader

void main()
{
  fragColor = texture(uTexture, texturePosition);
  fragColor.a = uAlpha;
}

This works as expected, except now where the texture is transparent it renders like it's behind something that is black

I'm missing something? Why adding an alpha channel changes the background of the texture to black?

Body:
I found a solution, but I don't understand why this works

void main()
{
  fragColor = texture(uTexture, texturePosition);
  fragColor *= vec4(uAlpha);
}


问:
Vuetify rendering v-datatable automatically
I have a problem v-datatable rendering each time I change a v-select.

I´d like it render only when I click in a button, I created to do fetch data from server.

Here is the codepen:  https://codepen.io/luizalves/pen/VwrwXwE?editors=101

For now, it´s rendering all times I change the v-select.

```<code>data:()=>({
grupos: [
      { id: 1, nome: 'Diário', ffi: 'YYYY-MM-DD', fff: 'DD-MM-YYYY' },
      { id: 2, nome: 'Mensal', ffi: 'YYYY-MM', fff: 'MM-YYYY' },
      { id: 3, nome: 'Anual', ffi: 'YYYY', fff: 'YYYY' },
    ],
grupo:1
headers: [
      { text: 'Data', value: 'label', sortable: false },
      { text: 'Total(R$) ', value: 'total', sortable: false },
    ],
)}
</code>```

// data-table

```<code>        <v-select
              v-model="grupo"
              label="Grupado por"
              :items="grupos"
              item-text="nome"
              item-value="id"
              class="purple-input"
            />
 <v-btn
        class="mt-1 mr-3"
        color="info"
        @click.stop="getEstatisticasPeriodo()"
      >
        Pesquisar
      </v-btn>
    <v-data-table
                  :headers="headers"
                  :items="result_dados"
                  :items-per-page="3"
                  :footer-props="{
                    'items-per-page-options': [3, 5, 10, 20, 30, 40, 50],
                  }"
                  class="elevation-1"
                >
                  <template
                    v-for="(header, i) in headers"
                    #[`item.${header.value}`]="{ item }"
                  >
                    <template v-if="header.value !== 'actions'">
                      <span :key="i">
                        {{ formatColumn(item, header) }}
                      </span>
                    </template>
                  </template>
         </v-data-table>
 methods: {
    formatColumn(item, col) {
      if (!item[col.value]) return ''
      if (['total'].includes(col.value)) {
        const formatado = Number(item[col.value]).toLocaleString('pt-BR', {
          style: 'currency',
          currency: 'BRL',
        })
        return formatado
      }
      if (['label'].includes(col.value)) {
        const ffi = this.grupos.find((m) => m.id == this.grupo).ffi
        const fff = this.grupos.find((m) => m.id == this.grupo).fff
        return this.$moment(item[col.value], ffi).format(fff)
      } else return item[col.value]
    },
getEstatisticasPeriodo(){
        // fetch api data
}
....
</code>```

答:
Any data value you access in formatCalories will be added the list of watched values. When the value changes, it will re-render the view and call formatCalories. To solve that issue, I just created a selectValue property that is only set when the button is clicked.

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      group: 1,
      selectValue: 1,
      groups: [
       { id: 1, name: 'day'},
       { id: 2, name: 'month' },
       { id: 3, name: 'year' },
      ],
      headers: [
        {
          text: 'Dessert (100g serving)',
          align: 'start',
          sortable: false,
          value: 'name',
        },
        { text: 'Calories', value: 'calories' },
        { text: 'Fat (g)', value: 'fat' },
        { text: 'Carbs (g)', value: 'carbs' },
        { text: 'Protein (g)', value: 'protein' },
        { text: 'Iron (%)', value: 'iron' },
      ],
      desserts: [
        {
          name: 'Frozen Yogurt',
          calories: 159,
          fat: 6.0,
          carbs: 24,
          protein: 4.0,
          iron: '1%',
        },
        {
          name: 'Ice cream sandwich',
          calories: 237,
          fat: 9.0,
          carbs: 37,
          protein: 4.3,
          iron: '1%',
        },
        {
          name: 'Eclair',
          calories: 262,
          fat: 16.0,
          carbs: 23,
          protein: 6.0,
          iron: '7%',
        },
        {
          name: 'Cupcake',
          calories: 305,
          fat: 3.7,
          carbs: 67,
          protein: 4.3,
          iron: '8%',
        },
        {
          name: 'Gingerbread',
          calories: 356,
          fat: 16.0,
          carbs: 49,
          protein: 3.9,
          iron: '16%',
        },
        {
          name: 'Jelly bean',
          calories: 375,
          fat: 0.0,
          carbs: 94,
          protein: 0.0,
          iron: '0%',
        },
        {
          name: 'Lollipop',
          calories: 392,
          fat: 0.2,
          carbs: 98,
          protein: 0,
          iron: '2%',
        },
        {
          name: 'Honeycomb',
          calories: 408,
          fat: 3.2,
          carbs: 87,
          protein: 6.5,
          iron: '45%',
        },
        {
          name: 'Donut',
          calories: 452,
          fat: 25.0,
          carbs: 51,
          protein: 4.9,
          iron: '22%',
        },
        {
          name: 'KitKat',
          calories: 518,
          fat: 26.0,
          carbs: 65,
          protein: 7,
          iron: '6%',
        },
      ],
    }
  },
  methods: {
    onSubmit() {
      this.selectValue = this.$refs.select.value;
    },
    formatCalories(calories) {
      const suffix = {
        1: '-red',
        2: '-orange',
        3: '-green'
      };

      return calories + suffix[this.selectValue];
    }
  },
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <v-app id="inspire">
    <v-row>
      <v-col cols='3'>
    <v-btn elevation="2" @click="onSubmit"> Submit </v-btn>
    <v-select
          v-model="group"
          label="Grouped by"
          :items="groups"
          item-text="name"
          item-value="id"
          class="purple-input"
          ref="select"
        />
        </v-col>
      </v-row>
    <v-data-table
      :headers="headers"
      :items="desserts"
      class="elevation-1"
    >
      <template v-slot:item.calories="{ item }">
          {{ formatCalories(item.calories) }}
         </template>
    </v-data-table>

  </v-app>
</div></code>```

Body:
I have a problem v-datatable rendering each time I change a v-select.

I´d like it render only when I click in a button, I created to do fetch data from server.

Here is the codepen:  https://codepen.io/luizalves/pen/VwrwXwE?editors=101

For now, it´s rendering all times I change the v-select.

data:()=>({
grupos: [
      { id: 1, nome: 'Diário', ffi: 'YYYY-MM-DD', fff: 'DD-MM-YYYY' },
      { id: 2, nome: 'Mensal', ffi: 'YYYY-MM', fff: 'MM-YYYY' },
      { id: 3, nome: 'Anual', ffi: 'YYYY', fff: 'YYYY' },
    ],
grupo:1
headers: [
      { text: 'Data', value: 'label', sortable: false },
      { text: 'Total(R$) ', value: 'total', sortable: false },
    ],
)}

// data-table

        <v-select
              v-model="grupo"
              label="Grupado por"
              :items="grupos"
              item-text="nome"
              item-value="id"
              class="purple-input"
            />
 <v-btn
        class="mt-1 mr-3"
        color="info"
        @click.stop="getEstatisticasPeriodo()"
      >
        Pesquisar
      </v-btn>
    <v-data-table
                  :headers="headers"
                  :items="result_dados"
                  :items-per-page="3"
                  :footer-props="{
                    'items-per-page-options': [3, 5, 10, 20, 30, 40, 50],
                  }"
                  class="elevation-1"
                >
                  <template
                    v-for="(header, i) in headers"
                    #[`item.${header.value}`]="{ item }"
                  >
                    <template v-if="header.value !== 'actions'">

                        {{ formatColumn(item, header) }}

                    </template>
                  </template>
         </v-data-table>
 methods: {
    formatColumn(item, col) {
      if (!item[col.value]) return ''
      if (['total'].includes(col.value)) {
        const formatado = Number(item[col.value]).toLocaleString('pt-BR', {
          style: 'currency',
          currency: 'BRL',
        })
        return formatado
      }
      if (['label'].includes(col.value)) {
        const ffi = this.grupos.find((m) => m.id == this.grupo).ffi
        const fff = this.grupos.find((m) => m.id == this.grupo).fff
        return this.$moment(item[col.value], ffi).format(fff)
      } else return item[col.value]
    },
getEstatisticasPeriodo(){
        // fetch api data
}
....

Body:
Any data value you access in formatCalories will be added the list of watched values. When the value changes, it will re-render the view and call formatCalories. To solve that issue, I just created a selectValue property that is only set when the button is clicked.

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      group: 1,
      selectValue: 1,
      groups: [
       { id: 1, name: 'day'},
       { id: 2, name: 'month' },
       { id: 3, name: 'year' },
      ],
      headers: [
        {
          text: 'Dessert (100g serving)',
          align: 'start',
          sortable: false,
          value: 'name',
        },
        { text: 'Calories', value: 'calories' },
        { text: 'Fat (g)', value: 'fat' },
        { text: 'Carbs (g)', value: 'carbs' },
        { text: 'Protein (g)', value: 'protein' },
        { text: 'Iron (%)', value: 'iron' },
      ],
      desserts: [
        {
          name: 'Frozen Yogurt',
          calories: 159,
          fat: 6.0,
          carbs: 24,
          protein: 4.0,
          iron: '1%',
        },
        {
          name: 'Ice cream sandwich',
          calories: 237,
          fat: 9.0,
          carbs: 37,
          protein: 4.3,
          iron: '1%',
        },
        {
          name: 'Eclair',
          calories: 262,
          fat: 16.0,
          carbs: 23,
          protein: 6.0,
          iron: '7%',
        },
        {
          name: 'Cupcake',
          calories: 305,
          fat: 3.7,
          carbs: 67,
          protein: 4.3,
          iron: '8%',
        },
        {
          name: 'Gingerbread',
          calories: 356,
          fat: 16.0,
          carbs: 49,
          protein: 3.9,
          iron: '16%',
        },
        {
          name: 'Jelly bean',
          calories: 375,
          fat: 0.0,
          carbs: 94,
          protein: 0.0,
          iron: '0%',
        },
        {
          name: 'Lollipop',
          calories: 392,
          fat: 0.2,
          carbs: 98,
          protein: 0,
          iron: '2%',
        },
        {
          name: 'Honeycomb',
          calories: 408,
          fat: 3.2,
          carbs: 87,
          protein: 6.5,
          iron: '45%',
        },
        {
          name: 'Donut',
          calories: 452,
          fat: 25.0,
          carbs: 51,
          protein: 4.9,
          iron: '22%',
        },
        {
          name: 'KitKat',
          calories: 518,
          fat: 26.0,
          carbs: 65,
          protein: 7,
          iron: '6%',
        },
      ],
    }
  },
  methods: {
    onSubmit() {
      this.selectValue = this.$refs.select.value;
    },
    formatCalories(calories) {
      const suffix = {
        1: '-red',
        2: '-orange',
        3: '-green'
      };

      return calories + suffix[this.selectValue];
    }
  },
})

<div id="app">
  <v-app id="inspire">
    <v-row>
      <v-col cols='3'>
    <v-btn elevation="2" @click="onSubmit"> Submit </v-btn>
    <v-select
          v-model="group"
          label="Grouped by"
          :items="groups"
          item-text="name"
          item-value="id"
          class="purple-input"
          ref="select"
        />
        </v-col>
      </v-row>
    <v-data-table
      :headers="headers"
      :items="desserts"
      class="elevation-1"
    >
      <template v-slot:item.calories="{ item }">
          {{ formatCalories(item.calories) }}
         </template>
    </v-data-table>

  </v-app>
</div>


问:
Unable to get SUM of a nested calculated field in Tableau
I am trying to get SUM() of a nested calculated field and not able to achieve it.

I have fields A, B and C. I need to display result for each row as change in A relative to C over time. I am doing that using the formula

(A- previous A)*(previous B/previous A) / previous C.

previous meaning value of same category from previous date. So tableau formula looks like this:

(SUM(A)-LOOKUP(SUM(A), -1))*(LOOKUP(SUM(B),-1)/LOOKUP(SUM(A),-1))/(LOOKUP(MIN(C),-1))

Applying this formula, result looks right for individual rows but the sum of individual rows is incorrect as it is not adding up the calculated value of each row and instead applying formula on the sum of each variable in the formula.

So, expected result is 0.6% but tableau is giving 0.9%.

I tried window_sum() on the calculated field but that returns same result as calculated field.

How can I get the sum of nested calculated field?

答:
You are creating a table calc - because you use the lookup() function. Table calcs operate on (I.e. take as input) the aggregated query results returned from the data source. That is  different from other calculations such as record-level, aggregate or LOD calcs — all of which take the original data rows as input. So it sounds like you are mixing concepts.

Table calcs are performed client-side, late in the order of operations. Other calcs are performed server-side, I.e. by the database server.

Table calcs are the only calcs in Tableau that can take order into account. Table calcs only see the aggregated query results that were fetched from the data source.

So you can either:

Fetch the level of detail you need for your calcs by adding more dimensions to the viz, say with the detail shelf

Or use custom sql or a database view to write an analytic or windowing query - which can take row order into account in the calculation


问:
Rcpp wrapper for algorithm to generate r x c contingency tables
I'm trying to use this C++ implementation of an algorithm for efficiently generating  r x c contingency tables with fixed margins: https://people.sc.fsu.edu/%7Ejburkardt/cpp_src/asa159/asa159.html

I'm working in Rcpp and am trying to create a function that I can utilize in R. I'm aware that there's a C implementation of this algorithm in R. That doesn't work for me because I need to be able to utilize this function within Rcpp. As an intermediate step, I'm just trying to wrap this algorithm and export it to R. Seems simple but I've struggled mighty with this.

The original function is defined as follows:

```<code>void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key,
  int *seed, int matrix[],  int *ierror )
</code>```

This is a link directly to the algorithm: https://people.sc.fsu.edu/%7Ejburkardt/cpp_src/asa159/asa159.cpp

I don't need the error handling and couldn't figure out how to deal with the void type so I altered the algorithm slightly and ended up with this:

```<code>int* rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key,
  int *seed, int matrix[])
</code>```

I've made several attempts. Here's one example. This will compile, but when I try to run the function in R, it crashes.

```<code>#include <Rcpp.h>
#include "asa159.h"

using namespace Rcpp;

//[[Rcpp::export]]

IntegerVector rcont2_cpp(int nrow,
                         int ncol,
                         IntegerVector nrowt_r,
                         IntegerVector ncolt_r,
                         bool key_r,
                         int seed_r) {

  std::vector<int>  nrowt_rr = as< std::vector<int> >(nrowt_r);
  std::vector<int>  ncolt_rr = as< std::vector<int> >(ncolt_r);

  int* nrowt = &nrowt_rr[0];
  int* ncolt = &ncolt_rr[0];

  int matrix[nrow * ncol];

  bool *key = &key_r;
  int *seed = &seed_r;

  int* out = rcont2(nrow, ncol, nrowt, ncolt, key, seed, matrix);

  int len_out = *(&out + 1) - out;

  std::vector<int> value_vec(out, out + len_out);

  return wrap(value_vec);

  }
</code>```

I assume I'm making some elementary mistakes here. Thank you in advance to anyone who has time to take a look.

答:
This is actually an excellent question, and I too have had good luck with the nice and very comprehensive site full of routines by John Burkardt at FSU.

But nothing is life is entirely free, and one needs to know a little bit about how C and C++ work to integrate such routines into R via Rcpp.  My version of the final file is much shorter: we just ship rowsums and colsums to it, and get the desired matrix back.  We also add the R call for the example at the bottom (a nice trick!)

Code

```<code>#include <Rcpp.h>
#include <asa159.cpp>

// [[Rcpp::export]]
Rcpp::IntegerMatrix rcont2_cpp(Rcpp::IntegerVector rowsums, Rcpp::IntegerVector colsums) {
    int nrow = rowsums.length();
    int ncol = colsums.length();
    Rcpp::IntegerMatrix matrix(nrow, ncol);
    rcont2(nrow, ncol, rowsums.begin(), colsums.begin(), matrix.begin());
    return matrix;
}

/*** R
rs <- c(6, 5)
cs <- c(3, 4, 4)
rcont2_cpp(rs, cs)
rcont2_cpp(rs, cs)              // different answer as randomized algo
rcont2_cpp(rs, cs)              // different answer as randomized algo
*/
</code>```

Output

This contains three example calls.

```<code>> sourceCpp("rcont2.cpp")
> rs <- c(6, 5)
> cs <- c(3, 4, 4)
> rcont2_cpp(rs, cs)
     [,1] [,2] [,3]
[1,]    3    1    2
[2,]    0    3    2
> rcont2_cpp(rs, cs)
     [,1] [,2] [,3]
[1,]    1    3    2
[2,]    2    1    2
> rcont2_cpp(rs, cs)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    2    1
>
</code>```

Diff to original asa159.cpp

The change to the original asa159.cpp is fairly small: we use R's own RNG, and we simplify the calling interface.  Propagation of error condition via Rcpp::stop() is left as an exercise, as they say :)

```<code>--- asa159.orig.cpp     2020-01-30 08:20:42.000000000 -0600
+++ asa159.cpp  2022-02-06 19:52:20.999042887 -0600
@@ -428,8 +428,8 @@
 }
 //****************************************************************************80

-void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key,
-  int *seed, int matrix[],  int *ierror )
+void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], /*bool *key, */
+              /*int *seed,*/ int matrix[] /*,  int *ierror*/ )

 //****************************************************************************80
 //
@@ -517,6 +517,10 @@
   double x;
   double y;

+  bool keyflag = false;         // added
+  bool *key = &keyflag;         // added
+  int ierr = 0;                 // added
+  int *ierror = &ierr;          // added
   *ierror = 0;
 //
 //  On user's signal, set up the factorial table.
@@ -638,7 +642,7 @@
 //
 //  Generate a pseudo-random number.
 //
-      r = r8_uniform_01 ( seed );
+      r = R::runif(0,1); //r8_uniform_01 ( seed );
 //
 //  Compute the conditional expected value of MATRIX(L,M).
 //
@@ -740,7 +744,7 @@
           break;
         }

-        r = r8_uniform_01 ( seed );
+        r = R::runif(0,1); // r8_uniform_01 ( seed );
         r = sumprb * r;

       }
</code>```

Body:
I'm trying to use this C++ implementation of an algorithm for efficiently generating  r x c contingency tables with fixed margins: https://people.sc.fsu.edu/%7Ejburkardt/cpp_src/asa159/asa159.html

I'm working in Rcpp and am trying to create a function that I can utilize in R. I'm aware that there's a C implementation of this algorithm in R. That doesn't work for me because I need to be able to utilize this function within Rcpp. As an intermediate step, I'm just trying to wrap this algorithm and export it to R. Seems simple but I've struggled mighty with this.

The original function is defined as follows:

void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key,
  int *seed, int matrix[],  int *ierror )

This is a link directly to the algorithm: https://people.sc.fsu.edu/%7Ejburkardt/cpp_src/asa159/asa159.cpp

I don't need the error handling and couldn't figure out how to deal with the void type so I altered the algorithm slightly and ended up with this:

int* rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key,
  int *seed, int matrix[])

I've made several attempts. Here's one example. This will compile, but when I try to run the function in R, it crashes.

#include <Rcpp.h>
#include "asa159.h"

using namespace Rcpp;

//[[Rcpp::export]]

IntegerVector rcont2_cpp(int nrow,
                         int ncol,
                         IntegerVector nrowt_r,
                         IntegerVector ncolt_r,
                         bool key_r,
                         int seed_r) {

  std::vector<int>  nrowt_rr = as< std::vector<int> >(nrowt_r);
  std::vector<int>  ncolt_rr = as< std::vector<int> >(ncolt_r);

  int* nrowt = &nrowt_rr[0];
  int* ncolt = &ncolt_rr[0];

  int matrix[nrow * ncol];

  bool *key = &key_r;
  int *seed = &seed_r;

  int* out = rcont2(nrow, ncol, nrowt, ncolt, key, seed, matrix);

  int len_out = *(&out + 1) - out;

  std::vector<int> value_vec(out, out + len_out);

  return wrap(value_vec);

  }

I assume I'm making some elementary mistakes here. Thank you in advance to anyone who has time to take a look.

Body:
This is actually an excellent question, and I too have had good luck with the nice and very comprehensive site full of routines by John Burkardt at FSU.

But nothing is life is entirely free, and one needs to know a little bit about how C and C++ work to integrate such routines into R via Rcpp.  My version of the final file is much shorter: we just ship rowsums and colsums to it, and get the desired matrix back.  We also add the R call for the example at the bottom (a nice trick!)

Code

#include <Rcpp.h>
#include <asa159.cpp>

// [[Rcpp::export]]
Rcpp::IntegerMatrix rcont2_cpp(Rcpp::IntegerVector rowsums, Rcpp::IntegerVector colsums) {
    int nrow = rowsums.length();
    int ncol = colsums.length();
    Rcpp::IntegerMatrix matrix(nrow, ncol);
    rcont2(nrow, ncol, rowsums.begin(), colsums.begin(), matrix.begin());
    return matrix;
}

/*** R
rs <- c(6, 5)
cs <- c(3, 4, 4)
rcont2_cpp(rs, cs)
rcont2_cpp(rs, cs)              // different answer as randomized algo
rcont2_cpp(rs, cs)              // different answer as randomized algo
*/

Output

This contains three example calls.

> sourceCpp("rcont2.cpp")
> rs <- c(6, 5)
> cs <- c(3, 4, 4)
> rcont2_cpp(rs, cs)
     [,1] [,2] [,3]
[1,]    3    1    2
[2,]    0    3    2
> rcont2_cpp(rs, cs)
     [,1] [,2] [,3]
[1,]    1    3    2
[2,]    2    1    2
> rcont2_cpp(rs, cs)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    2    1
>

Diff to original asa159.cpp

The change to the original asa159.cpp is fairly small: we use R's own RNG, and we simplify the calling interface.  Propagation of error condition via Rcpp::stop() is left as an exercise, as they say :)

--- asa159.orig.cpp     2020-01-30 08:20:42.000000000 -0600
+++ asa159.cpp  2022-02-06 19:52:20.999042887 -0600
@@ -428,8 +428,8 @@
 }
 //****************************************************************************80

-void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key,
-  int *seed, int matrix[],  int *ierror )
+void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], /*bool *key, */
+              /*int *seed,*/ int matrix[] /*,  int *ierror*/ )

 //****************************************************************************80
 //
@@ -517,6 +517,10 @@
   double x;
   double y;

+  bool keyflag = false;         // added
+  bool *key = &keyflag;         // added
+  int ierr = 0;                 // added
+  int *ierror = &ierr;          // added
   *ierror = 0;
 //
 //  On user's signal, set up the factorial table.
@@ -638,7 +642,7 @@
 //
 //  Generate a pseudo-random number.
 //
-      r = r8_uniform_01 ( seed );
+      r = R::runif(0,1); //r8_uniform_01 ( seed );
 //
 //  Compute the conditional expected value of MATRIX(L,M).
 //
@@ -740,7 +744,7 @@
           break;
         }

-        r = r8_uniform_01 ( seed );
+        r = R::runif(0,1); // r8_uniform_01 ( seed );
         r = sumprb * r;

       }


问:
How to index through treeview.item values
The code below changes each item in the row at each of the different columns. In this case six columns.

```<code>for child in treeview.getchildren():
    treeview.item(child, values=('1', '2', '3', '4', '5', '6'))
</code>```

Let's say I wanted to change a value of a cell in a specific row of my treeview. The treeview has 6 columns and I want to change the value of let's say the 5th column.

```<code>for child in treeview.get_children():
    treeview.item(x, option='values')[4]
</code>```

The code above is to select it, but I want to change the value of '5' in let's say '10'. How would I do that?

Any help is appreciated.

答:
You can use Treeview.set():

# assume column name for 5th column is 'col5'
for child in treeview.get_children():
    treeview.set(child, 'col5', '10')
```

Body:
The code below changes each item in the row at each of the different columns. In this case six columns.

for child in treeview.getchildren():
    treeview.item(child, values=('1', '2', '3', '4', '5', '6'))

Let's say I wanted to change a value of a cell in a specific row of my treeview. The treeview has 6 columns and I want to change the value of let's say the 5th column.

for child in treeview.get_children():
    treeview.item(x, option='values')[4]

The code above is to select it, but I want to change the value of '5' in let's say '10'. How would I do that?

Any help is appreciated.


答:
```<code>std::cout<< f.foo(a,b, std::plus<int>);
</code>```

std::plus<int> is a type. Just like int. This fails for the exact same reason the following code would fail to compile, too:

```<code>void function(int n)
{
}

void another_function()
{
    function(int);
}
</code>```

You can't "pass std::plus as an argument" for the same exact reason you can't pass int as an argument.

What you can do, though -- and what you should do --- is to construct an instance of std::plus:

```<code>std::cout<< f.foo(a,b, std::plus<int>{});
</code>```

Now, this passes an actual object, std::plus<int> to this function. However this is not going to be sufficient:

```<code>T fn(T a, T b, F f)
{
        return f<T>()(a,b);
}
</code>```

Here, f is going to be that std::plus<int> object. It is a callable object, so, well, all you have to do is call it:

```<code>T fn(T a, T b, F f)
{
        return f(a,b);
}
</code>```

Title: passing std::plus as an argument

Body:
std::cout<< f.foo(a,b, std::plus<int>);

std::plus<int> is a type. Just like int. This fails for the exact same reason the following code would fail to compile, too:

void function(int n)
{
}

void another_function()
{
    function(int);
}

You can't "pass std::plus as an argument" for the same exact reason you can't pass int as an argument.

What you can do, though -- and what you should do --- is to construct an instance of std::plus:

std::cout<< f.foo(a,b, std::plus<int>{});

Now, this passes an actual object, std::plus<int> to this function. However this is not going to be sufficient:

T fn(T a, T b, F f)
{
        return f<T>()(a,b);
}

Here, f is going to be that std::plus<int> object. It is a callable object, so, well, all you have to do is call it:

T fn(T a, T b, F f)
{
        return f(a,b);
}


问:
How to change indicator color in Toggle Button ( Android)
Hi every body I want to use toggle button but  with different indicator color (like green or red), How to change the color of indicator .

See default indicator on imgur

答:
When I used this answer above like:

```<code><style name="AppTheme.ToggleButton" parent="Base.Widget.AppCompat.Button">
<item name="colorButtonNormal">@color/red</item>
<item name="colorAccent">@color/green</item>
</style>
</code>```

my entire toggle button background become red.

If you want to change only bottom border colors you may use instead:

```<code><style name="AppTheme.ToggleButton" parent="Base.Widget.AppCompat.Button">
    <item name="colorControlNormal">@color/red</item>
    <item name="colorAccent">@color/green</item>
</style>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I used this answer above like:

<style name="AppTheme.ToggleButton" parent="Base.Widget.AppCompat.Button">
<item name="colorButtonNormal">@color/red</item>
<item name="colorAccent">@color/green</item>
</style>

my entire toggle button background become red.

If you want to change only bottom border colors you may use instead:

<style name="AppTheme.ToggleButton" parent="Base.Widget.AppCompat.Button">
    <item name="colorControlNormal">@color/red</item>
    <item name="colorAccent">@color/green</item>
</style>


答:
If you want to pass std::plus as a runtime argument you have to actually construct one.

You can't pass a type as an argument. Trying to pass a naked std::plus<int> is akin to writing a class name or type name there i.e. you would not expect foo(a,b, int) to compile if it expects the third argument to be an int value.

```<code>#include <functional>
#include <iostream>

template < class T, typename F >
T fn(T a, T b, F f)
{
    return f(a, b);
}

template<class T>
struct X
{
    template < typename F>
    T foo(T a, T b, F f)
    {
        return fn<T, F>(a, b, f);
    }
};

int main()
{
    int a = 1;
    int b = 1;
    X<int> f;
    std::cout << f.foo(a, b, std::plus<int>());
    return 0;
}
</code>```

Title: passing std::plus as an argument

Body:
If you want to pass std::plus as a runtime argument you have to actually construct one.

You can't pass a type as an argument. Trying to pass a naked std::plus<int> is akin to writing a class name or type name there i.e. you would not expect foo(a,b, int) to compile if it expects the third argument to be an int value.

#include <functional>
#include <iostream>

template < class T, typename F >
T fn(T a, T b, F f)
{
    return f(a, b);
}

template<class T>
struct X
{
    template < typename F>
    T foo(T a, T b, F f)
    {
        return fn<T, F>(a, b, f);
    }
};

int main()
{
    int a = 1;
    int b = 1;
    X<int> f;
    std::cout << f.foo(a, b, std::plus<int>());
    return 0;
}


问:
Highlight whole countries in Google Maps for Android
Referring to:

Highlight whole countries in Google Maps

I'm trying to return the location of selected countrys by the user in the Google Maps Android application.

Something like this but in Android google maps.  Is there a possibility to do this in android?

Is it possible to do this offline?

答:
Basically there are two things you are trying to do.

1- Reverse geocode in order to get the position of the clicked country. I used a repo that I found on GitHub in order to do this. Since it was efficient and works offline. --> https://github.com/AReallyGoodName/OfflineReverseGeocode

2- As soon as you get the clicked country, you need to highlight it. as explained by @xomena

You can also check this repo that I made which basically implements this.

https://github.com/moumen7/Map_picker


问:
Convert Swift graphics code to UIKit in Xamarin iOS C#
I need to crop an image to a circle in my Xamarin app.
This is platform-dependent, so it'd have to use the UIKit.

I've found the following Swift code (credit Cut a UIImage into a circle):

```<code>extension UIImage {
    var isPortrait:  Bool    { size.height > size.width }
    var isLandscape: Bool    { size.width > size.height }
    var breadth:     CGFloat { min(size.width, size.height) }
    var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
    var breadthRect: CGRect  { .init(origin: .zero, size: breadthSize) }
    var circleMasked: UIImage? {
        guard let cgImage = cgImage?
            .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                              y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                size: breadthSize)) else { return nil }
        let format = imageRendererFormat
        format.opaque = false
        return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
            UIBezierPath(ovalIn: breadthRect).addClip()
            UIImage(cgImage: cgImage, scale: format.scale, orientation: imageOrientation)
            .draw(in: .init(origin: .zero, size: breadthSize))
        }
    }
}
</code>```

Could you help me convert it into UIKit C#?

Thanks!

P.S.  There were no relevant replies, so to the best of my abilities I've put together a version that works. See that below.

答:
There were no relevant replies, so to the best of my abilities I've put together a version that works:

```<code>public UIImage cropToCircle(UIImage inimg) {
     if(null == inimg) return null;

     // step 1. crop to a square:
     var length = Math.Min(inimg.Size.Width, inimg.Size.Height);
     var x = inimg.Size.Width/2 - length/2;
     var y = inimg.Size.Height/2 - length/2;
     var cropRect = new CGRect(x, y, length, length);

     UIGraphics.BeginImageContextWithOptions(cropRect.Size, false, 0);
     var context = UIGraphics.GetCurrentContext();

     context.TranslateCTM(0.0f, (float)length);
     context.ScaleCTM(1.0f, -1.0f);
     context.DrawImage(new RectangleF(0, 0,
            (float)length, (float)length), inimg.CGImage);
     context.ClipToRect(cropRect);

     var croppedImage = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

     // step 2. crop to a circle
     UIImageView imageView = new UIImageView(croppedImage);
     var layer = imageView.Layer;
     layer.MasksToBounds = true;
     layer.CornerRadius =
          (nfloat)(Math.Min(imageView.Frame.Height, imageView.Frame.Width)) / 2;
     UIGraphics.BeginImageContext(imageView.Bounds.Size);
     layer.RenderInContext(UIGraphics.GetCurrentContext());
     var circleImg = UIGraphics.GetImageFromCurrentImageContext();
     UIGraphics.EndImageContext();

     return circleImg;
}
</code>```

(The reason I've used a layer for circular cropping is I don't know how to attach UIBezierPath to the context).

Body:
I need to crop an image to a circle in my Xamarin app.
This is platform-dependent, so it'd have to use the UIKit.

I've found the following Swift code (credit Cut a UIImage into a circle):

extension UIImage {
    var isPortrait:  Bool    { size.height > size.width }
    var isLandscape: Bool    { size.width > size.height }
    var breadth:     CGFloat { min(size.width, size.height) }
    var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
    var breadthRect: CGRect  { .init(origin: .zero, size: breadthSize) }
    var circleMasked: UIImage? {
        guard let cgImage = cgImage?
            .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                              y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                size: breadthSize)) else { return nil }
        let format = imageRendererFormat
        format.opaque = false
        return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
            UIBezierPath(ovalIn: breadthRect).addClip()
            UIImage(cgImage: cgImage, scale: format.scale, orientation: imageOrientation)
            .draw(in: .init(origin: .zero, size: breadthSize))
        }
    }
}

Could you help me convert it into UIKit C#?

Thanks!

P.S.  There were no relevant replies, so to the best of my abilities I've put together a version that works. See that below.

Body:
There were no relevant replies, so to the best of my abilities I've put together a version that works:

public UIImage cropToCircle(UIImage inimg) {
     if(null == inimg) return null;

     // step 1. crop to a square:
     var length = Math.Min(inimg.Size.Width, inimg.Size.Height);
     var x = inimg.Size.Width/2 - length/2;
     var y = inimg.Size.Height/2 - length/2;
     var cropRect = new CGRect(x, y, length, length);

     UIGraphics.BeginImageContextWithOptions(cropRect.Size, false, 0);
     var context = UIGraphics.GetCurrentContext();

     context.TranslateCTM(0.0f, (float)length);
     context.ScaleCTM(1.0f, -1.0f);
     context.DrawImage(new RectangleF(0, 0,
            (float)length, (float)length), inimg.CGImage);
     context.ClipToRect(cropRect);

     var croppedImage = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

     // step 2. crop to a circle
     UIImageView imageView = new UIImageView(croppedImage);
     var layer = imageView.Layer;
     layer.MasksToBounds = true;
     layer.CornerRadius =
          (nfloat)(Math.Min(imageView.Frame.Height, imageView.Frame.Width)) / 2;
     UIGraphics.BeginImageContext(imageView.Bounds.Size);
     layer.RenderInContext(UIGraphics.GetCurrentContext());
     var circleImg = UIGraphics.GetImageFromCurrentImageContext();
     UIGraphics.EndImageContext();

     return circleImg;
}

(The reason I've used a layer for circular cropping is I don't know how to attach UIBezierPath to the context).


问:
Wrapping filter formula into Array Formula to avoid dragging formula down sheet while also using named ranges
Original formula:

```<code>=ARRAY_CONSTRAIN(FILTER(typeOfFund, listOfFunds = $K5), 1, 1)
</code>```

The filter function by itself works (without the ArrayFormula) and if I'm only testing it with "K5" (instead of a range of multiple cells). However, it only outputs into the one cell the formula is located in. So I have to drag down the formula which slows down performance.

So I try to wrap it into an array formula and change the "K5" to a range to a longer range such as K5:K6

```<code>=ARRAYFORMULA(FILTER(typeOfFund, listOfFunds = $K5:K6))
</code>```

I also made sure to delete values down the range to avoid the "this formula will overwrite other cells" error.

答:
As noted by the comments and requests of "player0" and "MattKing," it's difficult (and often impossible) to suggest working formulas without seeing the spreadsheet and data in context. However, here is a stab in the dark at what you may actually need.

Try clearing M5:M and then place the following formula in M5:

=ArrayFormula(IFERROR(VLOOKUP(K5:K,{listOfFunds,typeOfFund},2,FALSE)))

This formula is based on the assumption  that the named ranges listOfFunds and typeOfFund run vertically parallel to one another and have the same starting point and number of rows in each.

If the Force Be With You, it may work.

If not, do share a link to your spreadsheet (or to a copy of it).

Body:
Original formula:

=ARRAY_CONSTRAIN(FILTER(typeOfFund, listOfFunds = $K5), 1, 1)

The filter function by itself works (without the ArrayFormula) and if I'm only testing it with "K5" (instead of a range of multiple cells). However, it only outputs into the one cell the formula is located in. So I have to drag down the formula which slows down performance.

So I try to wrap it into an array formula and change the "K5" to a range to a longer range such as K5:K6

=ARRAYFORMULA(FILTER(typeOfFund, listOfFunds = $K5:K6))

I also made sure to delete values down the range to avoid the "this formula will overwrite other cells" error.


问:
If a line starts with a string print THAT line and THE FOLLOWING one
this is my first post in the Stack Overflow community.Thanks in advance.

I have the following text structure

```<code>name:Light
component_id:12
-------------------
name:Normallight
component_id:13
-------------------
name:Externallight
component_id:14
-------------------
name:Justalight
component_id:15
</code>```

I wonder how can I print the lines that start with "name" together with the next one that starts with "component_id" So that it looks something like this using Python:

```<code>name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15
</code>```

So far I have this script but it only prints the lines that starts with "name"

```<code>x = open("file.txt")

for line in x:
    if line.startswith("name")
        print(line)
</code>```

Thanks

答:
How about using a variable?</p>
```<code>x = open("file.txt")

found = None

for line in x:
    if line.startswith("name"):
        found = line
    elif found is not None:
        print(found + "," + line)
        found = None
</code>```

Body:
this is my first post in the Stack Overflow community.Thanks in advance.

I have the following text structure

name:Light
component_id:12
-------------------
name:Normallight
component_id:13
-------------------
name:Externallight
component_id:14
-------------------
name:Justalight
component_id:15

I wonder how can I print the lines that start with "name" together with the next one that starts with "component_id" So that it looks something like this using Python:

name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15

So far I have this script but it only prints the lines that starts with "name"

x = open("file.txt")

for line in x:
    if line.startswith("name")
        print(line)

Thanks

Body:
How about using a variable?

x = open("file.txt")

found = None

for line in x:
    if line.startswith("name"):
        found = line
    elif found is not None:
        print(found + "," + line)
        found = None


问:
SQL join query using rows which only have date of today to sort
I'm sure this is really simple... just tired now.

I have a query

```<code>SELECT post.*, votes.datetime, COUNT(votes.post_id) AS votes
FROM posts LEFT JOIN votes
ON posts.id = votes.post_id
GROUP BY posts.id
ORDER BY votes DESC
</code>```

I need to fetch all posts on the left table whilst when counting votes on the votes table using the votes which happened today or between 1 hour and another hour of the same day. Does this make enough sense?

I have tried adding

```<code>WHERE DATE(votes.datetime) = DATE(NOW())
</code>```

But no luck, it just shows the rows which have votes which happened today and no other posts rows which have either no votes at all or votes that happened today.

I am using data type datetime for the datetime column

Any ideas how I can do this easily?

Thanks in advance!

-Stefan

答:
```<code>LEFT JOIN (SELECT * FROM votes WHERE DATE(datetime) = DATE(NOW())) votes
</code>```

I suspect this won't give you what you want, since SELECT ... votes.datetime ... will result in each post being listed multiple times, and COUNT(votes.post_id) almost always evaluating to 1.

Unfortunately, I can't grok exactly what you need from your question. (What does "... between 1 hour and another hour of the same day" mean? Also, you can't order by votes.) If you just want a count of today's votes for all posts, you can do this:

```<code>SELECT posts.id,
       (SELECT COUNT(*)
          FROM votes
         WHERE DATE(datetime) = DATE(NOW())
           AND post_id = posts.id
       ) AS num_votes
FROM posts
</code>```

Body:
I'm sure this is really simple... just tired now.

I have a query

SELECT post.*, votes.datetime, COUNT(votes.post_id) AS votes
FROM posts LEFT JOIN votes
ON posts.id = votes.post_id
GROUP BY posts.id
ORDER BY votes DESC

I need to fetch all posts on the left table whilst when counting votes on the votes table using the votes which happened today or between 1 hour and another hour of the same day. Does this make enough sense?

I have tried adding

WHERE DATE(votes.datetime) = DATE(NOW())

But no luck, it just shows the rows which have votes which happened today and no other posts rows which have either no votes at all or votes that happened today.

I am using data type datetime for the datetime column

Any ideas how I can do this easily?

Thanks in advance!

-Stefan

Body:
LEFT JOIN (SELECT * FROM votes WHERE DATE(datetime) = DATE(NOW())) votes

I suspect this won't give you what you want, since SELECT ... votes.datetime ... will result in each post being listed multiple times, and COUNT(votes.post_id) almost always evaluating to 1.

Unfortunately, I can't grok exactly what you need from your question. (What does "... between 1 hour and another hour of the same day" mean? Also, you can't order by votes.) If you just want a count of today's votes for all posts, you can do this:

SELECT posts.id,
       (SELECT COUNT(*)
          FROM votes
         WHERE DATE(datetime) = DATE(NOW())
           AND post_id = posts.id
       ) AS num_votes
FROM posts


问:
Returning a custom status code from express-validator .isEmail()
I have little experience with Node, and even less on Express/express-validator (been more of a NestJS guy). I'm tweaking some validations on an endpoint, and almost everything is working as it should. Currently I'm having a small issue trying to return a 400 HTTP status code when .isEmail() validation fails. Currently it returns the correct message, but with a (apparently default) 404. How can I setup .isEmail() to return a 400 error when it fails? I've tried some workarounds with .custom(), but with no success. Currently the code is:

```<code>exports.recoverPassword = [
    check('email')
    .custom((email, { req }) => {
        return new Promise (async (resolve, reject) => {
            let noEmail = (email === null || email === undefined)
            if(noEmail) {
                req.statusCode = 400
                return reject()
            }
            return resolve();
        })
    }).withMessage('Invalid request.')
    .bail()
    .isEmail()
    .withMessage('Email must be a valid email.')
    .custom((email, {req}) => {
        return new Promise(async (resolve, reject) => {
            let userExists = await ValidationHelper.exists(User, {email});
            if (!userExists) {
                req.statusCode = 404
                return reject()
            }
            return resolve();
        })
    }).withMessage('User not found.')
    .bail()
    .custom(async (email, {req}) => {
        return new Promise(async (resolve, reject) => {
            let user =  await ValidationHelper.first(User, {email})

            if (!user) {
                return reject()
            }
            if(user.blocked_at !== null) {
                req.statusCode = 403
                return reject()
            }
            return resolve()
        })
    }).withMessage('User account is blocked.')
];
</code>```

答:
Try to set the status code to the response not the request</p>
```<code>exports.someRoute = (req, res, next) => {
 res.statusCode = 400
};
</code>```

Body:
I have little experience with Node, and even less on Express/express-validator (been more of a NestJS guy). I'm tweaking some validations on an endpoint, and almost everything is working as it should. Currently I'm having a small issue trying to return a 400 HTTP status code when .isEmail() validation fails. Currently it returns the correct message, but with a (apparently default) 404. How can I setup .isEmail() to return a 400 error when it fails? I've tried some workarounds with .custom(), but with no success. Currently the code is:

exports.recoverPassword = [
    check('email')
    .custom((email, { req }) => {
        return new Promise (async (resolve, reject) => {
            let noEmail = (email === null || email === undefined)
            if(noEmail) {
                req.statusCode = 400
                return reject()
            }
            return resolve();
        })
    }).withMessage('Invalid request.')
    .bail()
    .isEmail()
    .withMessage('Email must be a valid email.')
    .custom((email, {req}) => {
        return new Promise(async (resolve, reject) => {
            let userExists = await ValidationHelper.exists(User, {email});
            if (!userExists) {
                req.statusCode = 404
                return reject()
            }
            return resolve();
        })
    }).withMessage('User not found.')
    .bail()
    .custom(async (email, {req}) => {
        return new Promise(async (resolve, reject) => {
            let user =  await ValidationHelper.first(User, {email})

            if (!user) {
                return reject()
            }
            if(user.blocked_at !== null) {
                req.statusCode = 403
                return reject()
            }
            return resolve()
        })
    }).withMessage('User account is blocked.')
];

Body:
Try to set the status code to the response not the request

exports.someRoute = (req, res, next) => {
 res.statusCode = 400
};


问:
How to print the multiples correctly?
I am trying to display the multiples of a user-inputted number given 6 user-inputted numbers. I think I am sort of close, but I am stuck.

For example, if someone enters "4" and then their 6-number sequence is "23 45 12 16 51 8", it should return 12 16 8 because those are the multiples of the first inputted "4".

So far I have the following:

```<code>#include <iostream>
using namespace std;

//Display multiples of a number that appear within a sequence of numbers.

//E.g. input is looking for multiples of 5 in the following sequence of 6 numbers: 6 10 9 3 25 79 → output: 10 25

int main() {
  int userNum;
  int seq1, seq2, seq3, seq4, seq5, seq6;

  cout << "Enter a number: " << userNum;
  cin >> userNum;

  cout << "Enter a sequence of 6 numbers: " << seq1 << " " << seq2 << " " << seq3 << " " << seq4 << " " << seq5 << " " << seq6;

  cin >> seq1;
  cin >> seq2;
  cin >> seq3;
  cin >> seq4;
  cin >> seq5;
  cin >> seq6;

  int sequence[] = {seq1, seq2, seq3, seq4, seq5, seq6};

  int total;

  for (int sequence[] = seq1; i < 6; i++) {

    if (i % userNum == 0) {
      return total;

    }

  }
  cout << "Multiples in the sequence are: " << total;

}
</code>```

答:
You print userNum and seq1 to seq6 before you've assigned values to them. That makes the program have undefined behavior.

Your for loop has invalid syntax and you also return instead of printing the matching values. A fix could look like this:
```<code>for (int i = 0; i < 6; i++) {
    if (sequence[i] % userNum == 0) {
        std::cout << sequence[i] << ' ';
    }
}
</code>```

You don't actually need the variables seq1 to seq6. Just input directly into sequence. You can also use range-based for loops to make looping over the elements in sequence easier.

Example:

#include <array>     // std::size
#include <iostream>

int main() {
    int userNum;
    std::cout << "Enter a number: ";
    std::cin >> userNum;

    int sequence[6];
    std::cout << "Enter a sequence of " << std::size(sequence) << " numbers: ";

    for(int& num : sequence) { // a range-based for loop
        std::cin >> num;       // assign to all 6 elements in a loop
    }

    std::cout << "Multiples in the sequence are: ";
    for(int num : sequence) { // another range-based for loop
        if(num % userNum == 0) {
            std::cout << num << ' ';
        }
    }
    std::cout << '\n';
}
```

Title: How to print the multiples correctly?

Body:
I am trying to display the multiples of a user-inputted number given 6 user-inputted numbers. I think I am sort of close, but I am stuck.

For example, if someone enters "4" and then their 6-number sequence is "23 45 12 16 51 8", it should return 12 16 8 because those are the multiples of the first inputted "4".

So far I have the following:

#include <iostream>
using namespace std;

//Display multiples of a number that appear within a sequence of numbers.

//E.g. input is looking for multiples of 5 in the following sequence of 6 numbers: 6 10 9 3 25 79 → output: 10 25

int main() {
  int userNum;
  int seq1, seq2, seq3, seq4, seq5, seq6;

  cout << "Enter a number: " << userNum;
  cin >> userNum;

  cout << "Enter a sequence of 6 numbers: " << seq1 << " " << seq2 << " " << seq3 << " " << seq4 << " " << seq5 << " " << seq6;

  cin >> seq1;
  cin >> seq2;
  cin >> seq3;
  cin >> seq4;
  cin >> seq5;
  cin >> seq6;

  int sequence[] = {seq1, seq2, seq3, seq4, seq5, seq6};

  int total;

  for (int sequence[] = seq1; i < 6; i++) {

    if (i % userNum == 0) {
      return total;

    }

  }
  cout << "Multiples in the sequence are: " << total;

}

Body:
You print userNum and seq1 to seq6 before you've assigned values to them. That makes the program have undefined behavior.

Your for loop has invalid syntax and you also return instead of printing the matching values. A fix could look like this:

for (int i = 0; i < 6; i++) {
    if (sequence[i] % userNum == 0) {
        std::cout << sequence[i] << ' ';
    }
}

You don't actually need the variables seq1 to seq6. Just input directly into sequence. You can also use range-based for loops to make looping over the elements in sequence easier.

Example:

#include <array>     // std::size
#include <iostream>

int main() {
    int userNum;
    std::cout << "Enter a number: ";
    std::cin >> userNum;

    int sequence[6];
    std::cout << "Enter a sequence of " << std::size(sequence) << " numbers: ";

    for(int& num : sequence) { // a range-based for loop
        std::cin >> num;       // assign to all 6 elements in a loop
    }

    std::cout << "Multiples in the sequence are: ";
    for(int num : sequence) { // another range-based for loop
        if(num % userNum == 0) {
            std::cout << num << ' ';
        }
    }
    std::cout << '\n';
}


问:
How to return a value from Firebase to a react component?
I am trying to read a value from RealtimeDatabase on Firebase and render it in an element, but it keeps returning undefined. I have the following code:

```<code>const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        return snapshot.val().name;
    })
}

const StudentName = (studentId) => ( <p>{getStudentName(studentId)}</p> )
</code>```

I know it's nothing wrong with the database itself or the value I'm finding, because if I do:

```<code>const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        console.log(snapshot.val().name);
        return "Test";
    })
}
</code>```

I still see a correct name from my database outputted to console as expected, yet "Test" is not returned to the element. However, if I do it like this:

```<code>const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        console.log(snapshot.val().name);
    })
    return "Test";
}
</code>```

then "Test" is returned to the
 element and displayed. I'm very confused, as I don't understand how my console.log() can be reached inside the function but a 'return' statement right after it will not return.

New to React and Firebase, please help! Thank you.

EDIT: I'm sure it's self-explanatory, but you can assume a simple database in the form:

```<code>{ "students": [
    "0": { "name": "David" },
    "1": { "name": "Sally" } ]}
</code>```

If 'studentId' is 0 then 'console.log(snapshot.val().name)' successfully outputs 'David', but 'David' will not return to the
 element.

答:
You can't return something from an asynchronous call like that. If you check in the debugger or add some logging, you'll see that your outer return "Test" runs before the console.log(snapshot.val().name) is ever called.

Instead in React you'll want to use a useState hook (or setState method) to tell React about the new value, so that it can then rerender the UI.

I recommend reading the React documentation on the using the state hook, and the documentation on setState.

Body:
I am trying to read a value from RealtimeDatabase on Firebase and render it in an element, but it keeps returning undefined. I have the following code:

const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        return snapshot.val().name;
    })
}

const StudentName = (studentId) => (
{getStudentName(studentId)}
 )

I know it's nothing wrong with the database itself or the value I'm finding, because if I do:

const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        console.log(snapshot.val().name);
        return "Test";
    })
}

I still see a correct name from my database outputted to console as expected, yet "Test" is not returned to the element. However, if I do it like this:

const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        console.log(snapshot.val().name);
    })
    return "Test";
}

then "Test" is returned to the
 element and displayed. I'm very confused, as I don't understand how my console.log() can be reached inside the function but a 'return' statement right after it will not return.

New to React and Firebase, please help! Thank you.

EDIT: I'm sure it's self-explanatory, but you can assume a simple database in the form:

{ "students": [
    "0": { "name": "David" },
    "1": { "name": "Sally" } ]}

If 'studentId' is 0 then 'console.log(snapshot.val().name)' successfully outputs 'David', but 'David' will not return to the
 element.


答:
If your structure is just composed of three types of lines, and you know that the line that starts with component id comes after the line that starts with name, then you can try to store it in a variable when name appears and then print the entire line when the component id line comes up.

For example:

```<code>for line in x:
    if line.startswith("name"):
        temp = line
    if line.startswith("component_id"):
        print(temp + ',' + line)
</code>```

Title: If a line starts with a string print THAT line and THE FOLLOWING one

Body:
If your structure is just composed of three types of lines, and you know that the line that starts with component id comes after the line that starts with name, then you can try to store it in a variable when name appears and then print the entire line when the component id line comes up.

For example:

for line in x:
    if line.startswith("name"):
        temp = line
    if line.startswith("component_id"):
        print(temp + ',' + line)


问:
Python exec() NameError: name 'o' is not defined
This code chunk here was intended to look for any occurrences of a letter in one list, and if it finds any, it replaces the value in the second list with the same index value.

iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'

def updateList(x, y):
    global iWord
    global cWord
    global letter
    bomb = f"iWord[{x}] = {y}"
    exec(bomb)
    print(iWord)

[updateList(x, y) for x, y in enumerate(cWord) if y == letter]
```
<p>Expected result:</p>
<pre class="lang-none prettyprint-override"><code>['_', 'o', 'o', '_']
</code>```

Actual result:

Traceback (most recent call last):
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 13, in <module>
    [updateList(x, y) for x, y in enumerate(cWord) if y == letter]
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 13, in <listcomp>
    [updateList(x, y) for x, y in enumerate(cWord) if y == letter]
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 10, in updateList
    exec(bomb)
  File "<string>", line 1, in <module>
NameError: name 'o' is not defined
PS C:\Users\night\Desktop\RGL>
```

答:
This code is wrong on so many aspects. I don't know if the purpose was to use exec for fun but this is really not needed. Also using a list comprehension as a loop to execute a function without output is not a recommended practice.

Here are pythonic ways to achieve your goal.

Defining a new list:

```<code>iWord = [b if b==letter else a for a,b in zip(iWord, cWord)]
</code>```

Modifying the list in place:

```<code>for i,x in enumerate(cWord):
    if x == letter:
        iWord[i] = letter
</code>```

Output: ['_', 'o', 'o', '_']

Body:
This code chunk here was intended to look for any occurrences of a letter in one list, and if it finds any, it replaces the value in the second list with the same index value.

iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'

def updateList(x, y):
    global iWord
    global cWord
    global letter
    bomb = f"iWord[{x}] = {y}"
    exec(bomb)
    print(iWord)

[updateList(x, y) for x, y in enumerate(cWord) if y == letter]

Expected result:

['_', 'o', 'o', '_']

Actual result:

Traceback (most recent call last):
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 13, in <module>
    [updateList(x, y) for x, y in enumerate(cWord) if y == letter]
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 13, in <listcomp>
    [updateList(x, y) for x, y in enumerate(cWord) if y == letter]
  File "c:\Users\night\Desktop\RGL\Code\test.py", line 10, in updateList
    exec(bomb)
  File "<string>", line 1, in <module>
NameError: name 'o' is not defined
PS C:\Users\night\Desktop\RGL>

Body:
This code is wrong on so many aspects. I don't know if the purpose was to use exec for fun but this is really not needed. Also using a list comprehension as a loop to execute a function without output is not a recommended practice.

Here are pythonic ways to achieve your goal.

Defining a new list:

iWord = [b if b==letter else a for a,b in zip(iWord, cWord)]

Modifying the list in place:

for i,x in enumerate(cWord):
    if x == letter:
        iWord[i] = letter

Output: ['_', 'o', 'o', '_']


问:
Select records with max date in datatables Uipath
Could you please help me with this?

I have a data table (Uipath) with the following fields: id, account, reg date, exp date. Each id might have more than one account. I need to select one record by id with max reg date.

In order to do this I am using:

(From row In data_dt
Group By id = row(0)  Into grp = Group
Let md = grp.Max(Function (d) d(3))
Select data_dt_max.Rows.Add({id, CDate(md.ToString).ToString("dd/MM/yyyy")})).CopyToDataTable.

This instruction works but does not give me all the fields.  I'm very rusty in programming, so I'm really not sure how to modify it or if I need a different approach.

Thanks very much for your help!

答:
```<code>// select all customers
var customersWithMaxRegDate = data.GroupBy(x => x.Id)
                                  .Select(g => new
                                   {
                                       // grp by id
                                       Id = g.Key,
                                       regDate = g.Max( x => x.regDate),
                                       // get customer record with max regdate
                                       customer = g
                                   );
</code>```


问:
Getting Service Unavailable for service metrices command in EKS
I am getting ServiceUnavailable error when I try to run kubectl top nodes or kubectl top pods command in EKS. I am running my cluster in EKS , and I am not finding any solution for this online. If any one have faced this issue in EKS please let me know how we can resolve this issue

```<code>Error from server (ServiceUnavailable): the server is currently unable to handle the request (get pods.metrics.k8s.io)
</code>```

out put of kubectl get apiservices v1beta1.metrics.k8s.io -o yaml

```<code>apiVersion: apiregistration.k8s.io/v1
kind: APIService
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apiregistration.k8s.io/v1","kind":"APIService","metadata":{"annotations":{},"labels":{"k8s-app":"metrics-server"},"name":"v1beta1.metrics.k8s.io"},"spec":{"group":"metrics.k8s.io","groupPriorityMinimum":100,"insecureSkipTLSVerify":true,"service":{"name":"metrics-server","namespace":"kube-system"},"version":"v1beta1","versionPriority":100}}
  creationTimestamp: "2022-02-03T08:22:59Z"
  labels:
    k8s-app: metrics-server
  name: v1beta1.metrics.k8s.io
  resourceVersion: "1373088"
  uid: 2066d4cb-8105-4aea-9678-8303595dc47b
spec:
  group: metrics.k8s.io
  groupPriorityMinimum: 100
  insecureSkipTLSVerify: true
  service:
    name: metrics-server
    namespace: kube-system
    port: 443
  version: v1beta1
  versionPriority: 100
status:
  conditions:
  - lastTransitionTime: "2022-02-03T08:22:59Z"
    message: 'failing or missing response from https://10.16.55.204:4443/apis/metrics.k8s.io/v1beta1:
      Get "https://10.16.55.204:4443/apis/metrics.k8s.io/v1beta1": dial tcp 10.16.55.204:4443:
      i/o timeout'
    reason: FailedDiscoveryCheck
    status: "False"
    type: Available
</code>```

metrics-server   1/1     1            1           3d22h

kubectl describe deployment metrics-server -n kube-system

```<code>Name:                   metrics-server
Namespace:              kube-system
CreationTimestamp:      Thu, 03 Feb 2022 09:22:59 +0100
Labels:                 k8s-app=metrics-server
Annotations:            deployment.kubernetes.io/revision: 2
Selector:               k8s-app=metrics-server
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  0 max unavailable, 25% max surge
Pod Template:
  Labels:           k8s-app=metrics-server
  Service Account:  metrics-server
  Containers:
   metrics-server:
    Image:      k8s.gcr.io/metrics-server/metrics-server:v0.6.0
    Port:       4443/TCP
    Host Port:  0/TCP
    Args:
      --cert-dir=/tmp
      --secure-port=4443
      --kubelet-insecure-tls=true
      --kubelet-preferred-address-types=InternalIP
      --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
      --kubelet-use-node-status-port
      --metric-resolution=15s
    Requests:
      cpu:        100m
      memory:     200Mi
    Liveness:     http-get https://:https/livez delay=0s timeout=1s period=10s #success=1 #failure=3
    Readiness:    http-get https://:https/readyz delay=20s timeout=1s period=10s #success=1 #failure=3
    Environment:  <none>
    Mounts:
      /tmp from tmp-dir (rw)
  Volumes:
   tmp-dir:
    Type:               EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:          <unset>
  Priority Class Name:  system-cluster-critical
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Progressing    True    NewReplicaSetAvailable
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:   metrics-server-5dcd6cbcb9 (1/1 replicas created)
Events:          <none>
</code>```

答: Download the components.yaml, find and replace 4443 to 443 and do a kubectl replace -f components.yaml -n kube-system --force.

Body:
I am getting ServiceUnavailable error when I try to run kubectl top nodes or kubectl top pods command in EKS. I am running my cluster in EKS , and I am not finding any solution for this online. If any one have faced this issue in EKS please let me know how we can resolve this issue

Error from server (ServiceUnavailable): the server is currently unable to handle the request (get pods.metrics.k8s.io)

out put of kubectl get apiservices v1beta1.metrics.k8s.io -o yaml

apiVersion: apiregistration.k8s.io/v1
kind: APIService
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apiregistration.k8s.io/v1","kind":"APIService","metadata":{"annotations":{},"labels":{"k8s-app":"metrics-server"},"name":"v1beta1.metrics.k8s.io"},"spec":{"group":"metrics.k8s.io","groupPriorityMinimum":100,"insecureSkipTLSVerify":true,"service":{"name":"metrics-server","namespace":"kube-system"},"version":"v1beta1","versionPriority":100}}
  creationTimestamp: "2022-02-03T08:22:59Z"
  labels:
    k8s-app: metrics-server
  name: v1beta1.metrics.k8s.io
  resourceVersion: "1373088"
  uid: 2066d4cb-8105-4aea-9678-8303595dc47b
spec:
  group: metrics.k8s.io
  groupPriorityMinimum: 100
  insecureSkipTLSVerify: true
  service:
    name: metrics-server
    namespace: kube-system
    port: 443
  version: v1beta1
  versionPriority: 100
status:
  conditions:
  - lastTransitionTime: "2022-02-03T08:22:59Z"
    message: 'failing or missing response from https://10.16.55.204:4443/apis/metrics.k8s.io/v1beta1:
      Get "https://10.16.55.204:4443/apis/metrics.k8s.io/v1beta1": dial tcp 10.16.55.204:4443:
      i/o timeout'
    reason: FailedDiscoveryCheck
    status: "False"
    type: Available

metrics-server   1/1     1            1           3d22h

kubectl describe deployment metrics-server -n kube-system

Name:                   metrics-server
Namespace:              kube-system
CreationTimestamp:      Thu, 03 Feb 2022 09:22:59 +0100
Labels:                 k8s-app=metrics-server
Annotations:            deployment.kubernetes.io/revision: 2
Selector:               k8s-app=metrics-server
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  0 max unavailable, 25% max surge
Pod Template:
  Labels:           k8s-app=metrics-server
  Service Account:  metrics-server
  Containers:
   metrics-server:
    Image:      k8s.gcr.io/metrics-server/metrics-server:v0.6.0
    Port:       4443/TCP
    Host Port:  0/TCP
    Args:
      --cert-dir=/tmp
      --secure-port=4443
      --kubelet-insecure-tls=true
      --kubelet-preferred-address-types=InternalIP
      --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
      --kubelet-use-node-status-port
      --metric-resolution=15s
    Requests:
      cpu:        100m
      memory:     200Mi
    Liveness:     http-get https://:https/livez delay=0s timeout=1s period=10s #success=1 #failure=3
    Readiness:    http-get https://:https/readyz delay=20s timeout=1s period=10s #success=1 #failure=3
    Environment:  <none>
    Mounts:
      /tmp from tmp-dir (rw)
  Volumes:
   tmp-dir:
    Type:               EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:          <unset>
  Priority Class Name:  system-cluster-critical
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Progressing    True    NewReplicaSetAvailable
  Available      True    MinimumReplicasAvailable
OldReplicaSets:  <none>
NewReplicaSet:   metrics-server-5dcd6cbcb9 (1/1 replicas created)
Events:          <none>


问:
Change absolute position with FrameLayout
I has a View that should be displayed at a specific position over some images, I already did that using AbsoluteLayout, but I don't want to use it and I'm trying to get the same result with a FrameLayout.

But I can't get this working, this is my two attempts:

```<code>public void showVideo(RectF bounds) {
    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) video.getLayoutParams();
    params.width = (int) bounds.width();
    params.height = (int) bounds.height();
    int x = (int) viewer.getPageXOffset();
    int y = (int) viewer.getPageYOffset();

    video.setPadding((int) (x + bounds.left), (int) (y + bounds.top), (int) (x + bounds.right),
            (int) (y + bounds.bottom));

    video.setLayoutParams(params);
    video.invalidate();

    video.setVisibility(View.VISIBLE);
    video.setFocusable(true);
    video.setFocusableInTouchMode(true);
    video.requestFocus();
}
</code>```

And:

```<code>public void showVideo(RectF bounds, final String videoUrl) {
    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) video.getLayoutParams();
    params.width = (int) bounds.width();
    params.height = (int) bounds.height();
    int x = (int) (viewer.getPageXOffset() + bounds.left);
    int y = (int) (viewer.getPageYOffset() + bounds.top);

    params.leftMargin = x;
    params.topMargin = y;

    video.setLayoutParams(params);
    video.invalidate();

    video.setVisibility(View.VISIBLE);
    video.setFocusable(true);
    video.setFocusableInTouchMode(true);
    video.requestFocus();
}
</code>```

But in both cases, the VideoView are displayed at v(0,0) (left-top corner).

答:
It should work when you set up gravity in LayoutParams.

Try

```<code>params.gravity = Gravity.LEFT | Gravity.TOP;
</code>```

for a start.

Body:
I has a View that should be displayed at a specific position over some images, I already did that using AbsoluteLayout, but I don't want to use it and I'm trying to get the same result with a FrameLayout.

But I can't get this working, this is my two attempts:

public void showVideo(RectF bounds) {
    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) video.getLayoutParams();
    params.width = (int) bounds.width();
    params.height = (int) bounds.height();
    int x = (int) viewer.getPageXOffset();
    int y = (int) viewer.getPageYOffset();

    video.setPadding((int) (x + bounds.left), (int) (y + bounds.top), (int) (x + bounds.right),
            (int) (y + bounds.bottom));

    video.setLayoutParams(params);
    video.invalidate();

    video.setVisibility(View.VISIBLE);
    video.setFocusable(true);
    video.setFocusableInTouchMode(true);
    video.requestFocus();
}

And:

public void showVideo(RectF bounds, final String videoUrl) {
    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) video.getLayoutParams();
    params.width = (int) bounds.width();
    params.height = (int) bounds.height();
    int x = (int) (viewer.getPageXOffset() + bounds.left);
    int y = (int) (viewer.getPageYOffset() + bounds.top);

    params.leftMargin = x;
    params.topMargin = y;

    video.setLayoutParams(params);
    video.invalidate();

    video.setVisibility(View.VISIBLE);
    video.setFocusable(true);
    video.setFocusableInTouchMode(true);
    video.requestFocus();
}

But in both cases, the VideoView are displayed at v(0,0) (left-top corner).

Body:
It should work when you set up gravity in LayoutParams.

Try

params.gravity = Gravity.LEFT | Gravity.TOP;

for a start.


问:
index.js not loading from main.js
I am working on a .net core MVC application. where I have integrated Twilio Video functionality.
In Views/Video/index.cshtml, reference for require js added like this,

```<code><script data-main="../TwilioVideo/main" src="~/TwilioVideo/require.js"></script>
</code>```

folder structure is like,

wwwroot

TwilioVideo

index.js

main.js

require.js

and the main.js file contains code,

```<code>    require.config({
paths: {
    "twilio-video": "https://media.twiliocdn.com/sdk/js/video/releases/2.4.0/twilio-video.min"
}
});
require(["index"], function () {

});
</code>```

when I run the code index file not loading, in the source I can only see main.js and require.js. someone, please help me to understand what might be the issue?

Thanks in advance!

答:
You can try to use code like this:</p>
```<code>require.config({
            paths: {
                "twilio-video": "/TwilioVideo"//It's the path of TwilioVideo folder
            }
        })
        require(["twilio-video/index"], function () {

        });
</code>```

Title: index.js not loading from main.js

Body:
I am working on a .net core MVC application. where I have integrated Twilio Video functionality.
In Views/Video/index.cshtml, reference for require js added like this,

folder structure is like,

wwwroot

TwilioVideo

index.js

main.js

require.js

and the main.js file contains code,

    require.config({
paths: {
    "twilio-video": "https://media.twiliocdn.com/sdk/js/video/releases/2.4.0/twilio-video.min"
}
});
require(["index"], function () {

});

when I run the code index file not loading, in the source I can only see main.js and require.js. someone, please help me to understand what might be the issue?

Thanks in advance!

Body:
You can try to use code like this:

require.config({
            paths: {
                "twilio-video": "/TwilioVideo"//It's the path of TwilioVideo folder
            }
        })
        require(["twilio-video/index"], function () {

        });


问:
mouseover and mouseout events html
how do I make button that when mouse over the button, the text on the button becomes red.
When the mouse left the button, the button text resumes the original color using mouseover and mouseout events.

here is the event for the button

< button id="Button" onclick="test()" > enter

答:
This could easily be done with css however per your question here is how you would accomplish this:</p>
```<code><button id="button" onmouseover="mouseOver()" onmouseout="mouseOut()" onclick="test()" >Enter</button>

<script>
function mouseOver() {
  document.getElementById("button").style.color = "red";
}

function mouseOut() {
  document.getElementById("button").style.color = "black";
}
</script>
</code>```

Title: mouseover and mouseout events html

Body:
This could easily be done with css however per your question here is how you would accomplish this:

<button id="button" onmouseover="mouseOver()" onmouseout="mouseOut()" onclick="test()" >Enter</button>

<script>
function mouseOver() {
  document.getElementById("button").style.color = "red";
}

function mouseOut() {
  document.getElementById("button").style.color = "black";
}
</script>


答:
One approach would be to read the entire file into Python as a string, then use regular expressions:

import re
with open('file.txt', 'r') as file:
    lines = file.read()

matches = [x[0] + ',' + x[1] for x in re.findall(r'\b(name:\w+)\s+(component_id:\d+)', lines)]
print('\n'.join(matches))
```
<p>This prints:</p>
```name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15
```

Body:
this is my first post in the Stack Overflow community.Thanks in advance.

I have the following text structure

name:Light
component_id:12
-------------------
name:Normallight
component_id:13
-------------------
name:Externallight
component_id:14
-------------------
name:Justalight
component_id:15

I wonder how can I print the lines that start with "name" together with the next one that starts with "component_id" So that it looks something like this using Python:

name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15

So far I have this script but it only prints the lines that starts with "name"

x = open("file.txt")

for line in x:
    if line.startswith("name")
        print(line)

Thanks

Body:
One approach would be to read the entire file into Python as a string, then use regular expressions:

import re
with open('file.txt', 'r') as file:
    lines = file.read()

matches = [x[0] + ',' + x[1] for x in re.findall(r'\b(name:\w+)\s+(component_id:\d+)', lines)]
print('\n'.join(matches))

This prints:

name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15


问:
Kotlin implicit conversion?
I just realize that you can actually compare String in Kotlin with < > or <= >=.

enter image description here

But I cannot find the documentation about this? Is this undocumented?

答:
This ends up calling compareTo().  There is no implicit conversion occurring.

The documentation is here:

https://kotlinlang.org/docs/operator-overloading.html#comparison-operators

```<code>a > b     a.compareTo(b) > 0
a < b     a.compareTo(b) < 0
a >= b    a.compareTo(b) >= 0
a <= b    a.compareTo(b) <= 0
</code>```

All comparisons are translated into calls to compareTo, that is required to return Int.

Title: Kotlin implicit conversion?

Body:
This ends up calling compareTo().  There is no implicit conversion occurring.

The documentation is here:

https://kotlinlang.org/docs/operator-overloading.html#comparison-operators

a > b     a.compareTo(b) > 0
a < b     a.compareTo(b) < 0
a >= b    a.compareTo(b) >= 0
a <= b    a.compareTo(b) <= 0

All comparisons are translated into calls to compareTo, that is required to return Int.