问:
My ChartJS dates don't show up correctly from coinranking API
Below is my code to display a chart of a crypto coin and it's change in prices over a period of time. I have also included the jsx file and the .env file

jsx:

```<code>import React from 'react';
import { Line } from 'react-chartjs-2';
import { Col, Row, Typography } from 'antd';

const { Title } = Typography;

const LineChart = ({ coinHistory, currentPrice, coinName }) => {
  const coinPrice = [];
  const coinTimestamp = [];

  for (let i = 0; i < coinHistory?.data?.history?.length; i += 1) {
    coinPrice.push(coinHistory?.data?.history[i].price);
  }

  for (let i = 0; i < coinHistory?.data?.history?.length; i += 1) {
    coinTimestamp.push(new Date(coinHistory?.data?.history[i].timestamp).toLocaleDateString());
  }
  const data = {
    labels: coinTimestamp,
    datasets: [
      {
        label: 'Price In USD',
        data: coinPrice,
        fill: false,
        backgroundColor: '#0071bd',
        borderColor: '#0071bd',
      },
    ],
  };

  const options = {
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  };

  return (
    <>
      <Row className="chart-header">
        <Title level={2} className="chart-title">{coinName} Price Chart </Title>
        <Col className="price-container">
          <Title level={5} className="price-change">Change: {coinHistory?.data?.change}%</Title>
          <Title level={5} className="current-price">Current {coinName} Price: $ {currentPrice}</Title>
        </Col>
      </Row>
      <Line data={data} options={options} />
    </>
  );
};

export default LineChart;
</code>```

.js file:

```<code>import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const cryptoApiHeaders = {
  'x-rapidapi-host': process.env.REACT_APP_CRYPTO_RAPIDAPI_HOST,
  'x-rapidapi-key': process.env.REACT_APP_RAPIDAPI_KEY,
};
const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
  reducerPath: 'cryptoApi',
  baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_CRYPTO_API_URL }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (count) => createRequest(`/coins?limit=${count}`),
    }),

    getCryptoDetails: builder.query({
      query: (coinId) => createRequest(`/coin/${coinId}`),
    }),

    getCryptoHistory: builder.query({
      query: ({ coinId, timeperiod }) => createRequest(`coin/${coinId}/history?timeperiod=${timeperiod}`),
    }),

    getExchanges: builder.query({
      query: () => createRequest('/exchanges'),
    }),
  }),
});

export const {
  useGetCryptosQuery,
  useGetCryptoDetailsQuery,
  useGetExchangesQuery,
  useGetCryptoHistoryQuery,
} = cryptoApi;
</code>```

.env:

```<code>REACT_APP_RAPIDAPI_KEY =  'my_key'
REACT_APP_CRYPTO_API_URL = 'https://coinranking1.p.rapidapi.com'
REACT_APP_NEWS_API_URL = 'https://bing-news-search1.p.rapidapi.com'
REACT_APP_NEWS_RAPIDAPI_HOST = 'bing-news-search1.p.rapidapi.com'
REACT_APP_CRYPTO_RAPIDAPI_HOST ='coinranking1.p.rapidapi.com'

ESLINT_NO_DEV_ERRORS=true
</code>```

When I run the React code all I get are 19/1/1970 as dates on the chart, I am not sure why the real dates are not showing up in the charts. Other data is showing up so I believe the key is fine.

答:
If you use ChartJS V.3 ->

First your should add a date adapter, if you use date-fns or moment there is an adapter for each one example :

```<code>import {
        Chart as ChartJS,
        LinearScale,
        PointElement,
        LineElement,
        Tooltip,
        Filler,
        TimeScale,
    } from 'chart.js'

    import "chartjs-adapter-moment"

    ChartJS.register(
        LinearScale,
        TimeScale,
        PointElement,
        Filler,
LineElement,
    Tooltip,
)
</code>```

Then you have to add the Time format in your xAxes Options :

```<code>  x: {
                    type: 'time',
                    time: {
                        unit: "day",
                        displayFormats: {
                            day: "MMM DD YYYY" // or whatever you want to display your date
                        }
                    },
}
</code>```

If you use ChartJS V2:

Don't install the adapter, it's not necessary but add in your Scales Options :

```<code>xAxes: [
                    {
                        // stacked: true,
                        type: 'time',
                        time: {
                            unit: 'day',
                            displayFormats: {
                                day: 'MMM DD YYYY'
                            }
                        },
                    },
                ],
</code>```

Body:
Below is my code to display a chart of a crypto coin and it's change in prices over a period of time. I have also included the jsx file and the .env file

jsx:

import React from 'react';
import { Line } from 'react-chartjs-2';
import { Col, Row, Typography } from 'antd';

const { Title } = Typography;

const LineChart = ({ coinHistory, currentPrice, coinName }) => {
  const coinPrice = [];
  const coinTimestamp = [];

  for (let i = 0; i < coinHistory?.data?.history?.length; i += 1) {
    coinPrice.push(coinHistory?.data?.history[i].price);
  }

  for (let i = 0; i < coinHistory?.data?.history?.length; i += 1) {
    coinTimestamp.push(new Date(coinHistory?.data?.history[i].timestamp).toLocaleDateString());
  }
  const data = {
    labels: coinTimestamp,
    datasets: [
      {
        label: 'Price In USD',
        data: coinPrice,
        fill: false,
        backgroundColor: '#0071bd',
        borderColor: '#0071bd',
      },
    ],
  };

  const options = {
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  };

  return (
    <>
      <Row className="chart-header">
        <Title level={2} className="chart-title">{coinName} Price Chart </Title>
        <Col className="price-container">
          <Title level={5} className="price-change">Change: {coinHistory?.data?.change}%</Title>
          <Title level={5} className="current-price">Current {coinName} Price: $ {currentPrice}</Title>
        </Col>
      </Row>
      <Line data={data} options={options} />
    </>
  );
};

export default LineChart;

.js file:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const cryptoApiHeaders = {
  'x-rapidapi-host': process.env.REACT_APP_CRYPTO_RAPIDAPI_HOST,
  'x-rapidapi-key': process.env.REACT_APP_RAPIDAPI_KEY,
};
const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
  reducerPath: 'cryptoApi',
  baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_CRYPTO_API_URL }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (count) => createRequest(`/coins?limit=${count}`),
    }),

    getCryptoDetails: builder.query({
      query: (coinId) => createRequest(`/coin/${coinId}`),
    }),

    getCryptoHistory: builder.query({
      query: ({ coinId, timeperiod }) => createRequest(`coin/${coinId}/history?timeperiod=${timeperiod}`),
    }),

    getExchanges: builder.query({
      query: () => createRequest('/exchanges'),
    }),
  }),
});

export const {
  useGetCryptosQuery,
  useGetCryptoDetailsQuery,
  useGetExchangesQuery,
  useGetCryptoHistoryQuery,
} = cryptoApi;

.env:

REACT_APP_RAPIDAPI_KEY =  'my_key'
REACT_APP_CRYPTO_API_URL = 'https://coinranking1.p.rapidapi.com'
REACT_APP_NEWS_API_URL = 'https://bing-news-search1.p.rapidapi.com'
REACT_APP_NEWS_RAPIDAPI_HOST = 'bing-news-search1.p.rapidapi.com'
REACT_APP_CRYPTO_RAPIDAPI_HOST ='coinranking1.p.rapidapi.com'

ESLINT_NO_DEV_ERRORS=true

When I run the React code all I get are 19/1/1970 as dates on the chart, I am not sure why the real dates are not showing up in the charts. Other data is showing up so I believe the key is fine.

Body:
If you use ChartJS V.3 ->

First your should add a date adapter, if you use date-fns or moment there is an adapter for each one example :

import {
        Chart as ChartJS,
        LinearScale,
        PointElement,
        LineElement,
        Tooltip,
        Filler,
        TimeScale,
    } from 'chart.js'

    import "chartjs-adapter-moment"

    ChartJS.register(
        LinearScale,
        TimeScale,
        PointElement,
        Filler,
LineElement,
    Tooltip,
)

Then you have to add the Time format in your xAxes Options :

  x: {
                    type: 'time',
                    time: {
                        unit: "day",
                        displayFormats: {
                            day: "MMM DD YYYY" // or whatever you want to display your date
                        }
                    },
}

If you use ChartJS V2:

Don't install the adapter, it's not necessary but add in your Scales Options :

xAxes: [
                    {
                        // stacked: true,
                        type: 'time',
                        time: {
                            unit: 'day',
                            displayFormats: {
                                day: 'MMM DD YYYY'
                            }
                        },
                    },
                ],


来源: stackexchange

问:
Firebase: Error .getDownloadURL is not a function
I want to get the link to the uploaded image with .getDownloadURL() but I end up with an error:

Uncaught (in promise) TypeError: uploadTask.snapshot.ref.getDownloadURL is not a function

If I remove .getDownloadURL() and .ref then everything works and I end up with:

```<code>Download URL Object { bytesTransferred: 120745, ... ref: {…} }
</code>```

Author source code:

```<code>import {upload} from './upload'
import { initializeApp } from "firebase/app";
import 'firebase/storage'
import { getStorage, ref, uploadBytesResumable } from "firebase/storage"
// Your web app's Firebase configuration

const firebaseConfig = {
  *code Firebase*
}
const app = initializeApp(firebaseConfig)
const storage = getStorage(app)

upload('#file', {
    multi: true,
    accept: ['.png', '.jpg', '.jpeg', '.gif'],
    onUpload(files, blocks) {
        files.forEach((file, index) => {
            const storageRef = ref(storage, `images/${file.name}`);
            const uploadTask = uploadBytesResumable(storageRef, file);

            uploadTask.on('state_changed', snapshot => {
                const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
                const block = blocks[index].querySelector('.preview-info-progress')
                block.textContent = percentage
                block.style.width = percentage
            }, error => {
                console.log(error)
            }, () => {
                uploadTask.snapshot.ref.getDownloadURL().then(url => {  // << problem
                    console.log('Download URL', url)
                })
            })
        })
    }
})
</code>```

Thank you!

答:
This solution from the official Firebase documentation helped.

```<code>...
    onUpload(files, blocks) {
        files.forEach((file, index) => {
            const storage = getStorage();
const starsRef = ref(storage, `images/${file.name}`);

            const uploadTask = uploadBytesResumable(starsRef, file);

            uploadTask.on('state_changed', snapshot => {
                const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
                const block = blocks[index].querySelector('.preview-info-progress')
                block.textContent = percentage
                block.style.width = percentage

            }, error => {
                console.log(error)
            }, () => {
                getDownloadURL(starsRef)
                  .then((url) => {
                console.log('URL:', url);
                })

            })
        })
    }
})
</code>```

I don't know if this is the right solution, and while it works, I'll investigate Firebase further.

ContentLicense: CC BY-SA 4.0

Body:
I want to get the link to the uploaded image with .getDownloadURL() but I end up with an error:

Uncaught (in promise) TypeError: uploadTask.snapshot.ref.getDownloadURL is not a function

If I remove .getDownloadURL() and .ref then everything works and I end up with:

Download URL Object { bytesTransferred: 120745, ... ref: {…} }

Author source code:

import {upload} from './upload'
import { initializeApp } from "firebase/app";
import 'firebase/storage'
import { getStorage, ref, uploadBytesResumable } from "firebase/storage"
// Your web app's Firebase configuration

