问:
Variables inside @media query in .SCSS files not working
In my angular application, I am writing scss for responsive design & I have few SASS variables declared outside & inside the media queries, but the variables declared inside the media query are not working.

In fonts.scss which is placed in 'styles' folder/directory (under src folder), I have few variables like this in mobile-first approach, I want to change the values of the variables in media queries as Iam working on a responsive design:

```<code>$font-1: normal normal normal 48px/48px Arial;
$font-2: normal normal 300 38px/38px Roboto;

@media screen and (min-width: 768px) {
  $font-1: normal normal normal 56px/56px Arial;
  $font-2: normal normal 300 48px/48px Roboto;
}
</code>```

In my angular component's .scss file, I have included the scss file & I have some classes

```<code>@import 'fonts';

.title1 {
    font: $font-1;
  }

.title2 {
    font: $font-2;
  }
</code>```

and in my component's .html file, I have this code.

```<code><h1 class="title1">Title</h1>
<h2 class="title2">Sub-Title</h2>
</code>```

In angular.json I have added this as I have .scss files in 'styles' folder/directory.

```<code>"stylePreprocessorOptions": {
              "includePaths": [
                "src/styles"
              ]
            },
</code>```

In index.html, I have added this in head section

```<code><meta name="viewport" content="width=device-width, initial-scale=1" />
</code>```

The problem I am facing is, the variables $font-1 and $font-2 are working but the values inside media queries are not working/reflecting. Any mistake I am doing here?

UPDATE: I even tried creating a mixin like this:

```<code>@mixin breakpoint($min-bp) {
    @media (min-width: $min-bp) {
      @content;
    }
}
</code>```

Included it in fonts.scss like this:

```<code> @include breakpoint('768px') {
     $font-1: normal normal normal 56px/56px Arial;
     $font-2: normal normal 300 48px/48px Roboto;
  }
</code>```

But still it did not work.

答:
Check in the config if root is already specified

```<code>{
...
"apps": [{
    "root": "src",
    ...
    "stylePreprocessorOptions": {
        "includePaths": [
          "./styles"
        ]
    }

}]
</code>```

}

If the root is already src, then you just need to remove src/styles and replace it with ./styles

Body:
In my angular application, I am writing scss for responsive design & I have few SASS variables declared outside & inside the media queries, but the variables declared inside the media query are not working.

In fonts.scss which is placed in 'styles' folder/directory (under src folder), I have few variables like this in mobile-first approach, I want to change the values of the variables in media queries as Iam working on a responsive design:

$font-1: normal normal normal 48px/48px Arial;
$font-2: normal normal 300 38px/38px Roboto;

@media screen and (min-width: 768px) {
  $font-1: normal normal normal 56px/56px Arial;
  $font-2: normal normal 300 48px/48px Roboto;
}

In my angular component's .scss file, I have included the scss file & I have some classes

@import 'fonts';

.title1 {
    font: $font-1;
  }

.title2 {
    font: $font-2;
  }

and in my component's .html file, I have this code.

Title

Sub-Title

In angular.json I have added this as I have .scss files in 'styles' folder/directory.

"stylePreprocessorOptions": {
              "includePaths": [
                "src/styles"
              ]
            },

In index.html, I have added this in head section

<meta name="viewport" content="width=device-width, initial-scale=1" />

The problem I am facing is, the variables $font-1 and $font-2 are working but the values inside media queries are not working/reflecting. Any mistake I am doing here?

UPDATE: I even tried creating a mixin like this:

@mixin breakpoint($min-bp) {
    @media (min-width: $min-bp) {
      @content;
    }
}

Included it in fonts.scss like this:

 @include breakpoint('768px') {
     $font-1: normal normal normal 56px/56px Arial;
     $font-2: normal normal 300 48px/48px Roboto;
  }

But still it did not work.

Body:
Check in the config if root is already specified

{
...
"apps": [{
    "root": "src",
    ...
    "stylePreprocessorOptions": {
        "includePaths": [
          "./styles"
        ]
    }

}]

}

If the root is already src, then you just need to remove src/styles and replace it with ./styles


来源: stackexchange

问:
Shell jq is adding header to every other line in csv output, not just once at the top
I am extracting keys from a json with this format:

[
 {
   "k1":{"k2":4},
   "k3":{"k2":6}
 }
]
[
 {
   "k1":{"k2":4},
   "k3":{"k2":6}
 }
]
```
<p>I am using this command <code>["a","b"], (.[] | [.k1.k2,.k3.k2]) | @csv</code> to extract two keys and adding two headers (<code>a</code>, <code>b</code>) to the csv. But The output to this is a header in every other line:</p>
```"\"a\",\"b\""
"4,6"
"\"a\",\"b\""
"4,6"
```

You can see this in this jq play. How can I change to filter to just put header on the first line?

答:
As you have stream in your json, you need inputs instead of .[]

```<code>jq -nr '(["a","b"], (inputs | map(.k1.k2,.k3.k2))) | @csv' input-json
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am extracting keys from a json with this format:

[
 {
   "k1":{"k2":4},
   "k3":{"k2":6}
 }
]
[
 {
   "k1":{"k2":4},
   "k3":{"k2":6}
 }
]

I am using this command ["a","b"], (.[] | [.k1.k2,.k3.k2]) | @csv to extract two keys and adding two headers (a, b) to the csv. But The output to this is a header in every other line:

"\"a\",\"b\""
"4,6"
"\"a\",\"b\""
"4,6"

You can see this in this jq play. How can I change to filter to just put header on the first line?

Body:
As you have stream in your json, you need inputs instead of .[]

jq -nr '(["a","b"], (inputs | map(.k1.k2,.k3.k2))) | @csv' input-json


问:
How to Validate InputQuery user input before the user clicks OK?
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I show an INPUT DIALOG to the user:

```<code>  var aNewFolderName: string := 'New Project Folder';
  if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
  begin
    // Todo: Create the folder if everything went OK, ELSE REPEAT the input action :-(
  end;
</code>```

Is there a way to VALIDATE the user's input BEFORE he clicks the OK button? (E.g., checking for not allowed characters, existing folder, etc.). Just repeating the whole input action in the case of invalid input AFTER the user clicked OK is not very smart and efficient:

```<code>  var aNewFolderName: string := 'New Project Folder';
  var InputIsValid: Boolean;
  repeat
    if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
    begin
      InputIsValid := CheckInput(aNewFolderName);
      if InputIsValid then CreateTheFolder(aNewFolderName);
    end
    else
      BREAK;
  until InputIsValid;
</code>```

Also, with this method, there is no feedback for the user about the specific cause of any invalid input.

答:
The easiest and most versatile option is to write your own input dialog and either include the validation code in the dialog or alternatively pass a callback method that does the validation.

But to answer the question as you asked it:

"Is there a way to VALIDATE the user's input BEFORE he clicks the OK button?"

No, there is no way, as far as I know.

Body:
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I show an INPUT DIALOG to the user:

  var aNewFolderName: string := 'New Project Folder';
  if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
  begin
    // Todo: Create the folder if everything went OK, ELSE REPEAT the input action :-(
  end;

Is there a way to VALIDATE the user's input BEFORE he clicks the OK button? (E.g., checking for not allowed characters, existing folder, etc.). Just repeating the whole input action in the case of invalid input AFTER the user clicked OK is not very smart and efficient:

  var aNewFolderName: string := 'New Project Folder';
  var InputIsValid: Boolean;
  repeat
    if Vcl.Dialogs.InputQuery('New Project Folder', 'Enter the name of the new Project Folder:', aNewFolderName) then
    begin
      InputIsValid := CheckInput(aNewFolderName);
      if InputIsValid then CreateTheFolder(aNewFolderName);
    end
    else
      BREAK;
  until InputIsValid;

Also, with this method, there is no feedback for the user about the specific cause of any invalid input.


问:
How to SELECT / Query Whole Numbers only
Would you know If i can select only whole numbers?
I don't want to round off the values.

For example this is select * from Table_1 below

Numbers
Team

10.5
A

12.12
B

23
C

I would do like
select * from Table_1
where NUMBERS is ;

Expected output below

Numbers
Team

23
C

Thank you very much!

答:
You can use the ROUND function to filter (rather than to display) the values:

SELECT *
FROM   table_1
WHERE  ROUND(numbers) = numbers;
```
<p>You could also use the <code>FLOOR</code>, <code>CEIL</code> or <code>TRUNC</code> functions instead of <code>ROUND</code>.</p>
<p>Or, you could use the <code>MOD</code> function:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM   table_1
WHERE  MOD(numbers, 1) = 0;
</code>```

(And you could apply a function-based index to MOD(number, 1) if you wanted to improve performance.)

Which, for the sample data:

CREATE TABLE table_1 (Numbers, Team) AS
SELECT 10.5,  'A' FROM DUAL UNION ALL
SELECT 12.12, 'B' FROM DUAL UNION ALL
SELECT 23,    'C' FROM DUAL;
```

All the options output:

NUMBERS
TEAM

23
C

db<>fiddle here

Body:
You can use the ROUND function to filter (rather than to display) the values:

SELECT *
FROM   table_1
WHERE  ROUND(numbers) = numbers;

You could also use the FLOOR, CEIL or TRUNC functions instead of ROUND.

Or, you could use the MOD function:

SELECT *
FROM   table_1
WHERE  MOD(numbers, 1) = 0;

(And you could apply a function-based index to MOD(number, 1) if you wanted to improve performance.)

Which, for the sample data:

CREATE TABLE table_1 (Numbers, Team) AS
SELECT 10.5,  'A' FROM DUAL UNION ALL
SELECT 12.12, 'B' FROM DUAL UNION ALL
SELECT 23,    'C' FROM DUAL;

All the options output:

NUMBERS
TEAM

23
C

db<>fiddle here


问:
Share file with React Native
I use { Share } from 'react-native'.
I shared message successfully, no problem.

Now, I generate dynamically a PDF and save it at local.
Is it possible to share the PDF like when I share an url? I didn't find solutions.

After thinking, if PDF isn't possible to share. I have the idea to create dynamically HTML file with react native, then I can share the html file, but it's the same problem. There are no informations about sharing file with { Share}.

I think it's possible with the { Share } from 'react-native' because I saw the same thing on another app on Android.

答:
here is my code currently are used in my app for share image link:

```<code>shareMessage =async (PhotoLink) => {
   try {
     const result = await Share.share({
       title:"title goes here",
       // url:,
       message: "see the photo"+JSON.stringify(PhotoLink),

     });
     if (result.action === Share.sharedAction) {
       if (result.activityType) {
         // shared with activity type of result.activityType
       } else {
         // shared
       }
     } else if (result.action === Share.dismissedAction) {
       // dismissed
     }
   } catch (error) {
     alert(error.message);
   }}
...
onPress={() => this.shareMessage(this.props.route.params.url)}
</code>```

the share component imported from react native;
you can use the like of your PDF to share;
my problem is how can I share link with a small image...you know...like telegram ... when you share a photo, like+ massage+photo will share in a frame.
I don't know how!

ContentLicense: CC BY-SA 3.0

Title: Share file with React Native

Body:
here is my code currently are used in my app for share image link:

shareMessage =async (PhotoLink) => {
   try {
     const result = await Share.share({
       title:"title goes here",
       // url:,
       message: "see the photo"+JSON.stringify(PhotoLink),

     });
     if (result.action === Share.sharedAction) {
       if (result.activityType) {
         // shared with activity type of result.activityType
       } else {
         // shared
       }
     } else if (result.action === Share.dismissedAction) {
       // dismissed
     }
   } catch (error) {
     alert(error.message);
   }}
...
onPress={() => this.shareMessage(this.props.route.params.url)}

the share component imported from react native;
you can use the like of your PDF to share;
my problem is how can I share link with a small image...you know...like telegram ... when you share a photo, like+ massage+photo will share in a frame.
I don't know how!


问:
install pycrypto on python3.6
I am running Centos7 with Python 3.6.  I am trying to install pycrypto with the command "pip3 install pycrypto".  I also installed the dev tools, so gcc is installed.  I am getting the following output.
What am I missing?</p>
```<code>    warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath.
    building 'Crypto.Hash._MD2' extension
    creating build/temp.linux-x86_64-3.6
    creating build/temp.linux-x86_64-3.6/src
    gcc -pthread -Wno-unused-result -Wsign-compare -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -std=c99 -O3 -fomit-frame-pointer -Isrc/ -I/usr/include/python3.6m -c src/MD2.c -o build/temp.linux-x86_64-3.6/src/MD2.o
    src/MD2.c:31:20: fatal error: Python.h: No such file or directory
     #include "Python.h"
                        ^
    compilation terminated.
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-h6pl3s2f/pycrypto/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-9fjag3e5-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-h6pl3s2f/pycrypto/
</code>```

答:
I also had the same issue for CentOS.
However, it turned out I was missing one of the dependencies.</p>
```<code>sudo yum install gcc

sudo yum install gcc-c++

sudo yum install python-devel

sudo pip install pycrypto
</code>```

Title: install pycrypto on python3.6

Body:
I am running Centos7 with Python 3.6.  I am trying to install pycrypto with the command "pip3 install pycrypto".  I also installed the dev tools, so gcc is installed.  I am getting the following output.
What am I missing?

    warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath.
    building 'Crypto.Hash._MD2' extension
    creating build/temp.linux-x86_64-3.6
    creating build/temp.linux-x86_64-3.6/src
    gcc -pthread -Wno-unused-result -Wsign-compare -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -std=c99 -O3 -fomit-frame-pointer -Isrc/ -I/usr/include/python3.6m -c src/MD2.c -o build/temp.linux-x86_64-3.6/src/MD2.o
    src/MD2.c:31:20: fatal error: Python.h: No such file or directory
     #include "Python.h"
                        ^
    compilation terminated.
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-h6pl3s2f/pycrypto/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-9fjag3e5-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-h6pl3s2f/pycrypto/

Body:
I also had the same issue for CentOS.
However, it turned out I was missing one of the dependencies.

sudo yum install gcc

sudo yum install gcc-c++

sudo yum install python-devel

sudo pip install pycrypto


问:
I have a chart but it is not updating the chart with react chart-js-2
I have a react weather project which is based on API
I have a component called CHART but it is not updating the most important part of the project.
Whenever I type the city name it is getting all the information's and updating the written part of the project. But it is not doing it with the chart.And it is always displaying the first values of first call but not updating.
When I come in to the Chart.js file and make a space  in the project and hit save it  is displaying the correct chart based on API .
I can smell there must be use case of useEffect Hook but how ?

Here is the Child Component

import React, {  useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS} from 'chart.js/auto';

const Chart = ({following}) => {
  const date = following.map(item => new Date(item.dt * 1000));
  const dateLocal = date.map(item => item.toLocaleString('default', { weekday: 'long' }));
  const temp = following.map(item => Math.floor(item.temp.day));

  const [userData, setUserData] = useState({
    labels: dateLocal,
    datasets: [
      {
        data: temp,
        label: 'Temperature',
        backgroundColor: [
          'rgba(0, 0, 0,.5)',
          'rgba(0, 0, 0,.5)',
          'rgba(0, 0, 0,.5)',
        ],
        color : ['rgba(0,0,0,1)'],
        fill:true,
        pointRadius: 1,
        pointHitRadius:4,
        pointHoverRadius:8,
        pointBackgroundColor: 'mediumblue',
        borderWidth: 2,
        pointBorderColor: 'lightblue',
        pointBorderWidth: 2,
        pointHoverBorderWidth: 2,
        tooltips: {
          mode: 'index',
          intersect: true,
          windowPadding: 10,
        },
        scales: {
          xAxes: [{
            gridLines: {
              display: false,
            },
            ticks: {
              fontColor: 'green',
              zeroLineColor: 'blue',
              callback :
               function (value) {
                  return value
                }
            }
          }],
          yAxes: [{
            gridLines: {
              display: false,
            },
            ticks: {
              fontColor: 'black',
              fontSize: 112,
              fontStyle: 'bold',
              color: 'red',
              callback :
                function (value) {
                  return value
                }
            }
          }]
        }
      }
    ]
  });

  return (

    <Line
      data={userData}
     />

  )
};

export default Chart;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

Here is the Parent App.js

import React, { useEffect, useState } from 'react';
import Chart from './Chart';

const api = {
  key: `${process.env.REACT_APP_API_KEY}`,
  base: 'https://api.openweathermap.org/data/2.5/'
}

function App() {

  const [query, setQuery] = useState('');
  const [weather, setWeather] = useState({});
  const [location, setLocation] = useState({ lat: '', lon: '' });
  const [following, setFollowing] = useState([]);

  const search = async (e) => {
    if (e.key === 'Enter') {
      await fetch(`${api.base}weather?q=${query}&units=metric&appid=${api.key}&lang=tr`)
        .then(res => res.json())
        .then(result => {
          setWeather(result);
          setQuery('');
          setLocation(result.coord);
          console.log(result);
          searchFollowing();
        }
        )
    }
  }

  useEffect(() => {
    if (location.lat && location.lon) {
      searchFollowing();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location])

  const searchFollowing = async () => {
    await fetch(`${api.base}onecall?lat=${location.lat}&lon=${location.lon}&units=metric&exclude=hourly,minutely&appid=${api.key}`)
      .then(res => res.json())
      .then(result2 => {
        const array = result2.daily.slice(1, 6);
        console.log(following);
        setFollowing(array);
        // following == array
      }
      )
  }

  const integer = (number) => {
    return Math.floor(Math.round(number));
  }

  const mapped = (following) => {
    following = [...following];
    return following.map((item, idx) => {
      const date = new Date(item.dt * 1000);
      const date1 = date.toLocaleString('default', { weekday: 'long' });
      const icon = item.weather[0].icon;
      const day = integer(item.temp.day);
      const night = integer(item.temp.night);
      return (

{date1}

          <img
            src={`http://openweathermap.org/img/wn/${icon}.png`}
            alt='weather'
            width={100}
            height={100}
          />