const firebaseConfig = {
  *code Firebase*
}
const app = initializeApp(firebaseConfig)
const storage = getStorage(app)

upload('#file', {
    multi: true,
    accept: ['.png', '.jpg', '.jpeg', '.gif'],
    onUpload(files, blocks) {
        files.forEach((file, index) => {
            const storageRef = ref(storage, `images/${file.name}`);
            const uploadTask = uploadBytesResumable(storageRef, file);

            uploadTask.on('state_changed', snapshot => {
                const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
                const block = blocks[index].querySelector('.preview-info-progress')
                block.textContent = percentage
                block.style.width = percentage
            }, error => {
                console.log(error)
            }, () => {
                uploadTask.snapshot.ref.getDownloadURL().then(url => {  // << problem
                    console.log('Download URL', url)
                })
            })
        })
    }
})

Thank you!

Body:
This solution from the official Firebase documentation helped.

...
    onUpload(files, blocks) {
        files.forEach((file, index) => {
            const storage = getStorage();
const starsRef = ref(storage, `images/${file.name}`);

            const uploadTask = uploadBytesResumable(starsRef, file);

            uploadTask.on('state_changed', snapshot => {
                const percentage = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0) + '%'
                const block = blocks[index].querySelector('.preview-info-progress')
                block.textContent = percentage
                block.style.width = percentage

            }, error => {
                console.log(error)
            }, () => {
                getDownloadURL(starsRef)
                  .then((url) => {
                console.log('URL:', url);
                })

            })
        })
    }
})

I don't know if this is the right solution, and while it works, I'll investigate Firebase further.


问:
Problems with using accumulate in c++
I'm using OpenCV to access the color data of the pixels within a specified area and currently I'm trying to use the accumulate method in c++ to sum up all the data numbers obtained in that specified area. But right now it has only given me the sum of only a single pixel within the specified area and not the whole area. I'm sure it is giving me the sum of a single pixel because I have used the push_back method and it has given me double the amount in that pixel. Is there something that I have missed and have not written? I'm kind of new to c++ so I would appreciate if someone would point me in the right direction.

```<code>    //the rows of the image
    for(int j=0; j<image; j++){
      int step = j*cols*elemSize;
      //the columns for the image
      for(int i-0; i<image; i++){
        int elm = i*elemSize;
        //obtaining the color data of the pixels
        uchar blue = image.data[step + elm + 0];
        uchar green = image.data[step + elm + 1];
        uchar red = image.data[step + elm + 2];
        std::vector<int> v = {blue};
        std::vector<int> w = {green};
        std::vector<int> x = {red};
        //using accumulate to sum up all the data
        int sumofblue = accumulate(v.begin(), v.end(), 0);
        int sumofgreen = accumulate(w.begin(), w.end(), 0);
        int sumofred = accumulate(x.begin(), x.end(), 0);
</code>```

The blue green red is the color data extracted(0-255) from the specified area and image.data is defined as the image used in the extraction.

答:
Is there something that I have missed and have not written?

you've missed the fact that you are still in the middle of your loop. You need to define v, w and x before the loop, and add each element, then accumulate after the loop.

```<code>std::vector<int> v;
std::vector<int> w;
std::vector<int> x;
//the rows of the image
for(int j=0; j<image/*??*/; j++){
  int step = j*cols*elemSize;
  //the columns for the image
  for(int i-0; i<image/*??*/; i++){
    int elm = i*elemSize;
    //obtaining the color data of the pixels
    v.push_back(image.data[step + elm + 0]);
    w.push_back(image.data[step + elm + 1]);
    x.push_back(image.data[step + elm + 2]);
  }
}

//using accumulate to sum up all the data
int sumofblue = accumulate(v.begin(), v.end(), 0);
int sumofgreen = accumulate(w.begin(), w.end(), 0);
int sumofred = accumulate(x.begin(), x.end(), 0);
</code>```

However you might as well just use += in the loop

```<code>int sumofblue = 0;
int sumofgreen = 0;
int sumofred = 0;
//the rows of the image
for(int j=0; j<image/*??*/; j++){
  int step = j*cols*elemSize;
  //the columns for the image
  for(int i-0; i<image/*??*/; i++){
    int elm = i*elemSize;
    //obtaining the color data of the pixels
    sumofblue += image.data[step + elm + 0];
    sumofgreen += image.data[step + elm + 1];
    sumofred += image.data[step + elm + 2];
  }
}
</code>```

If you have access to a ranges library with stride and drop, you don't need the nested loop at all. Depending on exactly what image.data is, you may need to wrap it in a std::span

```<code>std::span data { image.data, image.data_size }; // cols * rows * elemSize?
auto blue = data | views::stride(3);
auto green = data | views::drop(1) | views::stride(3);
auto red = data | views::drop(2)  | views::stride(3);
int sumofblue = std::accumulate(begin(blue), end(blue), 0);
int sumofgreen = std::accumulate(begin(green), end(green), 0);
int sumofred = std::accumulate(begin(red), end(red), 0);
</code>```

Title: Problems with using accumulate in c++

Body:
I'm using OpenCV to access the color data of the pixels within a specified area and currently I'm trying to use the accumulate method in c++ to sum up all the data numbers obtained in that specified area. But right now it has only given me the sum of only a single pixel within the specified area and not the whole area. I'm sure it is giving me the sum of a single pixel because I have used the push_back method and it has given me double the amount in that pixel. Is there something that I have missed and have not written? I'm kind of new to c++ so I would appreciate if someone would point me in the right direction.

    //the rows of the image
    for(int j=0; j<image; j++){
      int step = j*cols*elemSize;
      //the columns for the image
      for(int i-0; i<image; i++){
        int elm = i*elemSize;
        //obtaining the color data of the pixels
        uchar blue = image.data[step + elm + 0];
        uchar green = image.data[step + elm + 1];
        uchar red = image.data[step + elm + 2];
        std::vector<int> v = {blue};
        std::vector<int> w = {green};
        std::vector<int> x = {red};
        //using accumulate to sum up all the data
        int sumofblue = accumulate(v.begin(), v.end(), 0);
        int sumofgreen = accumulate(w.begin(), w.end(), 0);
        int sumofred = accumulate(x.begin(), x.end(), 0);

The blue green red is the color data extracted(0-255) from the specified area and image.data is defined as the image used in the extraction.

Body:
Is there something that I have missed and have not written?

you've missed the fact that you are still in the middle of your loop. You need to define v, w and x before the loop, and add each element, then accumulate after the loop.

std::vector<int> v;
std::vector<int> w;
std::vector<int> x;
//the rows of the image
for(int j=0; j<image/*??*/; j++){
  int step = j*cols*elemSize;
  //the columns for the image
  for(int i-0; i<image/*??*/; i++){
    int elm = i*elemSize;
    //obtaining the color data of the pixels
    v.push_back(image.data[step + elm + 0]);
    w.push_back(image.data[step + elm + 1]);
    x.push_back(image.data[step + elm + 2]);
  }
}

//using accumulate to sum up all the data
int sumofblue = accumulate(v.begin(), v.end(), 0);
int sumofgreen = accumulate(w.begin(), w.end(), 0);
int sumofred = accumulate(x.begin(), x.end(), 0);

However you might as well just use += in the loop

int sumofblue = 0;
int sumofgreen = 0;
int sumofred = 0;
//the rows of the image
for(int j=0; j<image/*??*/; j++){
  int step = j*cols*elemSize;
  //the columns for the image
  for(int i-0; i<image/*??*/; i++){
    int elm = i*elemSize;
    //obtaining the color data of the pixels
    sumofblue += image.data[step + elm + 0];
    sumofgreen += image.data[step + elm + 1];
    sumofred += image.data[step + elm + 2];
  }
}

If you have access to a ranges library with stride and drop, you don't need the nested loop at all. Depending on exactly what image.data is, you may need to wrap it in a std::span

std::span data { image.data, image.data_size }; // cols * rows * elemSize?
auto blue = data | views::stride(3);
auto green = data | views::drop(1) | views::stride(3);
auto red = data | views::drop(2)  | views::stride(3);
int sumofblue = std::accumulate(begin(blue), end(blue), 0);
int sumofgreen = std::accumulate(begin(green), end(green), 0);
int sumofred = std::accumulate(begin(red), end(red), 0);


问:
Automatic disk check
Ubuntu sometimes want to work automatic disk check and waiting press a key from me. But my computer is far away and hasn't a keyboard. I want to check automatic disk check without pressing a key. I'm using ubuntu 10.04. I know ubuntu does a disk check on every ~20 boots.  It is not a problem for me. My problem is waiting press a key from me for disk check. And so system is not booting until press a key.</p>

答: You can set FSCKFIX=yes</p>

ContentLicense: CC BY-SA 3.0

Title: Automatic disk check

Body: You can set FSCKFIX=yes


问:
Error while unzipping a file in shell script. - need PK compat. v5.1 (can do v4.6)
I'm using unzip test.zip in a Shell script. But while executing this line i get an error

```<code>Archive:  test.zip
   skipping: hello.pdf                need PK compat. v5.1 (can do v4.6)
</code>```

Even if i try to run this single command from the terminal in ubuntu it throws the same error need PK compat. v5.1 (can do v4.6)

Uninstalling and reinstalling unzip also didn't work. Alternately I had to install p7zip-full to unzip the test.zip file. How to fix this and use unzip in the shell script??

答:
You need install 7z

Search the package

$ apt search p7zip
....
....

p7zip/focal,now 16.02+dfsg-7build1 amd64 [已安装]
  7zr file archiver with high compression ratio

p7zip-full/focal 16.02+dfsg-7build1 amd64
  7z and 7za file archivers with high compression ratio
...```

You can see the p7zip-full/focal 16.02+dfsg-7build1 amd64 is the currect one

$ sudo apt install p7zip-full, now you can run 7z command,for help 7z --help

Decompress file with
7z x test.zip -p****
-p Switches doesn't have write if the file has no password

Body:
I'm using unzip test.zip in a Shell script. But while executing this line i get an error

Archive:  test.zip
   skipping: hello.pdf                need PK compat. v5.1 (can do v4.6)

Even if i try to run this single command from the terminal in ubuntu it throws the same error need PK compat. v5.1 (can do v4.6)

Uninstalling and reinstalling unzip also didn't work. Alternately I had to install p7zip-full to unzip the test.zip file. How to fix this and use unzip in the shell script??

Body:
You need install 7z

Search the package

$ apt search p7zip
....
....

p7zip/focal,now 16.02+dfsg-7build1 amd64 [已安装]
  7zr file archiver with high compression ratio

p7zip-full/focal 16.02+dfsg-7build1 amd64
  7z and 7za file archivers with high compression ratio
...

You can see the p7zip-full/focal 16.02+dfsg-7build1 amd64 is the currect one

$ sudo apt install p7zip-full, now you can run 7z command,for help 7z --help

Decompress file with
7z x test.zip -p****
-p Switches doesn't have write if the file has no password


问:
slice() on a long skinny list with multiple entries
I have a data frame in R which is comprised like this:

year
region
age
population_count
cumulative_count*
middle_value*

2001
Region x
0
10
10
50

2001
Region x
1
10
20
50

2001
Region x
2
10
30
50

2001
Region x
3
10
40
50

2001
Region x
4
10
50
50

2001
Region x
5
10
60
50

...2020
Region y
1
10
20
50

For each year and region combination I have a discrete cumulative_count (derived from population_count by age) and middle_value (derived from the cumulative_count), again discrete for each year and region combination.

I want to extract from this the row for each region and year combination where the cumulative_count is closest to the middle_value in each instance.
(in the example above this would be age 4 in region x where culmulative_count = 50 and middle_value=50).

I have tried slice from dplyr:

slice(which.min(abs(table$cumulative_count - table$middle_value)))

but this only returns the first instance of the row where there is a match, not all the subsequent year and region combinations.

group_by(year,region) doesn't return all the possible year and region combinations either.

I feel I should be looping through the data frame for all possible year and region combinations and then slicing out the rows that meet the criteria.

Any thoughts?

UPDATE
I used @Merijn van Tilborg dplyr approach, needed only the first match.

Here's a screenshot of the output table - note that variable column is the single year of age and is getting older.

答:
I suggest to use rank as it ranks from low to high. So if you rank on the absolute difference your grouped ranks are per definition 1 for the smallest difference. You can simply filter on that value. It also allows to set the ties with tie.methods.

include ties

```<code>dat %>%
  group_by(year, region) %>%
  filter(rank(abs(cumulative_count - middle_value), ties.method = "min") == 1)

# # A tibble: 6 x 6
# # Groups:   year, region [4]
#    year region     age population_count cumulative_count middle_value
#   <int> <chr>    <int>            <int>            <int>        <int>
# 1  2001 Region x     2               10               30           50
# 2  2002 Region x     2               10               30           50
# 3  2001 Region y     2               10               30           50
# 4  2002 Region y     0               10               30           50
# 5  2002 Region y     1               10               30           50
# 6  2002 Region y     2               10               30           50
</code>```

show first one only

```<code>dat %>%
  group_by(year, region) %>%
  filter(rank(abs(cumulative_count - middle_value), ties.method = "first") == 1)

# # A tibble: 4 x 6
# # Groups:   year, region [4]
#    year region     age population_count cumulative_count middle_value
#   <int> <chr>    <int>            <int>            <int>        <int>
# 1  2001 Region x     2               10               30           50
# 2  2002 Region x     2               10               30           50
# 3  2001 Region y     2               10               30           50
# 4  2002 Region y     0               10               30           50
</code>```

other options include: rank(x, na.last = TRUE, ties.method = c("average", "first", "last", "random", "max", "min"))

using data.table instead of dplyr

```<code>library(data.table)
setDT(dat) # make dat a data.table

dat[, .SD[rank(abs(cumulative_count - middle_value), ties.method = "min") == 1], by = c("year", "region")]
</code>```

data

```<code>dat <- structure(list(year = c(2001L, 2001L, 2001L, 2002L, 2002L, 2002L,
2001L, 2001L, 2001L, 2002L, 2002L, 2002L), region = c("Region x",
"Region x", "Region x", "Region x", "Region x", "Region x", "Region y",
"Region y", "Region y", "Region y", "Region y", "Region y"),
    age = c(0L, 1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L),
    population_count = c(10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
    10L, 10L, 10L, 10L), cumulative_count = c(10L, 20L, 30L,
    10L, 20L, 30L, 10L, 20L, 30L, 30L, 30L, 30L), middle_value = c(50L,
    50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L)), class = "data.frame", row.names = c(NA,
-12L))
</code>```

Body:
I suggest to use rank as it ranks from low to high. So if you rank on the absolute difference your grouped ranks are per definition 1 for the smallest difference. You can simply filter on that value. It also allows to set the ties with tie.methods.

include ties

dat %>%
  group_by(year, region) %>%
  filter(rank(abs(cumulative_count - middle_value), ties.method = "min") == 1)

# # A tibble: 6 x 6
# # Groups:   year, region [4]
#    year region     age population_count cumulative_count middle_value
#   <int> <chr>    <int>            <int>            <int>        <int>
# 1  2001 Region x     2               10               30           50
# 2  2002 Region x     2               10               30           50
# 3  2001 Region y     2               10               30           50
# 4  2002 Region y     0               10               30           50
# 5  2002 Region y     1               10               30           50
# 6  2002 Region y     2               10               30           50

show first one only

dat %>%
  group_by(year, region) %>%
  filter(rank(abs(cumulative_count - middle_value), ties.method = "first") == 1)

# # A tibble: 4 x 6
# # Groups:   year, region [4]
#    year region     age population_count cumulative_count middle_value
#   <int> <chr>    <int>            <int>            <int>        <int>
# 1  2001 Region x     2               10               30           50
# 2  2002 Region x     2               10               30           50
# 3  2001 Region y     2               10               30           50
# 4  2002 Region y     0               10               30           50

other options include: rank(x, na.last = TRUE, ties.method = c("average", "first", "last", "random", "max", "min"))

using data.table instead of dplyr

library(data.table)
setDT(dat) # make dat a data.table

dat[, .SD[rank(abs(cumulative_count - middle_value), ties.method = "min") == 1], by = c("year", "region")]

data

dat <- structure(list(year = c(2001L, 2001L, 2001L, 2002L, 2002L, 2002L,
2001L, 2001L, 2001L, 2002L, 2002L, 2002L), region = c("Region x",
"Region x", "Region x", "Region x", "Region x", "Region x", "Region y",
"Region y", "Region y", "Region y", "Region y", "Region y"),
    age = c(0L, 1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L),
    population_count = c(10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
    10L, 10L, 10L, 10L), cumulative_count = c(10L, 20L, 30L,
    10L, 20L, 30L, 10L, 20L, 30L, 30L, 30L, 30L), middle_value = c(50L,
    50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L)), class = "data.frame", row.names = c(NA,
-12L))


问:
Update SVG progress circle by clicking checkboxes
I have 5 checkboxes representing a To-Do list, for every checkbox I click, the circle's diameter should complete 1/5, 2/5 , 3/5, 4/5, 5/5 until it completes the 5 checkboxes, the order of how the checkboxes are created shouldn't matter. If I clicked "first ToDo" and "third ToDo" without selecting "second ToDo" the circle should still show 2/5 of itself.

So far I've been able to make the circle interact with the input of the checkboxes, but I'm struggling to make the visual progress happen, when I click one of the ToDos the progress circle it's marked but not in the right order and portions, also the idea is that the visual progress should move forward to the right until completing the circle.

Looking for information online, I see people uses <circle path>but it is really confusing for me because some configurations are made through CSS while other people do it in the JS, according to me it is best that I use JS to show the progress, because it should behave in base of the checkboxes.

function update() {

  var myBar = document.getElementById("myCircle");
  //Reference the Form.
  var toDo = document.getElementById("toDo");

  //Reference all the CheckBoxes in Table.
  boxes = toDo.querySelectorAll("input[type='checkbox']:checked");
  checked = boxes.length

  myBar.style.strokeDasharray = ((checked) * 100) + "%";
  if (checked === 0) {
    alert("Please select CheckBox(s).");
  }
  return true;
}

checks = document.querySelectorAll("input[type='checkbox']");
checks.forEach(function(box) {
  box.addEventListener("change", function() {
    update()
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myCircle {
  width: 0;
  height: 30px;
  stroke: #A3BBAD;
  stroke-width: 3px;
}

#myProgress {
  margin: auto;
  width: 50%;
  stroke: #357266;
  stroke-width: 3px;
}</code>```

<svg height="100" width="100">
  <circle id="myProgress" cx="50" cy="50" r="40" fill="transparent"/>
  <circle id="myCircle" cx="50" cy="50" r="40" fill="transparent"/>
</svg>

<form id="toDo">
  <input id="FirstToDo" type="checkbox" value="1" />First
  <input id="SecondToDo" type="checkbox" value="2" />Second
  <input id="ThirdToDo" type="checkbox" value="3" />Third
  <input id="FourthToDo" type="checkbox" value="4" />Fourth
  <input id="FifthToDo" type="checkbox" value="5" />Fifth
</form>
```

答:
Here is a CSS-only solution. For that the inputboxes must come above the circle in the markup and I added some layout hack, but you can adjust it with JS and keep the original markup.

The code uses a conic-gradient based on the sum of 5 CSS variables, which values are controlled by the checkboxes. Again this can be done via JS too if more flexibility is needed. The key point is coloring an area whose angle is based on a sum, rather than coloring 5 predefined areas.

#myProgress {
  --task1: 0;
  --task2: 0;
  --task3: 0;
  --task4: 0;
  --task5: 0;
}

#FirstToDo:checked ~ #myProgress {
  --task1: 1;
}

#SecondToDo:checked ~ #myProgress {
  --task2: 1;
}

#ThirdToDo:checked ~ #myProgress {
  --task3: 1;
}

#FourthToDo:checked ~ #myProgress {
  --task4: 1;
}

#FifthToDo:checked ~ #myProgress {
  --task5: 1;
}

.flex {
  display: flex;
  flex-direction: row;
}

.circle {
  order: -1;
  width: 100px;
  height: 100px;
  background: blue;
  border-radius: 50%;
  mask: radial-gradient(farthest-side, transparent 0 70%, #fff 70% 100%);
  -webkit-mask: radial-gradient(farthest-side, transparent 0 70%, #fff 70% 100%);
}

#myProgress {
  background-image: conic-gradient(
    green 0 calc((var(--task1) + var(--task2) + var(--task3) + var(--task4) + var(--task5))* 20%),
    transparent 0 100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex">
    <input id="FirstToDo" type="checkbox" value="1" /><label for="FirstToDo">First</label>
    <input id="SecondToDo" type="checkbox" value="2" /><label for="SecondToDo">Second</label>
    <input id="ThirdToDo" type="checkbox" value="3" /><label for="ThirdToDo">Third</label>
    <input id="FourthToDo" type="checkbox" value="4" /><label for="FourthToDo">Fourth</label>
    <input id="FifthToDo" type="checkbox" value="5" /><label for="FifthToDo">Fifth</label>

  <div id="myProgress" class="circle"></div>
</div></code>```

Body:
I have 5 checkboxes representing a To-Do list, for every checkbox I click, the circle's diameter should complete 1/5, 2/5 , 3/5, 4/5, 5/5 until it completes the 5 checkboxes, the order of how the checkboxes are created shouldn't matter. If I clicked "first ToDo" and "third ToDo" without selecting "second ToDo" the circle should still show 2/5 of itself.

So far I've been able to make the circle interact with the input of the checkboxes, but I'm struggling to make the visual progress happen, when I click one of the ToDos the progress circle it's marked but not in the right order and portions, also the idea is that the visual progress should move forward to the right until completing the circle.

Looking for information online, I see people uses <circle path>but it is really confusing for me because some configurations are made through CSS while other people do it in the JS, according to me it is best that I use JS to show the progress, because it should behave in base of the checkboxes.

function update() {

  var myBar = document.getElementById("myCircle");
  //Reference the Form.
  var toDo = document.getElementById("toDo");

  //Reference all the CheckBoxes in Table.
  boxes = toDo.querySelectorAll("input[type='checkbox']:checked");
  checked = boxes.length

  myBar.style.strokeDasharray = ((checked) * 100) + "%";
  if (checked === 0) {
    alert("Please select CheckBox(s).");
  }
  return true;
}

checks = document.querySelectorAll("input[type='checkbox']");
checks.forEach(function(box) {
  box.addEventListener("change", function() {
    update()
  });
});

#myCircle {
  width: 0;
  height: 30px;
  stroke: #A3BBAD;
  stroke-width: 3px;
}

#myProgress {
  margin: auto;
  width: 50%;
  stroke: #357266;
  stroke-width: 3px;
}