Gündüz     {day} °C

Gece     {night} °C

      )
    })
  }

  const dateBuild = (d) => {
    let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

    let day = days[d.getDay()]
    let date = d.getDate()
    let month = months[d.getMonth()]
    let year = d.getFullYear()

    return `${day} ${date} ${month} ${year}`
  }

  return (

 25) ? 'App hot' :
        ((weather.main.temp < 25 && weather.main.temp > 5) ?
          'App warm' : 'App')) : 'App'}>

          <input
            type="text"
            className="search-bar"
            placeholder="Search for a location..."
            onChange={e => setQuery(e.target.value)}
            onKeyPress={search}
            value={query}
          />

        {(typeof weather.main != "undefined") ? (

                {weather.name}, {weather.sys.country}

 {dateBuild(new Date())}

                {Math.round(weather.main.temp)}°C
                <img
                  src={`http://openweathermap.org/img/wn/${weather.weather[0].icon.slice(0, 2)}d.png`}
                  alt='weather'
                  width={150}
                  height={150}
                />

                  Hissedilen
                  {Math.floor(weather.main.feels_like)} °C

                  Şu an
                  {weather.weather[0].description}

                  Basınç
                  {weather.main.pressure} mb

                  Rüzgar
                  {Math.floor(weather.wind.speed)} km/h

                  En fazla
                  {Math.floor(weather.main.temp_max)} °C

                  En az
                  {Math.floor(weather.main.temp_min)} °C

            <Chart following={following} />

              {mapped(following)}

) : ('')}

  );
}

export default App;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

答:
UPDATE1 ==>  I did it with the useEffect hook can't able to do it with a built-in method  update()

import React, {  useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS} from 'chart.js/auto';

const Chart = ({following}) => {
  const date = following.map(item => new Date(item.dt * 1000));
  const dateLocal = date.map(item => item.toLocaleString('default', { weekday: 'long' }));
  const temp = following.map(item => Math.floor(item.temp.day));

  // if userData changes then the chart will re-render
    useEffect(() => {
      setUserData({
        labels: dateLocal,
        datasets: [
          {
            data: temp,
            label: 'Temperature',
            backgroundColor: [
              'rgba(0, 0, 0,.5)',
              'rgba(0, 0, 0,.5)',
              'rgba(0, 0, 0,.5)',
            ],
            color : ['rgba(0,0,0,1)'],
            fill:true,
            pointRadius: 1,
            pointHitRadius:4,
            pointHoverRadius:8,
            pointBackgroundColor: 'mediumblue',
            borderWidth: 2,
            pointBorderColor: 'lightblue',
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            tooltips: {
              mode: 'index',
              intersect: true,
              windowPadding: 10,
            },
            scales: {
              xAxes: [{
                gridLines: {
                  display: false,
                },
                ticks: {
                  fontColor: 'green'
                }
              }],
              yAxes: [{
                gridLines: {
                  display: false,
                },
                ticks: {
                  fontColor: 'green'
                }
              }]
            }
          }
        ]
      });
    },[following]);

  const [userData, setUserData] = useState({
    labels: dateLocal,
    datasets: [
      {
        data: temp,
        label: 'Temperature',
        backgroundColor: [
          'rgba(0, 0, 0,.5)',
          'rgba(0, 0, 0,.5)',
          'rgba(0, 0, 0,.5)',
        ],
        color : ['rgba(0,0,0,1)'],
        fill:true,
        pointRadius: 1,
        pointHitRadius:4,
        pointHoverRadius:8,
        pointBackgroundColor: 'mediumblue',
        borderWidth: 2,
        pointBorderColor: 'lightblue',
        pointBorderWidth: 2,
        pointHoverBorderWidth: 2,
        tooltips: {
          mode: 'index',
          intersect: true,
          windowPadding: 10,
        },
        scales: {
          xAxes: [{
            gridLines: {
              display: false,
            },
            ticks: {
              fontColor: 'green'
            }
          }],
          yAxes: [{
            gridLines: {
              display: false,
            },
            ticks: {
              fontColor: 'green'
            }
          }]
        }
      }
    ]
  });

  return (

    <Line className="actual-chart"
      data={userData}
      redraw={true}
     />

  )
};

export default Chart;
   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

Body:
I have a react weather project which is based on API
I have a component called CHART but it is not updating the most important part of the project.
Whenever I type the city name it is getting all the information's and updating the written part of the project. But it is not doing it with the chart.And it is always displaying the first values of first call but not updating.
When I come in to the Chart.js file and make a space  in the project and hit save it  is displaying the correct chart based on API .
I can smell there must be use case of useEffect Hook but how ?

Here is the Child Component

import React, {  useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS} from 'chart.js/auto';

const Chart = ({following}) => {
  const date = following.map(item => new Date(item.dt * 1000));
  const dateLocal = date.map(item => item.toLocaleString('default', { weekday: 'long' }));
  const temp = following.map(item => Math.floor(item.temp.day));

  const [userData, setUserData] = useState({
    labels: dateLocal,
    datasets: [
      {
        data: temp,
        label: 'Temperature',
        backgroundColor: [
          'rgba(0, 0, 0,.5)',
          'rgba(0, 0, 0,.5)',
          'rgba(0, 0, 0,.5)',
        ],
        color : ['rgba(0,0,0,1)'],
        fill:true,
        pointRadius: 1,
        pointHitRadius:4,
        pointHoverRadius:8,
        pointBackgroundColor: 'mediumblue',
        borderWidth: 2,
        pointBorderColor: 'lightblue',
        pointBorderWidth: 2,
        pointHoverBorderWidth: 2,
        tooltips: {
          mode: 'index',
          intersect: true,
          windowPadding: 10,
        },
        scales: {
          xAxes: [{
            gridLines: {
              display: false,
            },
            ticks: {
              fontColor: 'green',
              zeroLineColor: 'blue',
              callback :
               function (value) {
                  return value
                }
            }
          }],
          yAxes: [{
            gridLines: {
              display: false,
            },
            ticks: {
              fontColor: 'black',
              fontSize: 112,
              fontStyle: 'bold',
              color: 'red',
              callback :
                function (value) {
                  return value
                }
            }
          }]
        }
      }
    ]
  });

  return (

    <Line
      data={userData}
     />

  )
};

export default Chart;

Here is the Parent App.js

import React, { useEffect, useState } from 'react';
import Chart from './Chart';

const api = {
  key: `${process.env.REACT_APP_API_KEY}`,
  base: 'https://api.openweathermap.org/data/2.5/'
}