<svg height="100" width="100">
  <circle id="myProgress" cx="50" cy="50" r="40" fill="transparent"/>
  <circle id="myCircle" cx="50" cy="50" r="40" fill="transparent"/>
</svg>

<form id="toDo">
  <input id="FirstToDo" type="checkbox" value="1" />First
  <input id="SecondToDo" type="checkbox" value="2" />Second
  <input id="ThirdToDo" type="checkbox" value="3" />Third
  <input id="FourthToDo" type="checkbox" value="4" />Fourth
  <input id="FifthToDo" type="checkbox" value="5" />Fifth
</form>

Body:
Here is a CSS-only solution. For that the inputboxes must come above the circle in the markup and I added some layout hack, but you can adjust it with JS and keep the original markup.

The code uses a conic-gradient based on the sum of 5 CSS variables, which values are controlled by the checkboxes. Again this can be done via JS too if more flexibility is needed. The key point is coloring an area whose angle is based on a sum, rather than coloring 5 predefined areas.

#myProgress {
  --task1: 0;
  --task2: 0;
  --task3: 0;
  --task4: 0;
  --task5: 0;
}

#FirstToDo:checked ~ #myProgress {
  --task1: 1;
}

#SecondToDo:checked ~ #myProgress {
  --task2: 1;
}

#ThirdToDo:checked ~ #myProgress {
  --task3: 1;
}

#FourthToDo:checked ~ #myProgress {
  --task4: 1;
}

#FifthToDo:checked ~ #myProgress {
  --task5: 1;
}

.flex {
  display: flex;
  flex-direction: row;
}

.circle {
  order: -1;
  width: 100px;
  height: 100px;
  background: blue;
  border-radius: 50%;
  mask: radial-gradient(farthest-side, transparent 0 70%, #fff 70% 100%);
  -webkit-mask: radial-gradient(farthest-side, transparent 0 70%, #fff 70% 100%);
}

#myProgress {
  background-image: conic-gradient(
    green 0 calc((var(--task1) + var(--task2) + var(--task3) + var(--task4) + var(--task5))* 20%),
    transparent 0 100%);
}

<div class="flex">
    <input id="FirstToDo" type="checkbox" value="1" /><label for="FirstToDo">First</label>
    <input id="SecondToDo" type="checkbox" value="2" /><label for="SecondToDo">Second</label>
    <input id="ThirdToDo" type="checkbox" value="3" /><label for="ThirdToDo">Third</label>
    <input id="FourthToDo" type="checkbox" value="4" /><label for="FourthToDo">Fourth</label>
    <input id="FifthToDo" type="checkbox" value="5" /><label for="FifthToDo">Fifth</label>

  <div id="myProgress" class="circle"></div>
</div>


问:
Vue i18n format USD currency
When I display my currency in USD the output is always in the format
USD$500.00.

I am trying to remove the USD prefix from the start.

This is my numberFormats config:

```<code>numberFormats: {
    'en': {
        currency: {
            style: 'currency', currency: 'GBP'
        }
    },
    'us': {
        currency: {
            style: 'currency',
            currency: 'USD',
            currencyDisplay: 'symbol'
        }
    }
}
</code>```

I display the currency by doing {{ $n(500, 'currency') }}.

答:
Change symbole by narrowSymbol like this :</p>
```<code>numberFormats: {
    'en': {
        currency: {
            style: 'currency', currency: 'GBP'
        }
    },
    'us': {
        currency: {
            style: 'currency',
            currency: 'USD',
            currencyDisplay: 'narrowSymbol'
        }
    }
}
</code>```

Title: Vue i18n format USD currency

Body:
When I display my currency in USD the output is always in the format
USD$500.00.

I am trying to remove the USD prefix from the start.

This is my numberFormats config:

numberFormats: {
    'en': {
        currency: {
            style: 'currency', currency: 'GBP'
        }
    },
    'us': {
        currency: {
            style: 'currency',
            currency: 'USD',
            currencyDisplay: 'symbol'
        }
    }
}

I display the currency by doing {{ $n(500, 'currency') }}.

Body:
Change symbole by narrowSymbol like this :

numberFormats: {
    'en': {
        currency: {
            style: 'currency', currency: 'GBP'
        }
    },
    'us': {
        currency: {
            style: 'currency',
            currency: 'USD',
            currencyDisplay: 'narrowSymbol'
        }
    }
}


问:
Return keys whose values are true from a Json Object using java
From below json object , I want to return(/or add the keys to a Set) whose values are true.

```<code>  {
    "create": true,
    "read": false,
    "update": true,
    "delete": false
  }
</code>```

I want an output like below

[ create, update ]
Could some one help me with this?

Update :

I was trying as shown below to capture all the values that are true , but I think my Java 8 filter criteria is wrong.

```<code>
Map<String, Object> mapping = new ObjectMapper().readValue(permissionStr, HashMap.class);
mySet = mapping.entrySet().stream().filter(x->x.getValue().equals(Boolean.TRUE)).map(Map.Entry::getKey)
                    .collect(Collectors.toSet());
</code>```

答:
```<code>List<String> list;
String VariableName = JSONObjectName.getString("Create");
if(VariableName.equals("true")){
    list.add(VariableName);
}
</code>```

Body:
From below json object , I want to return(/or add the keys to a Set) whose values are true.

  {
    "create": true,
    "read": false,
    "update": true,
    "delete": false
  }

I want an output like below

[ create, update ]
Could some one help me with this?

Update :

I was trying as shown below to capture all the values that are true , but I think my Java 8 filter criteria is wrong.

Map<String, Object> mapping = new ObjectMapper().readValue(permissionStr, HashMap.class);
mySet = mapping.entrySet().stream().filter(x->x.getValue().equals(Boolean.TRUE)).map(Map.Entry::getKey)
                    .collect(Collectors.toSet());


问:
ResponseEntity in Optional as ok or noContent, depending if present
Im currently returning my content in this way:

```<code>Optional<String> data = Optional.of("bla");
Optional<ResponseEntity<?>> response = data.map(ResponseEntity::ok);
return response.orElse(ResponseEntity::noContent);
</code>```

is there a way to combine the map with the orElse without saving them into a variable first?

(something like this, but without the cast problems)

```<code>Optional<String> data = Optional.of("bla");
return data.map(ResponseEntity::ok) // Type: ResponseEntity<String>
  .orElse(ResponseEntity::noContent); // Type: ResponseEntity<?> => Cast Error
</code>```

This is a similar problem to

```<code>Optional.of<Object>("bla").orElse(2);
</code>```

but I don't know how how to do this with a map

```<code>Optional.of("bla")
        .<ResponseEntity<?>>map(ResponseEntity::ok)
        .orElse(ResponseEntity::noContent);
</code>```

does not work

答: return data.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.noContent().build());</p>

Body:
Im currently returning my content in this way:

Optional<String> data = Optional.of("bla");
Optional<ResponseEntity<?>> response = data.map(ResponseEntity::ok);
return response.orElse(ResponseEntity::noContent);

is there a way to combine the map with the orElse without saving them into a variable first?

(something like this, but without the cast problems)

Optional<String> data = Optional.of("bla");
return data.map(ResponseEntity::ok) // Type: ResponseEntity<String>
  .orElse(ResponseEntity::noContent); // Type: ResponseEntity<?> => Cast Error

This is a similar problem to

Optional.of<Object>("bla").orElse(2);

but I don't know how how to do this with a map

Optional.of("bla")
        .<ResponseEntity<?>>map(ResponseEntity::ok)
        .orElse(ResponseEntity::noContent);

does not work


问:
How does a node point to the next?
In a linked list implementation in python, we do something like:

first_node.next = second_node
```

Now here, second_node is an object of class create_node(). However, first_node.next is one of the arguments of this class.

Now with above mentioned line of code, are we just assigning the object, second_node to the attribute first_node.next or are we pointing the address of the second_node object to the first_node.next attribute?

It's confusing me. How does it work?

答:
When this code executes:

```<code>first_node.next = second_node
</code>```

...then first_node.next (which is an attribute of first_node) will reference the same node as second_node.

I'll assume this code as context:

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

first_node = Node(10)
second_node = Node(20)
first_node.next = second_node
```
<p>NB: It would be strange to call the class <code>create_node</code>. It is not common practice to use a verb here. Classes do more than just create things, so just name it by the instance you get from them, and use PascalCase. So <code>Node</code>.</p>
<p>Now to what this code does. It may help to visualise it.</p>
<ol>
<li><p>Create <code>first_node</code></p>
<pre class="lang-py prettyprint-override"><code>first_node = Node(10)
</code>```

 first_node
    ↓
┌────────────┐
│ value: 10  │
│ next: None │
└────────────┘
```
</li>
<li><p>Create <code>second_node</code></p>
<pre class="lang-py prettyprint-override"><code>second_node = Node(20)
</code>```

 first_node              second_node
    ↓                        ↓
┌────────────┐           ┌────────────┐
│ value: 10  │           │ value: 20  │
│ next: None │           │ next: None │
└────────────┘           └────────────┘
```
</li>
<li><p>Link the first to the second</p>
<pre class="lang-py prettyprint-override"><code>first_node.next = second_node
</code>```

 first_node              second_node
    ↓                        ↓
┌────────────┐           ┌────────────┐
│ value: 10  │           │ value: 20  │
│ next: ───────────────► │ next: None │
└────────────┘           └────────────┘
```

Title: How does a node point to the next?

Body:
In a linked list implementation in python, we do something like:

first_node.next = second_node

Now here, second_node is an object of class create_node(). However, first_node.next is one of the arguments of this class.

Now with above mentioned line of code, are we just assigning the object, second_node to the attribute first_node.next or are we pointing the address of the second_node object to the first_node.next attribute?

It's confusing me. How does it work?

Body:
When this code executes:

first_node.next = second_node

...then first_node.next (which is an attribute of first_node) will reference the same node as second_node.

I'll assume this code as context:

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

first_node = Node(10)
second_node = Node(20)
first_node.next = second_node

NB: It would be strange to call the class create_node. It is not common practice to use a verb here. Classes do more than just create things, so just name it by the instance you get from them, and use PascalCase. So Node.

Now to what this code does. It may help to visualise it.

Create first_node

first_node = Node(10)

 first_node
    ↓
┌────────────┐
│ value: 10  │
│ next: None │
└────────────┘

Create second_node

second_node = Node(20)

 first_node              second_node
    ↓                        ↓
┌────────────┐           ┌────────────┐
│ value: 10  │           │ value: 20  │
│ next: None │           │ next: None │
└────────────┘           └────────────┘

Link the first to the second

first_node.next = second_node

 first_node              second_node
    ↓                        ↓
┌────────────┐           ┌────────────┐
│ value: 10  │           │ value: 20  │
│ next: ───────────────► │ next: None │
└────────────┘           └────────────┘


问:
Problem with Multigradient brush implementation from scatch in C++ and GDI
I am trying to implement a gradient brush from scratch in C++ with GDI. I don't want to use GDI+ or any other graphics framework. I want the gradient to be of any direction (arbitrary angle).

My algorithm in pseudocode:

```<code>      For each pixel in x dirrection
      For each pixel in the y direction
          current position = current pixel - centre                      //translate origin
          rotate this pixel according to the given angle
          scalingFactor =( rotated pixel + centre ) / extentDistance    //translate origin back
          rgbColor = startColor + scalingFactor(endColor - startColor)
</code>```

extentDistance is the length of the line passing from the centre of the rectangle and has gradient equal to the angle of the gradient

Ok so far so good. I can draw this and it looks nice. BUT unfortunately because of the rotation bit the rectangle corners have the wrong color. The result is perfect only for angle which are multiples of 90 degrees. The problem appears to be that the scaling factor doesn't scale over the entire size of the rectangle.

I am not sure if you got my point cz it's really hard to explain my problem without a visualisation of it.

If anyone can help or redirect me to some helpful material I'd be grateful.

答:
Ok guys fixed it. Apparently the problem was that when I was rotating the gradient fill (not the rectangle) I wasn't calculating the scaling factor correctly. The distance over which the gradient is scaled changes according to the gradient direction. What must be done is to find where the edge points of the rect end up after the rotation and based on that you can find the distance over which the gradient should be scaled. So basically what needs to be corrected in my algorithm is the extentDistance.

How to do it:

•Transform the coordinates of all four corners

•Find the smallest of all four x's as minX

•Find the largest of all four x's and call it maxX

•Do the same for y's.

•The distance between these two point (max and min) is the extentDistance

Body:
I am trying to implement a gradient brush from scratch in C++ with GDI. I don't want to use GDI+ or any other graphics framework. I want the gradient to be of any direction (arbitrary angle).

My algorithm in pseudocode:

      For each pixel in x dirrection
      For each pixel in the y direction
          current position = current pixel - centre                      //translate origin
          rotate this pixel according to the given angle
          scalingFactor =( rotated pixel + centre ) / extentDistance    //translate origin back
          rgbColor = startColor + scalingFactor(endColor - startColor)

extentDistance is the length of the line passing from the centre of the rectangle and has gradient equal to the angle of the gradient

Ok so far so good. I can draw this and it looks nice. BUT unfortunately because of the rotation bit the rectangle corners have the wrong color. The result is perfect only for angle which are multiples of 90 degrees. The problem appears to be that the scaling factor doesn't scale over the entire size of the rectangle.

I am not sure if you got my point cz it's really hard to explain my problem without a visualisation of it.

If anyone can help or redirect me to some helpful material I'd be grateful.


问:
How can I plot "Arrival time" in my Shiny app? There are duplicates of each "Id" and "Arrival time"
I have chosen to use a long dataset for the plot. The variable "Arrival Time" means when somebody arrives at work. The variable "Mode" means the preferred mode of transport. However, the preferred mode of transport can be more than one. For example, some participants have chosen "Yes" to both "Car" and "Bicycle".

I need to plot the "Arrival time", which should be unique for every value of "Id".

I need to be able to filter the different modes of transport in my sidebarPanel.

I need to be able to choose all modes of transport

```<code>library(shiny)
library(ggplot2)
library(dplyr)
library(tidyverse)
library(readxl)
library(dplyr)
library(do)
library(shinyWidgets)

#1. READ DATA FROM EXCEL
Survey <- read_excel("~/EIGSI/Project/Work files for R studio/06_Participant.xlsx")

#2.SUBSET DATA
Data <- subset(Survey, select = c(1,3,5:14))

colnames(Data) <- c(
  'Id',
  'Arrival time',
  'On foot',
  'Bicycle',
  'Bicycle (Yélo)',
  'Motorcycle/scooter',
  'Scooter (trotinette)',
  'Bus',
  'Train',
  'Car',
  'Carpool',
  'Car (Yélo)'
)

#3.GATHER DATA FOR LONG TABLE
Data <- Data %>%
  gather(key = "Mode",
         value = "Answer",
         -Id, -`Arrival time`)

#4. OPTIONAL: ORDER THE X-AXIS OF THE PLOT
Data$`Arrival time` = ordered(Data$`Arrival time`, levels = c(
  "before 7h00",
  "7h00 - 7h30",
  "7h30 - 8h00",
  "8h00 - 8h30",
  "8h30 - 9h00",
  "9h00 - 9h30",
  "after 9h30"

))

#5. MAKE VECTOR OF CHOICES
a <- c(unique(Data$Mode))

#6. CONFIGURE THE SHINY APPLICATION
ui <- fluidPage(
  titlePanel("Arrival times"),  # Add a title panel
  sidebarLayout(
    position = "right",

    sidebarPanel(h3("Inputs for histogram"),
                 pickerInput("Mode", "Select mode", choices = a, options = list(`actions-box` = TRUE),multiple = T),
                 br()
    ),

    # Inside the sidebarLayout, add a sidebarPanel
    mainPanel(
      plotOutput("myhist")

    )
  )
)

# server.R ----
server <- function(input, output) {

  output$myhist <- renderPlot({

    observe({
      print(input$Mode) #ENABLES ME TO CHOOSE ALL VARIABLES
    })

  Data %>%
      ggplot(aes(x=`Arrival time`))+
      geom_histogram(stat = "count", data = Data[Data$Mode==input$Mode ,])

  })

}

# Run the app ----
shinyApp(ui = ui, server = server)
</code>```

This is an example of the dataset called Data, I show it using the dput() function:

```<code>     structure(list(Id = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4), `Arrival time` = structure(c(3L,
6L, 4L, 5L, 3L, 6L, 4L, 5L, 3L, 6L, 4L, 5L), .Label = c("before 7h00",
"7h00 - 7h30", "7h30 - 8h00", "8h00 - 8h30", "8h30 - 9h00", "9h00 - 9h30",
"after 9h30"), class = c("ordered", "factor")), Mode = c("On foot",
"On foot", "On foot", "On foot", "Scooter (trotinette)", "Scooter (trotinette)",
"Scooter (trotinette)", "Scooter (trotinette)", "Carpool", "Carpool",
"Carpool", "Carpool"), Answer = c("Yes", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No")), row.names = c(1L,
2L, 3L, 4L, 9157L, 9158L, 9159L, 9160L, 18313L, 18314L, 18315L,
18316L), class = "data.frame")
</code>```

答:
So just to clarify: What you want to do is first select the rows where the mode is one of the chosen modes and the answer is yes, and then plot the arrival times of those rows.

First, you can subset the dataset so it's only the modes you want and the answers "Yes". Now you have only the rows you want, but like you pointed out, some rows are duplicated.

Next, you drop the Mode and Answer columns and set Data to unique(Data). Dropping those two columns means you only have the ID and Arrival Time columns, and running the unique() will drop the duplicate rows and leave you with one row per ID (assuming each ID only has one arrival time).