function App() {

  const [query, setQuery] = useState('');
  const [weather, setWeather] = useState({});
  const [location, setLocation] = useState({ lat: '', lon: '' });
  const [following, setFollowing] = useState([]);

  const search = async (e) => {
    if (e.key === 'Enter') {
      await fetch(`${api.base}weather?q=${query}&units=metric&appid=${api.key}&lang=tr`)
        .then(res => res.json())
        .then(result => {
          setWeather(result);
          setQuery('');
          setLocation(result.coord);
          console.log(result);
          searchFollowing();
        }
        )
    }
  }

  useEffect(() => {
    if (location.lat && location.lon) {
      searchFollowing();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location])

  const searchFollowing = async () => {
    await fetch(`${api.base}onecall?lat=${location.lat}&lon=${location.lon}&units=metric&exclude=hourly,minutely&appid=${api.key}`)
      .then(res => res.json())
      .then(result2 => {
        const array = result2.daily.slice(1, 6);
        console.log(following);
        setFollowing(array);
        // following == array
      }
      )
  }

  const integer = (number) => {
    return Math.floor(Math.round(number));
  }

  const mapped = (following) => {
    following = [...following];
    return following.map((item, idx) => {
      const date = new Date(item.dt * 1000);
      const date1 = date.toLocaleString('default', { weekday: 'long' });
      const icon = item.weather[0].icon;
      const day = integer(item.temp.day);
      const night = integer(item.temp.night);
      return (

{date1}

          <img
            src={`http://openweathermap.org/img/wn/${icon}.png`}
            alt='weather'
            width={100}
            height={100}
          />

Gündüz     {day} °C

Gece     {night} °C

      )
    })
  }

  const dateBuild = (d) => {
    let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

    let day = days[d.getDay()]
    let date = d.getDate()
    let month = months[d.getMonth()]
    let year = d.getFullYear()

    return `${day} ${date} ${month} ${year}`
  }

  return (

 25) ? 'App hot' :
        ((weather.main.temp < 25 && weather.main.temp > 5) ?
          'App warm' : 'App')) : 'App'}>

          <input
            type="text"
            className="search-bar"
            placeholder="Search for a location..."
            onChange={e => setQuery(e.target.value)}
            onKeyPress={search}
            value={query}
          />

        {(typeof weather.main != "undefined") ? (

                {weather.name}, {weather.sys.country}

 {dateBuild(new Date())}

                {Math.round(weather.main.temp)}°C
                <img
                  src={`http://openweathermap.org/img/wn/${weather.weather[0].icon.slice(0, 2)}d.png`}
                  alt='weather'
                  width={150}
                  height={150}
                />

                  Hissedilen
                  {Math.floor(weather.main.feels_like)} °C

                  Şu an
                  {weather.weather[0].description}

                  Basınç
                  {weather.main.pressure} mb

                  Rüzgar
                  {Math.floor(weather.wind.speed)} km/h

                  En fazla
                  {Math.floor(weather.main.temp_max)} °C

                  En az
                  {Math.floor(weather.main.temp_min)} °C

            <Chart following={following} />

              {mapped(following)}

) : ('')}

  );
}

export default App;

Body:
UPDATE1 ==>  I did it with the useEffect hook can't able to do it with a built-in method  update()

import React, {  useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS} from 'chart.js/auto';

const Chart = ({following}) => {
  const date = following.map(item => new Date(item.dt * 1000));
  const dateLocal = date.map(item => item.toLocaleString('default', { weekday: 'long' }));
  const temp = following.map(item => Math.floor(item.temp.day));

  // if userData changes then the chart will re-render
    useEffect(() => {
      setUserData({
        labels: dateLocal,
        datasets: [
          {
            data: temp,
            label: 'Temperature',
            backgroundColor: [
              'rgba(0, 0, 0,.5)',
              'rgba(0, 0, 0,.5)',
              'rgba(0, 0, 0,.5)',
            ],
            color : ['rgba(0,0,0,1)'],
            fill:true,
            pointRadius: 1,
            pointHitRadius:4,
            pointHoverRadius:8,
            pointBackgroundColor: 'mediumblue',
            borderWidth: 2,
            pointBorderColor: 'lightblue',
            pointBorderWidth: 2,
            pointHoverBorderWidth: 2,
            tooltips: {
              mode: 'index',
              intersect: true,
              windowPadding: 10,
            },
            scales: {
              xAxes: [{
                gridLines: {
                  display: false,
                },
                ticks: {
                  fontColor: 'green'
                }
              }],
              yAxes: [{
                gridLines: {
                  display: false,
                },
                ticks: {
                  fontColor: 'green'
                }
              }]
            }
          }
        ]
      });
    },[following]);

  const [userData, setUserData] = useState({
    labels: dateLocal,
    datasets: [
      {
        data: temp,
        label: 'Temperature',
        backgroundColor: [
          'rgba(0, 0, 0,.5)',
          'rgba(0, 0, 0,.5)',
          'rgba(0, 0, 0,.5)',
        ],
        color : ['rgba(0,0,0,1)'],
        fill:true,
        pointRadius: 1,
        pointHitRadius:4,
        pointHoverRadius:8,
        pointBackgroundColor: 'mediumblue',
        borderWidth: 2,
        pointBorderColor: 'lightblue',
        pointBorderWidth: 2,
        pointHoverBorderWidth: 2,
        tooltips: {
          mode: 'index',
          intersect: true,
          windowPadding: 10,
        },
        scales: {
          xAxes: [{
            gridLines: {
              display: false,
            },
            ticks: {
              fontColor: 'green'
            }
          }],
          yAxes: [{
            gridLines: {
              display: false,
            },
            ticks: {
              fontColor: 'green'
            }
          }]
        }
      }
    ]
  });

  return (
    <div className="line" style={{ width:'100%'}}>
    <Line className="actual-chart"
      data={userData}
      redraw={true}
     />
    </div>
  )
};

export default Chart;

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


问:
PowerShell script to send me email alerts of Event Viewer errors/warnings/failures
I am trying to edit the script below to utilize the task scheduler send me an email notification every time an error/warning/failure is logged in our servers Event Viewer.

Important info:

I am brand new to PowerShell

The from email and to email are both apart of my company's outlook exchange server

I need this script to pull events from the "Windows" log folder in Event Viewer

I also believe this script requires a module installation, which I am struggling to figure out how to do

I need to know what to edit (I believe in the parameters) to make to fit my specific use case

Thanks in advance for any help at all. Here is the script from https://github.com/blachniet/blachniet-psutils/blob/master/Send-EventEntryEmail.psm1 :

```<code>Import-Module $PSScriptRoot\Send-EventEntryEmail.psm1

Function Send-EventEntryEmail {

[CmdletBinding()]
    param(
        [Parameter()]
        [string] $LogName = "System""Application""Security,

        [Parameter(Mandatory=$true)]
        [string] $Source,

        [Parameter()]
        [int] $Newest = 5,

        [Parameter()]
        [string[]] $EntryType = "Error""Warning""Failure",

        [Parameter(Mandatory=$true)]
        [string] $SmtpUser = "helpdesk@mydomain.com",

        [Parameter(Mandatory=$true)]
        [string] $SmtpPassword = "passwordexample",

        [Parameter()]
        [int] $SmtpPort = 587,

        [Parameter()]
        [string] $SmtpServer = "smtp.mail.outlook.com",

        [Parameter(Mandatory=$true)]
        [string] $MailFrom = "helpdesk@mydomain.com",

        [Parameter(Mandatory=$true)]
        [string] $MailTo = "myemail@mydomain.com,

        [Parameter()]
        [string] $Subject = "EventLogAlert",

    )

    # Get the event entries.
    $eventEntries = Get-EventLog -LogName $LogName -Source $Source -Newest $Newest -EntryType $EntryType

    # Create a table row for each entry.
    $rows = ""
    foreach ($eventEntry in $eventEntries){
        $rows += @"
        <tr>
            <td style="text-align: center; padding: 5px;">$($eventEntry.TimeGenerated)</td>
            <td style="text-align: center; padding: 5px;">$($eventEntry.EntryType)</td>
            <td style="padding: 5px;">$($eventEntry.Message)</td>
        </tr>
"@
    }

    # Create the email.
    $email = New-Object System.Net.Mail.MailMessage( $MailFrom , $MailTo )
    $email.Subject = $Subject
    $email.IsBodyHtml = $true
    $email.Body = @"
    <table style="width:100%;border">
        <tr>
            <th style="text-align: center; padding: 5px;">Time</th>
            <th style="text-align: center; padding: 5px;">Type</th>
            <th style="text-align: center; padding: 5px;">Message</th>
        </tr>

    $rows
    </table>
"@

    # Send the email.
    $SMTPClient=New-Object System.Net.Mail.SmtpClient( $SmtpServer , $SmtpPort )
    $SMTPClient.EnableSsl=$true
    $SMTPClient.Credentials=New-Object System.Net.NetworkCredential( $SmtpUser , $SmtpPassword );
    $SMTPClient.Send( $email )
}

Export-ModuleMember Send-EventEntryEmail
</code>```