One note, in your filter, you do this: data = Data[Data$Mode==input$Mode

This is not what you want because of two reasons:

It will take all rows that have the input Mode, even if the answer is No. You want to add an additional filter that the answer has to be Yes.

It will not work with multiple selections. Instead of ==, use %in%. This way, even if there are multiple selections, the filter will still work.

Body:
I have chosen to use a long dataset for the plot. The variable "Arrival Time" means when somebody arrives at work. The variable "Mode" means the preferred mode of transport. However, the preferred mode of transport can be more than one. For example, some participants have chosen "Yes" to both "Car" and "Bicycle".

I need to plot the "Arrival time", which should be unique for every value of "Id".

I need to be able to filter the different modes of transport in my sidebarPanel.

I need to be able to choose all modes of transport

library(shiny)
library(ggplot2)
library(dplyr)
library(tidyverse)
library(readxl)
library(dplyr)
library(do)
library(shinyWidgets)

#1. READ DATA FROM EXCEL
Survey <- read_excel("~/EIGSI/Project/Work files for R studio/06_Participant.xlsx")

#2.SUBSET DATA
Data <- subset(Survey, select = c(1,3,5:14))

colnames(Data) <- c(
  'Id',
  'Arrival time',
  'On foot',
  'Bicycle',
  'Bicycle (Yélo)',
  'Motorcycle/scooter',
  'Scooter (trotinette)',
  'Bus',
  'Train',
  'Car',
  'Carpool',
  'Car (Yélo)'
)

#3.GATHER DATA FOR LONG TABLE
Data <- Data %>%
  gather(key = "Mode",
         value = "Answer",
         -Id, -`Arrival time`)

#4. OPTIONAL: ORDER THE X-AXIS OF THE PLOT
Data$`Arrival time` = ordered(Data$`Arrival time`, levels = c(
  "before 7h00",
  "7h00 - 7h30",
  "7h30 - 8h00",
  "8h00 - 8h30",
  "8h30 - 9h00",
  "9h00 - 9h30",
  "after 9h30"

))

#5. MAKE VECTOR OF CHOICES
a <- c(unique(Data$Mode))

#6. CONFIGURE THE SHINY APPLICATION
ui <- fluidPage(
  titlePanel("Arrival times"),  # Add a title panel
  sidebarLayout(
    position = "right",

    sidebarPanel(h3("Inputs for histogram"),
                 pickerInput("Mode", "Select mode", choices = a, options = list(`actions-box` = TRUE),multiple = T),
                 br()
    ),

    # Inside the sidebarLayout, add a sidebarPanel
    mainPanel(
      plotOutput("myhist")

    )
  )
)

# server.R ----
server <- function(input, output) {

  output$myhist <- renderPlot({

    observe({
      print(input$Mode) #ENABLES ME TO CHOOSE ALL VARIABLES
    })

  Data %>%
      ggplot(aes(x=`Arrival time`))+
      geom_histogram(stat = "count", data = Data[Data$Mode==input$Mode ,])

  })

}

# Run the app ----
shinyApp(ui = ui, server = server)

This is an example of the dataset called Data, I show it using the dput() function:

     structure(list(Id = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4), `Arrival time` = structure(c(3L,
6L, 4L, 5L, 3L, 6L, 4L, 5L, 3L, 6L, 4L, 5L), .Label = c("before 7h00",
"7h00 - 7h30", "7h30 - 8h00", "8h00 - 8h30", "8h30 - 9h00", "9h00 - 9h30",
"after 9h30"), class = c("ordered", "factor")), Mode = c("On foot",
"On foot", "On foot", "On foot", "Scooter (trotinette)", "Scooter (trotinette)",
"Scooter (trotinette)", "Scooter (trotinette)", "Carpool", "Carpool",
"Carpool", "Carpool"), Answer = c("Yes", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No")), row.names = c(1L,
2L, 3L, 4L, 9157L, 9158L, 9159L, 9160L, 18313L, 18314L, 18315L,
18316L), class = "data.frame")


问:
How do PUT, POST or PATCH request differ ultimately?
The data, being sent over a PUT/PATCH/POST request, ultimately ends up in the database.

Now whether we are inserting a new resource or updating or modifying an existing one - it all depends upon the database operation being carried out.

Even if we send a POST and ultimately perform just an update in the database, it does not impact anywhere at all, isn't it?!

Hence, do they actually differ - apart from a purely conceptual point of view?

答:
They are slightly different and they bind to different concepts of REST API (which is based on HTTP)

Just imagine that you have some Booking entity. And yo perform the following actions with resources:

POST - creates a new resource. And it is not idempotent - if you sent the same request twice -> two bookings will be stored. The third time - will create the third one. You are updating your DB with every request.

PUT - updates the full representation of a resource. It means - it replaces the booking full object with a new one. And it is idempotent - you could send a request ten times result will be the same (if a resource wasn't changed between your calls)

PATCH - updates some part of the resource. For example, your booking entity has a date property -> you update only this property. For example, replace the existing date with new date which is sent at the request.

However, for either of the above - who is deciding whether it is going to be a new resource creation or updating/modifying an existing one, it's the database operation or something equivalent to that which takes care of persistence

You are mixing different things.

The persistence layer and UI layer are two different things.

The general pattern used at Java - Model View Controller.

REST API has its own concept. And the DB layer has its own purpose. Keep in mind that separating the work of your application into layers is exactly high cohesion - when code is narrow-focused and does one thing and does it well.

Mainly at the answer, I posted some concepts for REST.

The main decision about what the application should do - create the new entity or update is a developer. And this kind of decision is usually done through the service layer. There are many additional factors that could be done, like transactions support, performing filtering of the data from DB, pagination, etc.

Also, it depends on how the DB layer is implemented. If JPA with HIbernate is used or with JDBC template, custom queries execution...


问:
event listener wait for action/callback
Is it possible to handle an event listener like a callback and wait for its action/return?

Here is the scenario, I load a page and call initialize() which renders a div and a button but keeps it hidden. Then I tap a icon which I then display the div and button to make it visible.

When I call showDivAndButton, I'm waiting on a Promise or callback for when someone clicks on the rendered button. In this case I'm waiting for the "whats up?"

```<code>initialize() {
  window.addEventListener('message', async (e) => { if(e.data === 'hello-world') { return "whats up?"; } });
  renderDivAndButton();
}

showDivAndButton() {
  divAndButton.setVisible(true);

  // wait for button to be pressed and return string
}

renderDivAndButton() {
  btn.onclick = { window.postMessage('hello-world', '*'); }
}
</code>```

maybe async showDivAndButton(): Promise<string> {} ?

then do something like let res = await showDivAndButton();

but it doesn't make sense

答:
You could absolutely write a function using async/await that waits for the message you've posted to be fired (which is triggered by the button). To do that you'll need to wrap your event listener in a promise, like this:

```<code>async function waitForMessage() {
   return new Promise((accept, reject) => {
      const handler = (event: MessageEvent) => {
         if(event.data === 'hello-world') {
            /**
             * This try catch is important if your handler
             * does something more complicated that might
             * throw an error. If you don't do this, your
             * awaiting function won't be able to catch that error
             */
            try {
               // More code
               accept("What's up?")
            } catch(error) {
               reject(error)
            }
         }
         window.removeEventListener('message', handler)
      }

      window.addEventListener('message', handler);
   });
}
</code>```

This function can now be awaited exactly as you intend:

```<code>const message = await waitForMessage()
console.log(message) // "What's up?"
</code>```

Title: event listener wait for action/callback

Body:
Is it possible to handle an event listener like a callback and wait for its action/return?

Here is the scenario, I load a page and call initialize() which renders a div and a button but keeps it hidden. Then I tap a icon which I then display the div and button to make it visible.

When I call showDivAndButton, I'm waiting on a Promise or callback for when someone clicks on the rendered button. In this case I'm waiting for the "whats up?"

initialize() {
  window.addEventListener('message', async (e) => { if(e.data === 'hello-world') { return "whats up?"; } });
  renderDivAndButton();
}

showDivAndButton() {
  divAndButton.setVisible(true);

  // wait for button to be pressed and return string
}

renderDivAndButton() {
  btn.onclick = { window.postMessage('hello-world', '*'); }
}

maybe async showDivAndButton(): Promise<string> {} ?

then do something like let res = await showDivAndButton();

but it doesn't make sense

Body:
You could absolutely write a function using async/await that waits for the message you've posted to be fired (which is triggered by the button). To do that you'll need to wrap your event listener in a promise, like this:

async function waitForMessage() {
   return new Promise((accept, reject) => {
      const handler = (event: MessageEvent) => {
         if(event.data === 'hello-world') {
            /**
             * This try catch is important if your handler
             * does something more complicated that might
             * throw an error. If you don't do this, your
             * awaiting function won't be able to catch that error
             */
            try {
               // More code
               accept("What's up?")
            } catch(error) {
               reject(error)
            }
         }
         window.removeEventListener('message', handler)
      }

      window.addEventListener('message', handler);
   });
}

This function can now be awaited exactly as you intend:

const message = await waitForMessage()
console.log(message) // "What's up?"


问:
Why can not separate text lines in Telegram?
I created an EA in MQL4 where I send a text to be displayed as 3 lines of text in Telegram where each line is ended with \n as follows:

```<code>message = "Line one\n" +
          "Line two\n" +
          "Line three";
</code>```

But somehow, the message are shown in Telegram as 1 single line, concatenating all the 3 lines.
I think \n is not recognized by Telegram. I am not sure what kind of characters should be used to create a line break.
Can anyone provide some help for me on how to separate each lines so it is shown neatly in Telegram message?

Thank you.

Alvin

答: Try adding \r\n to your text instead of just \n.

Body:
I created an EA in MQL4 where I send a text to be displayed as 3 lines of text in Telegram where each line is ended with \n as follows:

message = "Line one\n" +
          "Line two\n" +
          "Line three";

But somehow, the message are shown in Telegram as 1 single line, concatenating all the 3 lines.
I think \n is not recognized by Telegram. I am not sure what kind of characters should be used to create a line break.
Can anyone provide some help for me on how to separate each lines so it is shown neatly in Telegram message?

Thank you.

Alvin


问:
Trying to update my quantity of stock by updating the a value into my database that i got out earlier by using the ID
need to update my SQL database with new number but I cant seem to be able  to do so. I'm using python with SQLite I'm not really any good at SQL so any help would be appreciated. I couldn't find a way to update it straight away so I thought a work around would be to get the number from the database then turn it back into a string to be enter back in. I'm sure I'm making this more difficult then it needs to be ive been stuck for a long time and really just dont know what to do now</p>
```<code>def delete():
    #create a database or connect ot one
    conn = sqlite3.connect('Food_item.db')

    #create cursor
    c = conn.cursor()

    # Delete a record
    if (len(f_name_editor.get()) != None and len(l_name_editor.get()) == 0):
        print ("hello")
        c.execute("DELETE from FOOD WHERE oid= " + f_name_editor.get())

    elif (len(f_name_editor.get()) != None and len(l_name_editor.get()) != None):

        c.execute("SELECT QUANTITY FROM FOOD WHERE ADMIN_ID= "+ f_name_editor.get())
        record_id = f_name_editor.get()
        records = c.fetchone()[0]
        sub_num= l_name_editor.get()
        new_items= (records-int(sub_num))
        Removed_items =str(new_items)
        print(Removed_items)

        c.execute("UPDATE QUANTITY FROM FOOD  =" +Removed_items+" WHERE ADMIN_ID= "+f_name_editor.get())
</code>```

答:
The UPDATE SQL in your code is invalid, it should be:

c.execute('UPDATE FOOD SET QUANTITY = ? WHERE ADMIN_ID = ?',
          (Removed_items, f_name_editor.get()))
conn.commit()
```
<p>Better use placeholders to avoid SQL injection and you need to call <code>conn.commit()</code> to make the update effective.</p>
<hr />
<p>Note that if <code>l_name_editor.get()</code> is the amount to be deducted from <code>QUANTITY</code>, you don't need to get the current <code>QUANTITY</code>. Just use one <code>UPDATE</code> SQL as below:</p>
<pre class="lang-py prettyprint-override"><code>c.execute('UPDATE FOOD SET QUANTITY = QUANTITY - ? WHERE ADMIN_ID = ?',
          (l_name_editor.get(), f_name_editor.get()))
conn.commit()
</code>```

Body:
need to update my SQL database with new number but I cant seem to be able  to do so. I'm using python with SQLite I'm not really any good at SQL so any help would be appreciated. I couldn't find a way to update it straight away so I thought a work around would be to get the number from the database then turn it back into a string to be enter back in. I'm sure I'm making this more difficult then it needs to be ive been stuck for a long time and really just dont know what to do now

def delete():
    #create a database or connect ot one
    conn = sqlite3.connect('Food_item.db')

    #create cursor
    c = conn.cursor()

    # Delete a record
    if (len(f_name_editor.get()) != None and len(l_name_editor.get()) == 0):
        print ("hello")
        c.execute("DELETE from FOOD WHERE oid= " + f_name_editor.get())

    elif (len(f_name_editor.get()) != None and len(l_name_editor.get()) != None):

        c.execute("SELECT QUANTITY FROM FOOD WHERE ADMIN_ID= "+ f_name_editor.get())
        record_id = f_name_editor.get()
        records = c.fetchone()[0]
        sub_num= l_name_editor.get()
        new_items= (records-int(sub_num))
        Removed_items =str(new_items)
        print(Removed_items)

        c.execute("UPDATE QUANTITY FROM FOOD  =" +Removed_items+" WHERE ADMIN_ID= "+f_name_editor.get())

Body:
The UPDATE SQL in your code is invalid, it should be:

c.execute('UPDATE FOOD SET QUANTITY = ? WHERE ADMIN_ID = ?',
          (Removed_items, f_name_editor.get()))
conn.commit()

Better use placeholders to avoid SQL injection and you need to call conn.commit() to make the update effective.

Note that if l_name_editor.get() is the amount to be deducted from QUANTITY, you don't need to get the current QUANTITY. Just use one UPDATE SQL as below:

c.execute('UPDATE FOOD SET QUANTITY = QUANTITY - ? WHERE ADMIN_ID = ?',
          (l_name_editor.get(), f_name_editor.get()))
conn.commit()


问:
If else statement in cypress is not working-what is wrong with my code?
I am starting out with cypress automation testing tool.
What I am trying to accomplish:

if the page contains "there are no results" then "mark as certified" button should not exist.
else if the page does not contain "there are no results" then click the select all button."mark as certified" button should exist.

here is the code that I have so far:

```<code>cy.get('body').then($body=> {
        if ($body.find('There are no results')) {
            //cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0');
            cy.get('Mark as Certified').should('not.exist');
        }
        else {
            cy.get('input[id="selectAll"]').click();
            cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0').contains('Mark as Certified');
            cy.get('.hZDZBR').click();

        }
    })
</code>```

What cypress does right now is:
It enters the if loop, executes it and says "mark as certified" not found.
But my question is, if "there are no results" does not exist on the page, and it does not find it, then why does it even execute the if loop and go into the else loop?
So it is executing the if loop as though it finds "mark as certified" but I can see that that doesnt exist on the page.

Help is appreciated thanks!

So I updated the above code to:

```<code>       cy.wait(5000);
        if ($body.find('There are no results').length>0) {
            //cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0');
            cy.wait(5000);
            cy.get('Mark as Certified').should('not.exist');
            cy.get('input[id="selectAll"]').should('not.exist');
        }
        else if($body.find('There are no results').length==0) {

            cy.get('input[id="selectAll"]').click();
            cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0').contains('Mark as Certified');
            cy.get('.hZDZBR').click();

        }
    })````
Now the control goes to else loop and does not execute:
````cy.get('Mark as Certified').should('not.exist');
     cy.get('input[id="selectAll"]').should('not.exist');
</code>```

What is wrong with my code?

Hi,
I again edited my code with:

```<code>const $el=Cypress.$('.Typography__StyledTypography-sc-153d8g4-0 jhYDmS TrainingQueueListstyles__EmptyListMessage-sc-19yfim3-1 ihRiqU');
       if($el.length){
        cy.log($el.length);
        cy.get('Mark as Certified').should('not.exist');
       } else{
        cy.get('input[id="selectAll"]').click();
        cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0').contains('Mark as Certified');
        cy.get('.hZDZBR').click();
       }
</code>```

"There are no results" exists on the page but cypress still enters the else loop, I fail to understand why.
Also I am trying to log $el.length using cy.log($el.length) but I dont see it logging this value anywhere.

hi, this is the latest code edit I made ,but cypress shows this red mark under the = sign and says , expected "{", I am unable to understand why its expecting this here: Any ideas how I can resolve this?

```<code>javascript
const $el=Cypress.$([class='Typography__StyledTypography-sc-153d8g4-0.jhYDmS.TrainingQueueListstyles__EmptyListMessage-sc-19yfim3-1.ihRiqU']);
</code>```

答:
Using conditions like this in your code is not recommended. This will cause a test case to no longer be deterministic in the worst case.
I would recommend to write the two if/else cases in two different test cases and in there can clearly describe (maybe also with cypress networking) when it should come to which behaviour.

You can find more information here: https://docs.cypress.io/guides/core-concepts/conditional-testing#Client-side-rendering

Body:
I am starting out with cypress automation testing tool.
What I am trying to accomplish:

if the page contains "there are no results" then "mark as certified" button should not exist.
else if the page does not contain "there are no results" then click the select all button."mark as certified" button should exist.

here is the code that I have so far:

cy.get('body').then($body=> {
        if ($body.find('There are no results')) {
            //cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0');
            cy.get('Mark as Certified').should('not.exist');
        }
        else {
            cy.get('input[id="selectAll"]').click();
            cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0').contains('Mark as Certified');
            cy.get('.hZDZBR').click();

        }
    })

What cypress does right now is:
It enters the if loop, executes it and says "mark as certified" not found.
But my question is, if "there are no results" does not exist on the page, and it does not find it, then why does it even execute the if loop and go into the else loop?
So it is executing the if loop as though it finds "mark as certified" but I can see that that doesnt exist on the page.

Help is appreciated thanks!

So I updated the above code to:

       cy.wait(5000);
        if ($body.find('There are no results').length>0) {
            //cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0');
            cy.wait(5000);
            cy.get('Mark as Certified').should('not.exist');
            cy.get('input[id="selectAll"]').should('not.exist');
        }
        else if($body.find('There are no results').length==0) {

            cy.get('input[id="selectAll"]').click();
            cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0').contains('Mark as Certified');
            cy.get('.hZDZBR').click();

        }
    })````