Below are the errors I get in ISE when I run this current script:

```<code>At line:17 char:34
+         [string[]] $EntryType = "Error""Warning""Failure",
+                                  ~
Missing ')' in function parameter list.
At line:35 char:49
+         [string] $MailTo = "myemail@mydomain.com,
+                                                 ~
Missing argument in parameter list.
At line:37 char:20
+         [Parameter()]
+                    ~
An expression was expected after '('.
At line:38 char:45
+         [string] $Subject = "EventLogAlert",
+                                             ~
Missing expression after ','.
At line:3 char:31
+ Function Send-EventEntryEmail {
+                               ~
Missing closing '}' in statement block or type definition.
At line:40 char:5
+     )
+     ~
Unexpected token ')' in expression or statement.
At line:78 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInFunctionParameterList
</code>```

答:
Very important Info missing: You need to adjust the XML of your task (add ValueQueries), after you created the Trigger!

(Export, adjust, Import)

```<code><EventTrigger>
  <Enabled>true</Enabled>
  <Subscription> ... </Subscription>
  <ValueQueries>
    <Value name="eventRecordID">Event/System/EventRecordID</Value>
    <Value name="eventChannel">Event/System/Channel</Value>
  </ValueQueries>
</EventTrigger>

</code>```

Nice-to-read:

https://learn.microsoft.com/de-de/archive/blogs/wincat/trigger-a-powershell-script-from-a-windows-event

I also adjusted the script to allow for Authentication, adjusted it to UTF-8 so äöü will work and added some more Information to the subject:

```<code># Collects all named paramters (all others end up in $Args)
param($eventRecordID,$eventChannel)

$event = Get-WinEvent -LogName $eventChannel -FilterXPath "<QueryList><Query Id='0' Path='$eventChannel'><Select Path='$eventChannel'>*[System[(EventRecordID=$eventRecordID)]]</Select></Query></QueryList>";

$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("<username>", $secpasswd)

Send-MailMessage `
    -From '<sender>' `
    -To '<receiver>' `
    -Subject "$env:COMPUTERNAME EVENTLOG $($event.Message.Split([Environment]::NewLine)[0][0..30] -join '')" `
    -SmtpServer '<server>' `
    -Credential $cred `
    -Body ($event.Message) `
    -Port 587 `
    -UseSsl `
    -Encoding UTF8;
</code>```

Body:
I am trying to edit the script below to utilize the task scheduler send me an email notification every time an error/warning/failure is logged in our servers Event Viewer.

Important info:

I am brand new to PowerShell

The from email and to email are both apart of my company's outlook exchange server

I need this script to pull events from the "Windows" log folder in Event Viewer

I also believe this script requires a module installation, which I am struggling to figure out how to do

I need to know what to edit (I believe in the parameters) to make to fit my specific use case

Thanks in advance for any help at all. Here is the script from https://github.com/blachniet/blachniet-psutils/blob/master/Send-EventEntryEmail.psm1 :

Import-Module $PSScriptRoot\Send-EventEntryEmail.psm1

Function Send-EventEntryEmail {

[CmdletBinding()]
    param(
        [Parameter()]
        [string] $LogName = "System""Application""Security,

        [Parameter(Mandatory=$true)]
        [string] $Source,

        [Parameter()]
        [int] $Newest = 5,

        [Parameter()]
        [string[]] $EntryType = "Error""Warning""Failure",

        [Parameter(Mandatory=$true)]
        [string] $SmtpUser = "helpdesk@mydomain.com",

        [Parameter(Mandatory=$true)]
        [string] $SmtpPassword = "passwordexample",

        [Parameter()]
        [int] $SmtpPort = 587,

        [Parameter()]
        [string] $SmtpServer = "smtp.mail.outlook.com",

        [Parameter(Mandatory=$true)]
        [string] $MailFrom = "helpdesk@mydomain.com",

        [Parameter(Mandatory=$true)]
        [string] $MailTo = "myemail@mydomain.com,

        [Parameter()]
        [string] $Subject = "EventLogAlert",

    )

    # Get the event entries.
    $eventEntries = Get-EventLog -LogName $LogName -Source $Source -Newest $Newest -EntryType $EntryType

    # Create a table row for each entry.
    $rows = ""
    foreach ($eventEntry in $eventEntries){
        $rows += @"

            $($eventEntry.TimeGenerated)
            $($eventEntry.EntryType)
            $($eventEntry.Message)

"@
    }

    # Create the email.
    $email = New-Object System.Net.Mail.MailMessage( $MailFrom , $MailTo )
    $email.Subject = $Subject
    $email.IsBodyHtml = $true
    $email.Body = @"

            Time
            Type
            Message

    $rows

"@

    # Send the email.
    $SMTPClient=New-Object System.Net.Mail.SmtpClient( $SmtpServer , $SmtpPort )
    $SMTPClient.EnableSsl=$true
    $SMTPClient.Credentials=New-Object System.Net.NetworkCredential( $SmtpUser , $SmtpPassword );
    $SMTPClient.Send( $email )
}

Export-ModuleMember Send-EventEntryEmail

Below are the errors I get in ISE when I run this current script:

At line:17 char:34
+         [string[]] $EntryType = "Error""Warning""Failure",
+                                  ~
Missing ')' in function parameter list.
At line:35 char:49
+         [string] $MailTo = "myemail@mydomain.com,
+                                                 ~
Missing argument in parameter list.
At line:37 char:20
+         [Parameter()]
+                    ~
An expression was expected after '('.
At line:38 char:45
+         [string] $Subject = "EventLogAlert",
+                                             ~
Missing expression after ','.
At line:3 char:31
+ Function Send-EventEntryEmail {
+                               ~
Missing closing '}' in statement block or type definition.
At line:40 char:5
+     )
+     ~
Unexpected token ')' in expression or statement.
At line:78 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInFunctionParameterList

Body:
Very important Info missing: You need to adjust the XML of your task (add ValueQueries), after you created the Trigger!

(Export, adjust, Import)

<EventTrigger>
  <Enabled>true</Enabled>
  <Subscription> ... </Subscription>
  <ValueQueries>
    <Value name="eventRecordID">Event/System/EventRecordID</Value>
    <Value name="eventChannel">Event/System/Channel</Value>
  </ValueQueries>
</EventTrigger>

Nice-to-read:

https://learn.microsoft.com/de-de/archive/blogs/wincat/trigger-a-powershell-script-from-a-windows-event

I also adjusted the script to allow for Authentication, adjusted it to UTF-8 so äöü will work and added some more Information to the subject:

# Collects all named paramters (all others end up in $Args)
param($eventRecordID,$eventChannel)

$event = Get-WinEvent -LogName $eventChannel -FilterXPath "<QueryList><Query Id='0' Path='$eventChannel'><Select Path='$eventChannel'>*[System[(EventRecordID=$eventRecordID)]]</Select></Query></QueryList>";

$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("<username>", $secpasswd)

Send-MailMessage `
    -From '<sender>' `
    -To '<receiver>' `
    -Subject "$env:COMPUTERNAME EVENTLOG $($event.Message.Split([Environment]::NewLine)[0][0..30] -join '')" `
    -SmtpServer '<server>' `
    -Credential $cred `
    -Body ($event.Message) `
    -Port 587 `
    -UseSsl `
    -Encoding UTF8;


答:
Your input is a stream of JSON documents. Thus, your filter gets executed once for each document, including constructing the headers.

One solution would be to use the --slurp or -s option to read in the stream as an array. This, however, would necessitate to go one level deeper in your iteration (.[][] instead of just .[]):

```<code>jq -s '["a","b"], (.[][] | [.k1.k2,.k3.k2]) | @csv'
</code>```

Demo

Another way would be to use inputs which gives you all input documents at once. This, however, would necessitate to iterate over that (input[] instead of .[]) and use the --null-input or -n flag to avoid swallowing up the first elemment:

```<code>jq -n '["a","b"], (inputs[] | [.k1.k2,.k3.k2]) | @csv'
</code>```

Demo

Note: You also may want to use the --raw-output or -r flag to produce raw text instead of JSON when generating the output with @csv (as I already did in the demos).

Title: Shell jq is adding header to every other line in csv output, not just once at the top

Body:
Your input is a stream of JSON documents. Thus, your filter gets executed once for each document, including constructing the headers.

One solution would be to use the --slurp or -s option to read in the stream as an array. This, however, would necessitate to go one level deeper in your iteration (.[][] instead of just .[]):

jq -s '["a","b"], (.[][] | [.k1.k2,.k3.k2]) | @csv'

Demo

Another way would be to use inputs which gives you all input documents at once. This, however, would necessitate to iterate over that (input[] instead of .[]) and use the --null-input or -n flag to avoid swallowing up the first elemment:

jq -n '["a","b"], (inputs[] | [.k1.k2,.k3.k2]) | @csv'

Demo

Note: You also may want to use the --raw-output or -r flag to produce raw text instead of JSON when generating the output with @csv (as I already did in the demos).


问:
How to perform a 3-way visual diff on git?
I'd like to do a 3-way diff of a single file that exist in 2 different branches, that is, the last commit in each branch and also consider the common ancestor.
I want to use an external tool that allows to do 3-way comparison.
I was considering to use git difftool but as far as I could see it only allows comparing any 2 versions of a given file.
I could use mergetool but that forces me to run git merge first so that, BASE, REMOTE and LOCAL variables are set. I don't want to run git merge. I just want to do a 3-way diff first to see the changes done on the file in both branches considering its common ancestor.

Is there an option to do what I need using difftool or mergetool?
Thanks

答:
Install the 3-way diff tool you prefer, my preferred one is KDiff3.

Open for editing the GIT global configuration:
git edit --global --edit

Adjust it within the tool you chosen:

```<code>[diff]
    tool = kdiff3
[difftool]
    prompt = true
[difftool "kdiff3"]
    cmd = 'C:/Program Files/KDiff3/kdiff3.exe' \"$LOCAL\" \"$REMOTE\"
    keepBackup = false
[merge]
    tool = kdiff3
[mergetool]
    prompt = true
[mergetool "kdiff3"]
    cmd = 'C:/Program Files/KDiff3/kdiff3.exe' \"$BASE\" \"$LOCAL\" \"$REMOTE\" -o \"$MERGED\"
    trustExitCode = true
    keepBackup = true
</code>```

To open it on a file in VS Code using right click command, I added this simple plugin: GIT diff merge tool.

Body:
Install the 3-way diff tool you prefer, my preferred one is KDiff3.

Open for editing the GIT global configuration:
git edit --global --edit

Adjust it within the tool you chosen:

[diff]
    tool = kdiff3
[difftool]
    prompt = true
[difftool "kdiff3"]
    cmd = 'C:/Program Files/KDiff3/kdiff3.exe' \"$LOCAL\" \"$REMOTE\"
    keepBackup = false
[merge]
    tool = kdiff3
[mergetool]
    prompt = true
[mergetool "kdiff3"]
    cmd = 'C:/Program Files/KDiff3/kdiff3.exe' \"$BASE\" \"$LOCAL\" \"$REMOTE\" -o \"$MERGED\"
    trustExitCode = true
    keepBackup = true

To open it on a file in VS Code using right click command, I added this simple plugin: GIT diff merge tool.


问:
Validating an email address
I am trying to send an email using c# using the following code.

```<code>MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress, friendlyName);
mail.To.Add(toAddress);
mail.CC.Add(ccAddress);

//set the content
mail.Subject = emailSubject;
mail.Body = emailHeader + "\n" + emailBody;

//send the message
SmtpClient smtp = new SmtpClient(ServerAddress);
smtp.Credentials = CredentialCache.DefaultNetworkCredentials;
mail.IsBodyHtml = true;
smtp.Send(mail);
</code>```

Now the "toAddress" string that my function recieves might contain a single address, or it might have many, comma delimited addresses.

Now the problem is that, in case of multiple comma delimited addresses, one or two of them might be of the wrong email address format.

So when I try to send an email using this code, I get the exception:

"The specified string is not in the form required for an e-mail address."

Is there any way to validate the comma delimited email addresses?
I had read somewhere that the only way to validate an email address is to send an email to it, because the regular expressions to validate an email addreess can be surprisingly huge.

Also, I have no control over the design, or on how that address string comes to my function,I can't add the email validation in the UI, so I am helpless there...

My problem is that the email will not be delivered to ALL the addresses in the comma delimited string, even though only SOME of the addresses are of the wrong format.

Is there any way to properly validate email addresses in .NET? Is there a way to weed out the bad email addresses and send the mail to only the good ones?

答:
There does not appear to be a good way to validate email addresses.

I have not found a regex to date which will validate correctly. I have had cases of email addresses being blocked by regex. So our focus is to ensure that the MailMessage does not throw an exception during a send. If it does, we can notify the users. But outside of that, if you give bad email address, you don't get an email.

Title: Validating an email address

Body:
I am trying to send an email using c# using the following code.

MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress, friendlyName);
mail.To.Add(toAddress);
mail.CC.Add(ccAddress);

//set the content
mail.Subject = emailSubject;
mail.Body = emailHeader + "\n" + emailBody;

//send the message
SmtpClient smtp = new SmtpClient(ServerAddress);
smtp.Credentials = CredentialCache.DefaultNetworkCredentials;
mail.IsBodyHtml = true;
smtp.Send(mail);

Now the "toAddress" string that my function recieves might contain a single address, or it might have many, comma delimited addresses.

Now the problem is that, in case of multiple comma delimited addresses, one or two of them might be of the wrong email address format.

So when I try to send an email using this code, I get the exception:

"The specified string is not in the form required for an e-mail address."

Is there any way to validate the comma delimited email addresses?
I had read somewhere that the only way to validate an email address is to send an email to it, because the regular expressions to validate an email addreess can be surprisingly huge.

Also, I have no control over the design, or on how that address string comes to my function,I can't add the email validation in the UI, so I am helpless there...

My problem is that the email will not be delivered to ALL the addresses in the comma delimited string, even though only SOME of the addresses are of the wrong format.

Is there any way to properly validate email addresses in .NET? Is there a way to weed out the bad email addresses and send the mail to only the good ones?


问:
How to solve this attribute error in python?

def encode_sequences(tokenizer, length , lines):
  seq = tokenizer.text_to_sequences(lines)
  seq = pad_sequences(seq, maxlen = length, padding = 'posts')
  return seq

from sklearn.model_selection import train_test_split
train , test = train_test_split(deu_eng , test_size = 0.2, random_state = 12)

trainX = encode_sequences(deu_tokenizer, deu_length, train[:,1])
trainY = encode_sequences(eng_tokenizer, eng_length, train[:,0])

testX = encode_sequences(deu_tokenizer, deu_length, test[:,1])
testY = encode_sequences(eng_tokenizer, eng_length, test[:,0])
```
```error :-
AttributeError                            Traceback (most recent call last)
<ipython-input-29-0cb789025947> in <module>()
      7 train , test = train_test_split(deu_eng , test_size = 0.2, random_state = 12)
      8
----> 9 trainX = encode_sequences(deu_tokenizer, deu_length, train[:,1])
     10 trainY = encode_sequences(eng_tokenizer, eng_length, train[:,0])
     11

<ipython-input-29-0cb789025947> in encode_sequences(tokenizer, length, lines)
      1 #model
      2 def encode_sequences(tokenizer, length , lines):
----> 3   seq = tokenizer.text_to_sequences(lines)
      4   seq = pad_sequences(seq, maxlen = length, padding = 'posts')
      5   return seq