Now the control goes to else loop and does not execute:
````cy.get('Mark as Certified').should('not.exist');
     cy.get('input[id="selectAll"]').should('not.exist');

What is wrong with my code?

Hi,
I again edited my code with:

const $el=Cypress.$('.Typography__StyledTypography-sc-153d8g4-0 jhYDmS TrainingQueueListstyles__EmptyListMessage-sc-19yfim3-1 ihRiqU');
       if($el.length){
        cy.log($el.length);
        cy.get('Mark as Certified').should('not.exist');
       } else{
        cy.get('input[id="selectAll"]').click();
        cy.get('.hZDZBR > .Typography__StyledTypography-sc-153d8g4-0').contains('Mark as Certified');
        cy.get('.hZDZBR').click();
       }

"There are no results" exists on the page but cypress still enters the else loop, I fail to understand why.
Also I am trying to log $el.length using cy.log($el.length) but I dont see it logging this value anywhere.

hi, this is the latest code edit I made ,but cypress shows this red mark under the = sign and says , expected "{", I am unable to understand why its expecting this here: Any ideas how I can resolve this?

javascript
const $el=Cypress.$([class='Typography__StyledTypography-sc-153d8g4-0.jhYDmS.TrainingQueueListstyles__EmptyListMessage-sc-19yfim3-1.ihRiqU']);


问:
In R how would you replace values in a matrix that have a certain condition with values from another vector?
I have a matrix and a vector like this:

```<code>Matrix<-cbind(c(3,3,5,1),c(2,5,2,1))
Vector<-c(2,3,3,3)
</code>```

I want to replace the Matrix elements that are >= the corresponding Vector value with the values in the Vector so that the Matrix would now look like this:

```<code>MatrixNew<-cbind(c(2,3,3,1),c(2,3,2,1))
</code>```

What logic would achieve this?

答:
Thought you had to use apply(Matrix, \(x) pmin(x, Vector)), but actually, you can just use pmin() directly on your Matrix because it will recycle the Vector to match the length.

pmin(Matrix, Vector)
#>      [,1] [,2]
#> [1,]    2    2
#> [2,]    3    3
#> [3,]    3    2
#> [4,]    1    1
```

Body:
I have a matrix and a vector like this:

Matrix<-cbind(c(3,3,5,1),c(2,5,2,1))
Vector<-c(2,3,3,3)

I want to replace the Matrix elements that are >= the corresponding Vector value with the values in the Vector so that the Matrix would now look like this:

MatrixNew<-cbind(c(2,3,3,1),c(2,3,2,1))

What logic would achieve this?


问:
Iterate an object to fill the FormData so I can update my Order to Database
So with React I have an normal object where is filled with different kind of data, that I fetch from database, so now after I update the order in the front I want to send the new data object to the Database, and the problem is that I need to send it as Form-data because I have multipy images.

So after I fetch the order I put in on React state and this is how it looks when i console log it::

So now I need to make a formData and fill with all those informations, and send to database, I'm using node for backend thoo.

I've tried this until now:

```<code>onClick={() => {
  for (let key in data) {
    formData.append(key, data[key]);
  }
  dispatch(
    updateOrder({
      token: auth.token,
      id: order.order._id,
      body: formData,
    })
  );
}}
</code>```

But I don't know I'm getting an 500 (Internal Server Error).

Update:

For some reasons the formData is not showing anything when I consoled it.

Here is screenshot of it:

答:
Try this:</p>
```<code>onClick={() => {
  let formData = new FormData();
  for (const [key, value] of Object.entries(data)) {
    formData.append(key, value);
  }

  dispatch(
    updateOrder({
      token: auth.token,
      id: order.order._id,
      body: formData,
    })
  );
}}

</code>```

Body:
So with React I have an normal object where is filled with different kind of data, that I fetch from database, so now after I update the order in the front I want to send the new data object to the Database, and the problem is that I need to send it as Form-data because I have multipy images.

So after I fetch the order I put in on React state and this is how it looks when i console log it::

So now I need to make a formData and fill with all those informations, and send to database, I'm using node for backend thoo.

I've tried this until now:

onClick={() => {
  for (let key in data) {
    formData.append(key, data[key]);
  }
  dispatch(
    updateOrder({
      token: auth.token,
      id: order.order._id,
      body: formData,
    })
  );
}}

But I don't know I'm getting an 500 (Internal Server Error).

Update:

For some reasons the formData is not showing anything when I consoled it.

Here is screenshot of it:

Body:
Try this:

onClick={() => {
  let formData = new FormData();
  for (const [key, value] of Object.entries(data)) {
    formData.append(key, value);
  }

  dispatch(
    updateOrder({
      token: auth.token,
      id: order.order._id,
      body: formData,
    })
  );
}}


问:
C# SerialPort Encoding conversion to byte[]
i know I recieve some data in byte format from the serial port (a u-blox GPS device), that should look like this:

```<code>Hex:        0xB5 0x62 0x01 0x21
ISO 8859-1: µ    b    1    !
</code>```

So i read a string s from the command line and print in in a text box and it looks like:

```<code>Tbx:        ?    b       !
</code>```

That seems fine, as the textbox isn't configured to respect the encoding.

When I try to convert the string s to the bytes (which should look like the first Hex-line), I get

```<code>Bytes(d):   63   98   1    33
Bytes(h):   0x3F 0x62 0x1  0x21
</code>```

As you see, the µ char is wrong encoded, somewhere along my way.
Here is the code:

```<code>string s = port.ReadLine();
System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
System.Text.Encoding ascii = port.Encoding;

byte[] bASCII = ascii.GetBytes(s);
byte[] bICO = Encoding.Convert(ascii, iso_8859_1, bASCII);
</code>```

Where do I mess up the µ?

答:
Try this</p>

```<code>System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
port.Encoding = iso_8859_1;

string s = port.ReadLine();

byte[] theBytes = iso_8859_1.GetBytes(s);
</code>```

Body:
i know I recieve some data in byte format from the serial port (a u-blox GPS device), that should look like this:

Hex:        0xB5 0x62 0x01 0x21
ISO 8859-1: µ    b    1    !

So i read a string s from the command line and print in in a text box and it looks like:

Tbx:        ?    b       !

That seems fine, as the textbox isn't configured to respect the encoding.

When I try to convert the string s to the bytes (which should look like the first Hex-line), I get

Bytes(d):   63   98   1    33
Bytes(h):   0x3F 0x62 0x1  0x21

As you see, the µ char is wrong encoded, somewhere along my way.
Here is the code:

string s = port.ReadLine();
System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
System.Text.Encoding ascii = port.Encoding;

byte[] bASCII = ascii.GetBytes(s);
byte[] bICO = Encoding.Convert(ascii, iso_8859_1, bASCII);

Where do I mess up the µ?

Body:
Try this

System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
port.Encoding = iso_8859_1;

string s = port.ReadLine();

byte[] theBytes = iso_8859_1.GetBytes(s);


问:
How to pass parameters to URL from Laravel Blade file
I want to pass parameters from my blade file to the URL when the user presses the next or previous button. I want to achieve that when the user presses the button next, the parameters page will be equal to 1, and the value will keep increasing by one every time the user presses the following button. I know I have to do something in ref, but I do not know what code to put in. So the example URL after the user presses the next button will be www.example.com?page=1.

```<code><div>
    <ul class="pagination">
        <li class="">
            <a href=""><i class="fa fa-angle-left"></i> Previous</a>
        </li>
        <li class="">
            <a href="">Next <i class="fa fa-angle-right"></i></a>
        </li>
    </ul>
</div>
</code>```

答:
Like options you can learn about generating URLs to Named Routes.
With this helper you can past URL in your blade

```<code><a herf="{{ route('name_your_route', ['page' => 2]) }}">test</a>
</code>```

If need more logic you can write in @php section, but its not good

If you need rewrite (redisign) standart pagination you can do this with customizing pagination view

Body:
I want to pass parameters from my blade file to the URL when the user presses the next or previous button. I want to achieve that when the user presses the button next, the parameters page will be equal to 1, and the value will keep increasing by one every time the user presses the following button. I know I have to do something in ref, but I do not know what code to put in. So the example URL after the user presses the next button will be www.example.com?page=1.

             Previous

            Next

Body:
Like options you can learn about generating URLs to Named Routes.
With this helper you can past URL in your blade

<a herf="{{ route('name_your_route', ['page' => 2]) }}">test</a>

If need more logic you can write in @php section, but its not good

If you need rewrite (redisign) standart pagination you can do this with customizing pagination view


问:
Run postgres operator with statement timeout airflow dag
so i've been trying to run 2 postgres operator on my DAG and looks like this:

```<code>default_args = {
    'owner': 'local',
}