AttributeError: 'Tokenizer' object has no attribute 'text_to_sequences'
```

答:
I believe you have mispelled the texts_to_sequences attribute. The error states that it cannot find the text_to_sequences method in the line:

```<code>seq = tokenizer.text_to_sequences(lines)
</code>```

From the documentation, you can see that this method should be spelled:

```<code>seq = tokenizer.texts_to_sequences(lines)
</code>```

This should resolve the error.

Body:
def encode_sequences(tokenizer, length , lines):
  seq = tokenizer.text_to_sequences(lines)
  seq = pad_sequences(seq, maxlen = length, padding = 'posts')
  return seq

from sklearn.model_selection import train_test_split
train , test = train_test_split(deu_eng , test_size = 0.2, random_state = 12)

trainX = encode_sequences(deu_tokenizer, deu_length, train[:,1])
trainY = encode_sequences(eng_tokenizer, eng_length, train[:,0])

testX = encode_sequences(deu_tokenizer, deu_length, test[:,1])
testY = encode_sequences(eng_tokenizer, eng_length, test[:,0])

error :-
AttributeError                            Traceback (most recent call last)
<ipython-input-29-0cb789025947> in <module>()
      7 train , test = train_test_split(deu_eng , test_size = 0.2, random_state = 12)
      8
----> 9 trainX = encode_sequences(deu_tokenizer, deu_length, train[:,1])
     10 trainY = encode_sequences(eng_tokenizer, eng_length, train[:,0])
     11

<ipython-input-29-0cb789025947> in encode_sequences(tokenizer, length, lines)
      1 #model
      2 def encode_sequences(tokenizer, length , lines):
----> 3   seq = tokenizer.text_to_sequences(lines)
      4   seq = pad_sequences(seq, maxlen = length, padding = 'posts')
      5   return seq

AttributeError: 'Tokenizer' object has no attribute 'text_to_sequences'

Body:
I believe you have mispelled the texts_to_sequences attribute. The error states that it cannot find the text_to_sequences method in the line:

seq = tokenizer.text_to_sequences(lines)

From the documentation, you can see that this method should be spelled:

seq = tokenizer.texts_to_sequences(lines)

This should resolve the error.


问:
WP Scroll to ID on click
I will be really grateful if someone could assist me.

I have a GravityForms form on Wordpress and I want the radio button selected to scroll to the form that appears below.

I found that every button has a unique generated class and every form has a unique generated ID. I tried implementing different JavaScript scripts in the Insert Header and Footer plugin.

But nothing I've tried has worked, here is the form:

https://cleanexpert.co.uk/booking/?gpmpn_page=2&postcode=n145ae

答:
Please try this:</p>
```<code>    jQuery('.gfield-choice-input').on('click', function(event) {
     var target = jQuery("#field_1_80");
       // event.preventDefault();
        jQuery('html, body').stop().animate({
            scrollTop: target.offset().top - 180
        }, 2000);
});
</code>```

Title: WP Scroll to ID on click

Body:
Please try this:

    jQuery('.gfield-choice-input').on('click', function(event) {
     var target = jQuery("#field_1_80");
       // event.preventDefault();
        jQuery('html, body').stop().animate({
            scrollTop: target.offset().top - 180
        }, 2000);
});


问:
How to use inheritance in relation to MongoRepositories in spring boot
In my program I have a abstract class "user" which the objects "business" and "customer" inherit from. I am wanting to put some methods inside "UserService" which the other two objects services will make use of. Now in one of these methods I need to call a repository like so.

```<code>userRepository.findByEmail(user.getEmail);
</code>```

Now my problem is that, the other two objects will have problems using the method that contains that line as they will need to have their own repositories (BusinessRepository and CustomerRepository). So my question is, how can I get those two sub repositories to inherit from the userRepository so I dont have to override each method with its respective repository.

```<code>public interface BusinessRepository extends MongoRepository<Business, String>

public interface UserRepository extends MongoRepository<User, String>
</code>```

As you can see there will be issues with the object type if I simply get business Repository to extend UserRepository, any ideas?

Thanks!

答:
You could try to create an interface that doesn't extend from MongoRepository but has all the methods in it:

```<code>public interface UserRepositoryModel<T extends User>{
    T findByEmail(String email);
    //other methods
}

</code>```

And then have the other Repositories extend from this one, too:

```<code>@Repository
public interface BusinessRepository extends MongoRepository<Business, String>, UserRepositoryModel<Business> { }

@Repository
public interface CutomerRepository extends MongoRepository<Cutomer, String>, UserRepositoryModel<Customer>{ }
</code>```

Body:
In my program I have a abstract class "user" which the objects "business" and "customer" inherit from. I am wanting to put some methods inside "UserService" which the other two objects services will make use of. Now in one of these methods I need to call a repository like so.

userRepository.findByEmail(user.getEmail);

Now my problem is that, the other two objects will have problems using the method that contains that line as they will need to have their own repositories (BusinessRepository and CustomerRepository). So my question is, how can I get those two sub repositories to inherit from the userRepository so I dont have to override each method with its respective repository.

public interface BusinessRepository extends MongoRepository<Business, String>

public interface UserRepository extends MongoRepository<User, String>

As you can see there will be issues with the object type if I simply get business Repository to extend UserRepository, any ideas?

Thanks!

Body:
You could try to create an interface that doesn't extend from MongoRepository but has all the methods in it:

public interface UserRepositoryModel<T extends User>{
    T findByEmail(String email);
    //other methods
}

And then have the other Repositories extend from this one, too:

@Repository
public interface BusinessRepository extends MongoRepository<Business, String>, UserRepositoryModel<Business> { }

@Repository
public interface CutomerRepository extends MongoRepository<Cutomer, String>, UserRepositoryModel<Customer>{ }


问:
Numpy/Scipy pinv and pinv2 behave differently
I am working with bidimensional arrays on Numpy for Extreme Learning Machines. One of my arrays, H, is random, and I want to compute its pseudoinverse.
If I use scipy.linalg.pinv2 everything runs smoothly. However, if I use scipy.linalg.pinv, sometimes (30-40% of the times) problems arise.

The reason why I am using pinv2 is because I read (here: http://vene.ro/blog/inverses-pseudoinverses-numerical-issues-speed-symmetry.html ) that pinv2 performs better on "tall" and on "wide" arrays.

The problem is that, if H has a column j of all 1, pinv(H) has huge coefficients at row j.
This is in turn a problem because, in such cases, np.dot(pinv(H), Y) contains some nan values (Y is an array of small integers).

Now, I am not into linear algebra and numeric computation enough to understand if this is a bug or some precision related property of the two functions. I would like you to answer this question so that, if it's the case, I can file a bug report (honestly, at the moment I would not even know what to write).

I saved the arrays with np.savetxt(fn, a, '%.2e', ';'): please, see https://dl.dropboxusercontent.com/u/48242012/example.tar.gz to find them.

Any help is appreciated. In the provided file, you can see in pinv(H).csv that rows 14, 33, 55, 56 and 99 have huge values, while in pinv2(H) the same rows have more decent values.

Your help is appreciated.

答:
Starting from scipy 1.7.0 , pinv2 is deprecated and also replaced by a SVD solution.

DeprecationWarning: scipy.linalg.pinv2 is deprecated since SciPy 1.7.0, use scipy.linalg.pinv instead

That means, numpy.pinv, scipy.pinv and scipy.pinv2 now compute all equivalent solutions. They are also equally fast in their computation, with scipy being slightly faster.

```<code>import numpy as np
import scipy

arr = np.random.rand(1000, 2000)
res1 = np.linalg.pinv(arr)
res2 = scipy.linalg.pinv(arr)
res3 = scipy.linalg.pinv2(arr)

np.testing.assert_array_almost_equal(res1, res2, decimal=10)
np.testing.assert_array_almost_equal(res1, res3, decimal=10)
</code>```

Body:
Starting from scipy 1.7.0 , pinv2 is deprecated and also replaced by a SVD solution.

DeprecationWarning: scipy.linalg.pinv2 is deprecated since SciPy 1.7.0, use scipy.linalg.pinv instead

That means, numpy.pinv, scipy.pinv and scipy.pinv2 now compute all equivalent solutions. They are also equally fast in their computation, with scipy being slightly faster.

import numpy as np
import scipy

arr = np.random.rand(1000, 2000)
res1 = np.linalg.pinv(arr)
res2 = scipy.linalg.pinv(arr)
res3 = scipy.linalg.pinv2(arr)

np.testing.assert_array_almost_equal(res1, res2, decimal=10)
np.testing.assert_array_almost_equal(res1, res3, decimal=10)


问:
Null terminating int arrays
If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?

```<code>int *array = new int[x];
..do some stuff..
delete array;
</code>```

I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?

答: The size of the array is always known. In your code, the size of the array is whatever the value of x is, therefore, the program knows how much memory to free.

Title: Null terminating int arrays

Body:
If I want to dynamically create an int array in C++ and then delete it later, do I need to null terminate the int array? If so, how do I do it? If not, how does the computer know how much memory to free?

int *array = new int[x];
..do some stuff..
delete array;

I know for a char array it deletes up to a null character ('\0') and if you don't have a terminating null character in your string you'll probably get memory violation errors but how does this apply to arrays of ints (and other arrays, like arrays of structs)?


问:
Sync vs async for file write in NodeJS
I've recently been told sync functions completly block the app while they are in use. That is why I want to convert the functionality of the code below to async.
I recive an optimized image, save the file as a .webp format and delete the old nonoptimized one. Than the new user_file gets saved to a database right after this.

```<code>fs.writeFileSync(req.file.path + '.webp', data);
user_file = user_file + '.webp';
fs.unlinkSync(req.file.path);
</code>```

If I just convert it to async like this it just goes on and inserts the old user_file:

```<code>fs.writeFile(req.file.path + '.webp', data, err => {
  if (err) {
    console.error(err);
    return;
  }
  fs.unlink(req.file.path, (err) => {
    if (err) {
      console.error(err);
      return;
    }
    user_file = user_file + '.webp';
  });
});  // I could just put user_file = user_file + '.webp'; here but I also want to make sure that it was successfully saved before moving on
</code>```

How do I keep this async but still wait for the functions to be fully completed before moving on to db insertions?

答:
Use fs.Promises API instead of a classic with a callback.

await fsPromises.writeFile(req.file.path + '.webp', data)
```

Title: Sync vs async for file write in NodeJS

Body:
I've recently been told sync functions completly block the app while they are in use. That is why I want to convert the functionality of the code below to async.
I recive an optimized image, save the file as a .webp format and delete the old nonoptimized one. Than the new user_file gets saved to a database right after this.

fs.writeFileSync(req.file.path + '.webp', data);
user_file = user_file + '.webp';
fs.unlinkSync(req.file.path);

If I just convert it to async like this it just goes on and inserts the old user_file:

fs.writeFile(req.file.path + '.webp', data, err => {
  if (err) {
    console.error(err);
    return;
  }
  fs.unlink(req.file.path, (err) => {
    if (err) {
      console.error(err);
      return;
    }
    user_file = user_file + '.webp';
  });
});  // I could just put user_file = user_file + '.webp'; here but I also want to make sure that it was successfully saved before moving on

How do I keep this async but still wait for the functions to be fully completed before moving on to db insertions?


问:
how to access the properties of the host activity from a fragment dialog (kotlin)?
i have this fragment dialog and i want to edit some host activity properties when he click on btnOk in line 26 can any one help me or give me another way to communicate between a dialog fragment and its host activity
`

```<code>package com.exemple.tic_tac_toe

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.DialogFragment
import android.app.Activity

class restartDialog : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val layout : View = inflater.inflate(R.layout.exit_layout , container , false)
        this.isCancelable = false
        val btnOk : Button = layout.findViewById(R.id.btnYes)
        val btnNo : Button = layout.findViewById(R.id.btnNO)
        btnOk.setOnClickListener(){
            dismiss()
            /////here acces the host activity properties and change them
        }
        btnNo.setOnClickListener(){
            dismiss()
        }
        return  layout
    }
}
</code>```

`

答:
restartDialog.kt:

```<code>package com.exemple.tic_tac_toe

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.DialogFragment
import android.app.Activity

class restartDialog(
    private val someTextView: TextView
) : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val layout : View = inflater.inflate(R.layout.exit_layout , container , false)
        this.isCancelable = false
        val btnOk : Button = layout.findViewById(R.id.btnYes)
        val btnNo : Button = layout.findViewById(R.id.btnNO)
        btnOk.setOnClickListener(){
            dismiss()
            /////here acces the host activity properties and change them
            someTextView.text  = "text will change"
        }
        btnNo.setOnClickListener(){
            dismiss()
        }
        return  layout
    }
}
</code>```

MainActivty.kt:

```<code>package com.exemple.tic_tac_toe
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {
     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val someText : TextView = findViewById(R.id.someText)
        val btndialog : Button = findViewById(R.id.btndialog)
        val restartDialog= restartDialog(someText)
        btndialog .setOnClickListener(){
        if (!restartDialog.isAdded) {
                restartDialog.show(childFragmentManager, "")
            }
          }
     }
}
</code>```

Body:
i have this fragment dialog and i want to edit some host activity properties when he click on btnOk in line 26 can any one help me or give me another way to communicate between a dialog fragment and its host activity
`

package com.exemple.tic_tac_toe

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.DialogFragment
import android.app.Activity

class restartDialog : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val layout : View = inflater.inflate(R.layout.exit_layout , container , false)
        this.isCancelable = false
        val btnOk : Button = layout.findViewById(R.id.btnYes)
        val btnNo : Button = layout.findViewById(R.id.btnNO)
        btnOk.setOnClickListener(){
            dismiss()
            /////here acces the host activity properties and change them
        }
        btnNo.setOnClickListener(){
            dismiss()
        }
        return  layout
    }
}

`

Body:
restartDialog.kt:

package com.exemple.tic_tac_toe

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.DialogFragment
import android.app.Activity

class restartDialog(
    private val someTextView: TextView
) : DialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val layout : View = inflater.inflate(R.layout.exit_layout , container , false)
        this.isCancelable = false
        val btnOk : Button = layout.findViewById(R.id.btnYes)
        val btnNo : Button = layout.findViewById(R.id.btnNO)
        btnOk.setOnClickListener(){
            dismiss()
            /////here acces the host activity properties and change them
            someTextView.text  = "text will change"
        }
        btnNo.setOnClickListener(){
            dismiss()
        }
        return  layout
    }
}

MainActivty.kt:

package com.exemple.tic_tac_toe
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {
     override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val someText : TextView = findViewById(R.id.someText)
        val btndialog : Button = findViewById(R.id.btndialog)
        val restartDialog= restartDialog(someText)
        btndialog .setOnClickListener(){
        if (!restartDialog.isAdded) {
                restartDialog.show(childFragmentManager, "")
            }
          }
     }
}


问:
Update a deeply nested dictionary with a given list
I use Python 3.9 and I have a problem, I have a list:

```<code>keyList = ['a', 'b', 'c', 'd']
</code>```

and I have a dictionary too, and I want to edit (update) this dictionary in the following way:

```<code>myDict = {}
#some code to add the keyList to myDict, this is my question, because I don't know...
myDict = {'a' : {'b' : {'c' : {'d' : 1}}}}

#or when myDict isn't equal to {}

myDict = {'a' : {'c' : 1}}
#same code to add the keyList to myDict
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}}
#same code to add the keyList to myDict, but when it is created, add the +1 to value:
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 2}}}}
</code>```

答:
IIUC, you could use dict.setdefault iteratively:

```<code>def update_myDict(myDict):
    d = myDict
    for k in keyList:
        if k == keyList[-1]:
            d[k] = d.get(k, 0) + 1
        else:
            d = d.setdefault(k, {})
    return myDict
</code>```

Output:

```<code>>>> update_myDict({})
{'a': {'b': {'c': {'d': 1}}}}

>>> update_myDict({'a' : {'c' : 1}})
{'a': {'c': 1, 'b': {'c': {'d': 1}}}}

>>> update_myDict({'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}})
{'a': {'c': 1, 'b': {'c': {'d': 2}}}}
</code>```

Body:
I use Python 3.9 and I have a problem, I have a list:

keyList = ['a', 'b', 'c', 'd']

and I have a dictionary too, and I want to edit (update) this dictionary in the following way:

myDict = {}
#some code to add the keyList to myDict, this is my question, because I don't know...
myDict = {'a' : {'b' : {'c' : {'d' : 1}}}}

#or when myDict isn't equal to {}

myDict = {'a' : {'c' : 1}}
#same code to add the keyList to myDict
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}}
#same code to add the keyList to myDict, but when it is created, add the +1 to value:
myDict = {'a' : {'c' : 1, 'b' : {'c' : {'d' : 2}}}}

Body:
IIUC, you could use dict.setdefault iteratively:

def update_myDict(myDict):
    d = myDict
    for k in keyList:
        if k == keyList[-1]:
            d[k] = d.get(k, 0) + 1
        else:
            d = d.setdefault(k, {})
    return myDict

Output:

>>> update_myDict({})
{'a': {'b': {'c': {'d': 1}}}}

>>> update_myDict({'a' : {'c' : 1}})
{'a': {'c': 1, 'b': {'c': {'d': 1}}}}

>>> update_myDict({'a' : {'c' : 1, 'b' : {'c' : {'d' : 1}}}})
{'a': {'c': 1, 'b': {'c': {'d': 2}}}}