log = logging.getLogger(_name_)

TEMP_SETTLEMENT ="""
set statement_timeout to 0;
select function_a();
"""

VACUM_SETTLEMENT="""
vacuum (verbose, analyze) test_table;
"""

try:
    with DAG(
        dag_id='temp-test',
        default_args=default_args,
        schedule_interval=none,
        start_date=datetime(2021, 10, 1),
        max_active_runs=1,
        catchup=False
    ) as dag:

        pg = PostgresOperator(
            task_id="data",
            postgres_conn_id="connection_1",
            database="DB_test",
            autocommit=True,
            sql=TEMP_SETTLEMENT,
        )

        vacum = PostgresOperator(
            task_id="vacum",
            postgres_conn_id="connection_1",
            database="DB_test",
            autocommit=True,
            sql=VACUM_SETTLEMENT,    )

        pg >> vacum

except ImportError as e:
    log.warning("Could not import DAGs: %s", str(e))
</code>```

i keep getting the statement timeout when i try to run the temp_settlement, is there any way to keep the statement_timeout=0?

Thanks

答:
Update:

Starting apache-airflow-providers-postgres>=4.1.0
you can do:

```<code>PostgresOperator(
...,
runtime_parameters={'statement_timeout': '3000ms'},
)
</code>```

This capability was added in PR that solved issue.

Original Answer:

You didn't mention it by from your description I assume that the timeout comes from Postgres and not from Airflow.

For the moment the PostgresOperator does not allow to override the hook/connection settings.
To solve your issue you will need to edit connection_1 in the extra field as explained in the docs you will need to add statement_timeout:

```<code>{'statement_timeout': '3600s'}
</code>```

I opened https://github.com/apache/airflow/issues/21486 as a followup feature request to allow setting statement_timeout directly from the operator.

Body:
so i've been trying to run 2 postgres operator on my DAG and looks like this:

default_args = {
    'owner': 'local',
}

log = logging.getLogger(_name_)

TEMP_SETTLEMENT ="""
set statement_timeout to 0;
select function_a();
"""

VACUM_SETTLEMENT="""
vacuum (verbose, analyze) test_table;
"""

try:
    with DAG(
        dag_id='temp-test',
        default_args=default_args,
        schedule_interval=none,
        start_date=datetime(2021, 10, 1),
        max_active_runs=1,
        catchup=False
    ) as dag:

        pg = PostgresOperator(
            task_id="data",
            postgres_conn_id="connection_1",
            database="DB_test",
            autocommit=True,
            sql=TEMP_SETTLEMENT,
        )

        vacum = PostgresOperator(
            task_id="vacum",
            postgres_conn_id="connection_1",
            database="DB_test",
            autocommit=True,
            sql=VACUM_SETTLEMENT,    )

        pg >> vacum

except ImportError as e:
    log.warning("Could not import DAGs: %s", str(e))

i keep getting the statement timeout when i try to run the temp_settlement, is there any way to keep the statement_timeout=0?

Thanks

Body:
Update:

Starting apache-airflow-providers-postgres>=4.1.0
you can do:

PostgresOperator(
...,
runtime_parameters={'statement_timeout': '3000ms'},
)

This capability was added in PR that solved issue.

Original Answer:

You didn't mention it by from your description I assume that the timeout comes from Postgres and not from Airflow.

For the moment the PostgresOperator does not allow to override the hook/connection settings.
To solve your issue you will need to edit connection_1 in the extra field as explained in the docs you will need to add statement_timeout:

{'statement_timeout': '3600s'}

I opened https://github.com/apache/airflow/issues/21486 as a followup feature request to allow setting statement_timeout directly from the operator.


问:
vue3 array value problem between components
i have a strange problem with arrays in vue3

When loading the components, a start array is transferred, in the components the values are taken over with a watcher if the start array changes. that works wonderfully. the whole thing is a little game, the user moves a cone on a certain route.

I switch to another component by changing a page number. the component with the game should actually be completely from the dom, I don't see anything in the tree either.

```<code><transition name="fadepage" mode="out-in" >
    <div v-if="getPage()==3">
        <VueGameIntro  :content="content" :level="level" :kontrastswitch="kontrastSwitch" :typoswitch="typoSwitch" :levelcolor="levelColor" @mqttMessage="changeMqttMessage"></VueGameIntro>
    </div>
  </transition>

  <transition name="fadepage" mode="out-in" >
    <div v-if="getPage()==4">
        <VueGame   :content="content" :level="level" :playerlist="playerList" :startpointlist="startPointList" :levelendstate="levelEndState" :activeplayerlist="activePlayerList" :kegelmoved="kegelMoved" :kontrastswitch="kontrastSwitch" :id="id" @mqttMessage="changeMqttMessage" @changeCurrPoint="changeCurrPoint"></VueGame>
    </div>
  </transition>

  <transition name="fadepage" mode="out-in">
    <div v-if="getPage()==5">
        <VueGameOutro  :content="content" :level="level" :levelendstate="levelEndState" :kontrastswitch="kontrastSwitch" :typoswitch="typoSwitch" @mqttMessage="changeMqttMessage"></VueGameOutro>
    </div>
</code>```

ok, when the first level has been played it changes to another component VueGameOutro, then it goes back to the actual game components with a new level. Suddenly I have the feeling that this array exists twice.

in the console i see different values than in the output on the screen: {{ currPointList }} shows something different than this.currPointList. in the vue dev plugin, however, are the values as well as the screen output. but the component definitely has a different starting point than the one in the currPointList.

the value in the console seems to have been the latest from the previous level.

Is that possible? how can I be sure that a component is completely gone?

are there arrays that have different values for string or number?

##########################################################
edited

that's the console output:
currPointList unmounted 25,0,0,0,
currPointList mounted 8,0,0,0,
GAME_MOVE currPointList #move,1,3,1 25,0,0,0,
currPointList before move 25,0,0,0,
currPointList move point updated 3,0,0,0,

as you can see, the 25 is in front of the unmount, then the component is reloaded and gets the 8 once via a property form the parent comp

then a move command arrives via websocket, an mqtt component receives the message and sends it to the game via MITT emitter. there's no other place to change currPointList. the first value jumps back to 25.

答: the problem occurred because the emitter.on("eventname" ...) was not deleted when removing the components. I also changed the emitter.on to an arrow function.</p>

Body:
i have a strange problem with arrays in vue3

When loading the components, a start array is transferred, in the components the values are taken over with a watcher if the start array changes. that works wonderfully. the whole thing is a little game, the user moves a cone on a certain route.

I switch to another component by changing a page number. the component with the game should actually be completely from the dom, I don't see anything in the tree either.

<transition name="fadepage" mode="out-in" >

        <VueGameIntro  :content="content" :level="level" :kontrastswitch="kontrastSwitch" :typoswitch="typoSwitch" :levelcolor="levelColor" @mqttMessage="changeMqttMessage"></VueGameIntro>

  </transition>

  <transition name="fadepage" mode="out-in" >

        <VueGame   :content="content" :level="level" :playerlist="playerList" :startpointlist="startPointList" :levelendstate="levelEndState" :activeplayerlist="activePlayerList" :kegelmoved="kegelMoved" :kontrastswitch="kontrastSwitch" :id="id" @mqttMessage="changeMqttMessage" @changeCurrPoint="changeCurrPoint"></VueGame>

  </transition>

  <transition name="fadepage" mode="out-in">

        <VueGameOutro  :content="content" :level="level" :levelendstate="levelEndState" :kontrastswitch="kontrastSwitch" :typoswitch="typoSwitch" @mqttMessage="changeMqttMessage"></VueGameOutro>

ok, when the first level has been played it changes to another component VueGameOutro, then it goes back to the actual game components with a new level. Suddenly I have the feeling that this array exists twice.

in the console i see different values than in the output on the screen: {{ currPointList }} shows something different than this.currPointList. in the vue dev plugin, however, are the values as well as the screen output. but the component definitely has a different starting point than the one in the currPointList.

the value in the console seems to have been the latest from the previous level.

Is that possible? how can I be sure that a component is completely gone?

are there arrays that have different values for string or number?

##########################################################
edited

that's the console output:
currPointList unmounted 25,0,0,0,
currPointList mounted 8,0,0,0,
GAME_MOVE currPointList #move,1,3,1 25,0,0,0,
currPointList before move 25,0,0,0,
currPointList move point updated 3,0,0,0,

as you can see, the 25 is in front of the unmount, then the component is reloaded and gets the 8 once via a property form the parent comp

then a move command arrives via websocket, an mqtt component receives the message and sends it to the game via MITT emitter. there's no other place to change currPointList. the first value jumps back to 25.


问:
How can I integrate in html pages 2 different CSS styles for 2 diferent images?
Can anyone help me?

How can I integrate in html pages 2 different CSS styles for 2 diferent images, both being separated vertically by a space?

See the paintings below. They have different sizes, different styles.

答:
A friend write for me this code, a good answer:

HTML

```<code><div id="img1"><img src=logo.png"></div>
<div id="img2"><img src=logo2.png"></div>
</code>```

CSS

```<code>#img1{border-style :solid;
border-color:red;}

#img2{border-style :solid;
border-color:blue;
margin-top:20px;}
</code>```

SOURCE: HERE

Body:
A friend write for me this code, a good answer:

HTML

<div id="img1"><img src=logo.png"></div>
<div id="img2"><img src=logo2.png"></div>

CSS

#img1{border-style :solid;
border-color:red;}

#img2{border-style :solid;
border-color:blue;
margin-top:20px;}

SOURCE: HERE


问:
I have updated app to angular 13, "ngx-popover" library causing to "Ivy" related error while npm start
I have updated app to angular 13, "ngx-popover" library causing to "Ivy" related error while npm start.

In "package.json":

```<code>"ngx-popover": "^0.0.16"
</code>```

Versions:

```<code>Angular CLI: 13.0.4
Node: 16.13.1
Package Manager: npm 8.1.2
</code>```

Error while "npm start":

```<code>Error: node_modules/ngx-popover/index.d.ts:3:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

This likely means that the library (ngx-popover) which declares PopoverModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.
</code>```

"ngx-popover" library is not updated from time. So it may not supporting Angular 13 Ivy.

Please suggest me solution for this issue.

答:
ngx-popover ist definitly not meant to be used by ivy. A simple workaround is using ng-bootstrap and implement their popover:

https://www.npmjs.com/package/@ng-bootstrap/ng-bootstrap

Body:
I have updated app to angular 13, "ngx-popover" library causing to "Ivy" related error while npm start.

In "package.json":

"ngx-popover": "^0.0.16"

Versions:

Angular CLI: 13.0.4
Node: 16.13.1
Package Manager: npm 8.1.2

Error while "npm start":

Error: node_modules/ngx-popover/index.d.ts:3:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

This likely means that the library (ngx-popover) which declares PopoverModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

"ngx-popover" library is not updated from time. So it may not supporting Angular 13 Ivy.

Please suggest me solution for this issue.