问:
Validate the input from POST values?
Hello dear friends of the web, today I have a problem and it is that I do not know how to validate the data of an INPUT in the POST, if someone can help me to validate this data I would be very grateful, this is the code:

```<code>include("GameEngine/Village.php");

$unarray = array(1 => U1, U2, U3, U4, U5, U6, U11, U12, U13, U14, U15, U16, U21, U22, U23, U24, U25, U26, U31, U32, U33, U34, U35, U36, U41, U42, U43, U44, U45, U46, U0);

if (isset($_GET['id']) && $_GET['id'] == 1) {
    $res_qty = $_POST['resqty'];
    $cost = $res_qty * 30;
    $allres_qty = $res_qty * 100000;
    $database->query("UPDATE " . TB_PREFIX . "users SET `gold` = `gold`- " . $cost . " WHERE id =" . $session->uid);
    $database->query("UPDATE " . TB_PREFIX . "vdata SET `wood` = `wood` + " . $allres_qty . ", `clay` = `clay` + " . $allres_qty . ", `iron` = `iron` + " . $allres_qty . ", `crop` = `crop` + " . $allres_qty . " WHERE wref =" . $village->wid);
    $_SESSION['info'] = $allres_qty . " Wood, Clay, Iron, Crop, added at the cost of " . $cost . " gold.";

    header("Location:dorf1.php");
}
if (isset($_GET['id']) && $_GET['id'] == 2) {
    $troop_type = $_POST['trooptype'];
    $troop_qty = $_POST['troopqty'];
    $cost = $troop_qty * 30;
    $dt = array();

    header("Location:dorf1.php");

    for ($x = 1; $x < 11; $x++) {
        $dt[$x] = 3333;
        if ($x == $troop_type) $dt[$x] = floor($troop_qty * 3333);
    }

    $tribe = $database->getUserField($database->getVillageField($village->wid, "owner"), "tribe", 0);

    if ($tribe == 1) {
        $u = "";
    } elseif ($tribe == 2) {
        $u = "1";
    } elseif ($tribe == 3) {
        $u = "2";
    } elseif ($tribe == 4) {
        $u = "3";
    } else {
        $u = "4";
    }

    $database->modifyUnit(
        $village->wid,
        array($u . "1", $u . "2", $u . "3", $u . "4", $u . "5", $u . "6", $tribe . "0", "hero"),
        array($dt[1], $dt[2], $dt[3], $dt[4], $dt[5], $dt[6], 0),
        array(1, 1, 1, 1, 1, 1)
    );

    $database->query("UPDATE " . TB_PREFIX . "users SET `gold` = `gold`- " . $cost . " WHERE id =" . $session->uid);

    $_SESSION['info'] = ($troop_qty * 3333) . " " . $unarray[($tribe - 1) * 10 + $troop_type] . " added at the cost of " . $cost . " gold.";
} elseif (isset($_GET['id']) && $_GET['id'] == 3) {
    $attack = $_POST['attack'];
    $cost = $attack * 10;
    header("Location:dorf1.php");
    $q = "UPDATE " . TB_PREFIX . "movement SET starttime=" . time() . ", endtime=" . (time() + 5) . " WHERE (`to` =" . $village->wid . " OR `from` = " . $village->wid . ") AND proc = 0";

    $result = $database->query($q);

    if (mysql_affected_rows() > 10) {
        //modify gold
        $database->modifyGold($session->uid, 10);
    }
    $database->query("UPDATE " . TB_PREFIX . "users SET `gold` = `gold`- " . $cost . " WHERE id =" . $session->uid);

    $_SESSION['info'] = "added at the cost of " . $cost . " gold.";
}
</code>```

Hello what I need to validate is the amount of troops and res that I give to my users, this is a script to give troops in my game but I need to validate the troops and resources, thank you very much!
If someone can help me, I would be very grateful!

答:
Here is an example of general data validation :

```<code><?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
</code>```

Source : https://www.w3schools.com/php/php_form_validation.asp

The main idea is to accept only patterns that match what you want to receive as valid data.

Title: Validate the input from POST values?

Body:
Hello dear friends of the web, today I have a problem and it is that I do not know how to validate the data of an INPUT in the POST, if someone can help me to validate this data I would be very grateful, this is the code:

include("GameEngine/Village.php");

$unarray = array(1 => U1, U2, U3, U4, U5, U6, U11, U12, U13, U14, U15, U16, U21, U22, U23, U24, U25, U26, U31, U32, U33, U34, U35, U36, U41, U42, U43, U44, U45, U46, U0);

if (isset($_GET['id']) && $_GET['id'] == 1) {
    $res_qty = $_POST['resqty'];
    $cost = $res_qty * 30;
    $allres_qty = $res_qty * 100000;
    $database->query("UPDATE " . TB_PREFIX . "users SET `gold` = `gold`- " . $cost . " WHERE id =" . $session->uid);
    $database->query("UPDATE " . TB_PREFIX . "vdata SET `wood` = `wood` + " . $allres_qty . ", `clay` = `clay` + " . $allres_qty . ", `iron` = `iron` + " . $allres_qty . ", `crop` = `crop` + " . $allres_qty . " WHERE wref =" . $village->wid);
    $_SESSION['info'] = $allres_qty . " Wood, Clay, Iron, Crop, added at the cost of " . $cost . " gold.";

    header("Location:dorf1.php");
}
if (isset($_GET['id']) && $_GET['id'] == 2) {
    $troop_type = $_POST['trooptype'];
    $troop_qty = $_POST['troopqty'];
    $cost = $troop_qty * 30;
    $dt = array();

    header("Location:dorf1.php");

    for ($x = 1; $x < 11; $x++) {
        $dt[$x] = 3333;
        if ($x == $troop_type) $dt[$x] = floor($troop_qty * 3333);
    }

    $tribe = $database->getUserField($database->getVillageField($village->wid, "owner"), "tribe", 0);

    if ($tribe == 1) {
        $u = "";
    } elseif ($tribe == 2) {
        $u = "1";
    } elseif ($tribe == 3) {
        $u = "2";
    } elseif ($tribe == 4) {
        $u = "3";
    } else {
        $u = "4";
    }

    $database->modifyUnit(
        $village->wid,
        array($u . "1", $u . "2", $u . "3", $u . "4", $u . "5", $u . "6", $tribe . "0", "hero"),
        array($dt[1], $dt[2], $dt[3], $dt[4], $dt[5], $dt[6], 0),
        array(1, 1, 1, 1, 1, 1)
    );

    $database->query("UPDATE " . TB_PREFIX . "users SET `gold` = `gold`- " . $cost . " WHERE id =" . $session->uid);

    $_SESSION['info'] = ($troop_qty * 3333) . " " . $unarray[($tribe - 1) * 10 + $troop_type] . " added at the cost of " . $cost . " gold.";
} elseif (isset($_GET['id']) && $_GET['id'] == 3) {
    $attack = $_POST['attack'];
    $cost = $attack * 10;
    header("Location:dorf1.php");
    $q = "UPDATE " . TB_PREFIX . "movement SET starttime=" . time() . ", endtime=" . (time() + 5) . " WHERE (`to` =" . $village->wid . " OR `from` = " . $village->wid . ") AND proc = 0";

    $result = $database->query($q);

    if (mysql_affected_rows() > 10) {
        //modify gold
        $database->modifyGold($session->uid, 10);
    }
    $database->query("UPDATE " . TB_PREFIX . "users SET `gold` = `gold`- " . $cost . " WHERE id =" . $session->uid);

    $_SESSION['info'] = "added at the cost of " . $cost . " gold.";
}

Hello what I need to validate is the amount of troops and res that I give to my users, this is a script to give troops in my game but I need to validate the troops and resources, thank you very much!
If someone can help me, I would be very grateful!

Body:
Here is an example of general data validation :

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

Source : https://www.w3schools.com/php/php_form_validation.asp

The main idea is to accept only patterns that match what you want to receive as valid data.


来源: stackexchange

问:
Cross-Thread Exception - Environment Only
A control can only be accessed by the thread that created it - this much I know.

I have a DataGridView with a
DataSource based on a BindingList<>.

I have a worker thread (non-GUI)
that runs some fancy
calculations/comparisons/etc and
then adds/edits an object to/in the BindingList<>.

On a timer, the GUI thread refreshes itself against the BindingList<>.

This code works flawlessly - as long as I'm not running in the environment.  In the environment when the .Add() method is called on the BindingList<> I get this handy little error:

```<code>An Exception has occurred
EXCEPTION : Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
IN METHOD : get_Handle
AT LINE   : 0
CLASS     : System.Windows.Forms.Control
</code>```

Notice how the name of the control being violated is blank...  I would think that if the problem was with updating the BindingList<> it wouldn't matter if I was running in the environment or not.  Notwithstanding, that's what I'm seeing.  Moreover, the .Add() completes successfully even though the exception is thrown!!

Obviously, it's not a big deal in my production environment (yet?) since it only happens in Studio; and yes I could Invoke the GUI thread to perform the Add, or store the adds in a place for the GUI thread to retrieve them later...  I'm not looking for a work-around but more so am interested in the answer to this question:

Why does the error only appear in studio?

答:
I think it is happening all the time; however, binding errors are usually silently ignored (for example, BindingSource.DataError ). Visual Studio catches exceptions that are handled - to highlight fail.

Having a data-bound control (DataGridView) and binding-aware collection is asking for trouble if you then update that from another thread. The "observer" nature leads it to do updates on the UI thread. I have hacked around this in the past, but I kinda think you should disable the data-binding completely and update manually. And don't forget that manual update and the background edits should both synchronise access so they don't fight.

Depending on how exactly you are doing the binding, you should be able to disable it and manually refresh it in a loop.

ContentLicense: CC BY-SA 3.0

Body:
A control can only be accessed by the thread that created it - this much I know.

I have a DataGridView with a
DataSource based on a BindingList<>.

I have a worker thread (non-GUI)
that runs some fancy
calculations/comparisons/etc and
then adds/edits an object to/in the BindingList<>.

On a timer, the GUI thread refreshes itself against the BindingList<>.

This code works flawlessly - as long as I'm not running in the environment.  In the environment when the .Add() method is called on the BindingList<> I get this handy little error:

An Exception has occurred
EXCEPTION : Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
IN METHOD : get_Handle
AT LINE   : 0
CLASS     : System.Windows.Forms.Control

Notice how the name of the control being violated is blank...  I would think that if the problem was with updating the BindingList<> it wouldn't matter if I was running in the environment or not.  Notwithstanding, that's what I'm seeing.  Moreover, the .Add() completes successfully even though the exception is thrown!!

Obviously, it's not a big deal in my production environment (yet?) since it only happens in Studio; and yes I could Invoke the GUI thread to perform the Add, or store the adds in a place for the GUI thread to retrieve them later...  I'm not looking for a work-around but more so am interested in the answer to this question:

Why does the error only appear in studio?


问:
Regex after last slash select first digit separate sub-string of 1 or 2 letters
I'm relatively new to RegEx and I'm struggling with making the following match and I hope that the community can help.

I have URLs in the following format:

https://somedomain.com/sub/SUBSITE/FOLDER/12345DR6789

Where I am interested in extracting specific digits from the identifier '12345DR6789' at the end of the string specifically the first numeric digit '1' and the string in the middle 'DR' that can be either 1 or 2 letters so the result for:

12345DR6789 = 1DR

Another example with a single letter:

72345A6789 = 7A

The format will always be the same and the length will vary based on whether there are 1 or 2 letters present.

I managed to get the letter(s) parsed using:

(?<=\d{5})(.*?)(?=\d{3,4}$)

But I don't know how to include/concat the first digit after the slash.

A different strategy might be to match everything after the last slash '72345A6789' and remove 4 digits on either side of the letter(s) but I'm at a loss of how to do that.

Thank you in advance for any help.

答:
You could use 2 capturing groups instead of using lookarounds. The lookaround in your example will only match a single value.

Taking the quantifiers {5} and {3,4} from the example pattern into account:

```<code>(\d)\d{4}([A-Z]{1,2})\d{3,4}$
</code>```

In parts

(\d) Capture group 1, match a digit

\d{4} Match 4 digits

( Capture group 2

[A-Z]{1,2} Match 1-2 times A-Z

) Close group
\d{3,4} Match 3-4 digits

$ End of string

Regex demo

If the pattern should start with http:

```<code>^https?://\S+/(\d)\d{4}([A-Z]{1,2})\d{3,4}$
</code>```

Regex demo

ContentLicense: CC BY-SA 4.0

Body:
You could use 2 capturing groups instead of using lookarounds. The lookaround in your example will only match a single value.

Taking the quantifiers {5} and {3,4} from the example pattern into account:

(\d)\d{4}([A-Z]{1,2})\d{3,4}$

In parts

(\d) Capture group 1, match a digit

\d{4} Match 4 digits

( Capture group 2

[A-Z]{1,2} Match 1-2 times A-Z

) Close group
\d{3,4} Match 3-4 digits

$ End of string

Regex demo

If the pattern should start with http:

^https?://\S+/(\d)\d{4}([A-Z]{1,2})\d{3,4}$

Regex demo


问:
Transferring a double from C++ to python without loss of precision
I have some C++ code which outputs an array of double values. I want to use these double values in python. The obvious and easiest way to transfer the values would of course be dumping them into a file and then rereading the file in python. However, this would lead to loss of precision, because not all decimal places may be transferred. On the other hand, if I add more decimal places, the file gets larger. The array I am trying to transfer has a few million entries. Hence, my idea is to use the double's binary representation, dump them into a binary file and rereading that in python.

The first problem is, that I do not know how the double values are formatted in memory, for example here.  It is easy to read the binary representation of an object from memory, but I have to known where the sign bit, the exponent and the mantiassa are located. There are of course standards for this. The first question is therefore, how do I know which standard my compiler uses? I want to use g++-9. I tried googling this question for various compilers, but without any precise answer. The next question would be on how to turn the bytes back into a double, given the format.

Another possibility may be to compile the C++ code as a python module and use it directly, transferring the array without a file from memory only. But I do not know if this would be easy to set up quickly.

I have also seen that it is possible to compile C++ code directly from a string in python using numpy, but I cannot find any documentation for that.

答:
I have not checked that, but probably python's C++ interface will store doubles by just copying the binary image they represent (the 64bit image) as most probably both languages use the same internal representation of binary floating point numbers (IEEE-754 binary 64bit format)  This has one reason: it is because both use the floating point coprocessor to operate on them, and that's the format it requires to pass it the numbers.

One question arises on that, as you don't say: How have you determined that you are lossing precision in the data? Have you checked different decimal digits only? Or have you exported the actual binary format to check for differences in the bit patterns?  A common mistake is to print both numbers with, let's say 20 significand digits, and then observe differences in the last two or three digits.  This is because you are failing to acquaint on that doubles represented this way (in binary IEEE-752 format) have only around 17 significant digits (it depends on the number, but you can have differences on digit 17th or later, this is because the numbers are binary encoded)

What I strongly don't recommend to you is to convert those numbers into a decimal representation and send them as ascii strings.  You are going to lose some precision (in form of rounding errors, see below) in the encoding, and then again in the decoding phase in python.  Think that converting (even at the maximum precision) a binary floating point into decimal, and then back to binary is almost always a lossing information process.  The problem is that a number that can be represented exactly in decimal (like 0.1) cannot be represented exactly in binary form (you get a periodic infinite repeating sequence, as when you divide 1.0 by 3.0 in decimal, you get a result that is not exact) The opposite conversion is different, as you can always convert a finite decimal binary number into a finite decimal base ten number, but not within 53 bits --which is the amount of bits dedicated to the significand in 64 bit floating point numbers)

So, my advice is to recheck where your numbers show differences and compare with what I say here (if the numbers show differences in digit positions after the 16th decimal digit, those differences are ok --- they have to do only with the different algorithms used by C++ library and python library to convert the numbers into decimal format)  If the differences occur before that, check how are represented floating point numbers in python, or check if, at some point, you lose precision by storing those numbers in a single precision float variable (this is more frequent that normally one estimates) and see if there's some difference (I don't believe there will be) in the formats used by both environments.  By the way, showing such differences in your question should be a plus (something you have also not done) as we could tell you if the differences you observe are normal or not.


问:
Nest httpClient calls and tell which one failed?
I have a component somewhat like the pseudo-code snippet at the bottom.

I need to amend onDeployForTesting() so that it calls myService.save() before calling myService.deployForTesting(). I have been looking into nested Observables and nested calls to httpClient but I can never tell which Observable failed (if one does). I need to know this so that I can continue to set notifications.

Question

How do I nest two (or more) httpClient requests, and see which one in the chain failed (in an RxJS way)?

What I have tried

```<code>onSaveAndDeployForTesting() {
    this.myService
        .save(arg1)
        .pipe(
            concatMap(  // also tried: switchMap, mergeMap
                () => this.myService.deployForTesting(arg2),
            ),
        )
        .subscribe(
            console.info,
            console.error,  // this gives a very generic error with no pointer to which Observable actually failed
            console.info,
        );
}
</code>```

Existing code

```<code>class MyClass {
    // other code

    onSave() {
        this.myService.save(arg1)
            .subscribe(
                (data) => {
                    this.notificationService.set({
                        type: NotificationType.SUCCESS,
                        title: 'Success',
                        description: 'Lorem ipsum dolor sit amet',
                    });
                },
                (err) => {
                    if (err.errorCode === 409) {
                        this.notificationService.set({
                            type: NotificationType.WARNING,
                            title: 'Save Conflict',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    } else {
                        this.notificationService.set({
                            type: NotificationType.ERROR,
                            title: 'Error',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    }
                },
            );
    }

    onDeployForTesting(arg1) {
        this.myService.deployForTesting(arg1)
            .subscribe(
                (data) => {
                    if (data.status === 207) {
                        this.notificationService.set({
                            type: NotificationType.WARNING,
                            title: 'Unable to deploy configuration',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    } else {
                        this.notificationService.set({
                            type: NotificationType.SUCCESS,
                            title: 'Success',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    }
                },
                (err) => {
                    this.notificationService.set({
                        type: NotificationType.ERROR,
                        title: 'Error',
                        description: 'Lorem ipsum dolor sit amet',
                    });
                },
            );
    }
}

class MyService {
    // other code

    save(data) {
        return this.http.put('/my/save/url', data);
    }

    deployForTesting(data) {
        return this.http.post('/my/deploy/url', data);
    }
}
</code>```

答:
You could use RxJS catchError. Try the following

import { throwError, of, EMPTY } from 'rxjs';
import { catchError, concatMap } from 'rxjs/operators';

onSaveAndDeployForTesting() {
  this.myService.save(arg1).pipe(
    catchError(saveError => this.handleSaveError(saveError)),
    concatMap(() => this.myService.deployForTesting(arg2).pipe(
      catchError(deployError => this.handleDeployError(deployError))
    ))
  )
  .subscribe(
    console.info,
    console.error,
    console.info,
  );
}

handleSaveError(error) {
  // handle error from `save()` call
  return EMPTY;      // also `throwError()` or `of()`
}

handleDeployError(error) {
  // handle error from `deployForTesting()` call
  return EMPTY;      // also `throwError()` or `of()`
}
```

Remember to return an observable from the catchError.

Body:
I have a component somewhat like the pseudo-code snippet at the bottom.

I need to amend onDeployForTesting() so that it calls myService.save() before calling myService.deployForTesting(). I have been looking into nested Observables and nested calls to httpClient but I can never tell which Observable failed (if one does). I need to know this so that I can continue to set notifications.

Question

How do I nest two (or more) httpClient requests, and see which one in the chain failed (in an RxJS way)?

What I have tried

onSaveAndDeployForTesting() {
    this.myService
        .save(arg1)
        .pipe(
            concatMap(  // also tried: switchMap, mergeMap
                () => this.myService.deployForTesting(arg2),
            ),
        )
        .subscribe(
            console.info,
            console.error,  // this gives a very generic error with no pointer to which Observable actually failed
            console.info,
        );
}

Existing code

class MyClass {
    // other code

    onSave() {
        this.myService.save(arg1)
            .subscribe(
                (data) => {
                    this.notificationService.set({
                        type: NotificationType.SUCCESS,
                        title: 'Success',
                        description: 'Lorem ipsum dolor sit amet',
                    });
                },
                (err) => {
                    if (err.errorCode === 409) {
                        this.notificationService.set({
                            type: NotificationType.WARNING,
                            title: 'Save Conflict',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    } else {
                        this.notificationService.set({
                            type: NotificationType.ERROR,
                            title: 'Error',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    }
                },
            );
    }

    onDeployForTesting(arg1) {
        this.myService.deployForTesting(arg1)
            .subscribe(
                (data) => {
                    if (data.status === 207) {
                        this.notificationService.set({
                            type: NotificationType.WARNING,
                            title: 'Unable to deploy configuration',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    } else {
                        this.notificationService.set({
                            type: NotificationType.SUCCESS,
                            title: 'Success',
                            description: 'Lorem ipsum dolor sit amet',
                        });
                    }
                },
                (err) => {
                    this.notificationService.set({
                        type: NotificationType.ERROR,
                        title: 'Error',
                        description: 'Lorem ipsum dolor sit amet',
                    });
                },
            );
    }
}

class MyService {
    // other code

    save(data) {
        return this.http.put('/my/save/url', data);
    }

    deployForTesting(data) {
        return this.http.post('/my/deploy/url', data);
    }
}

Body:
You could use RxJS catchError. Try the following

import { throwError, of, EMPTY } from 'rxjs';
import { catchError, concatMap } from 'rxjs/operators';

onSaveAndDeployForTesting() {
  this.myService.save(arg1).pipe(
    catchError(saveError => this.handleSaveError(saveError)),
    concatMap(() => this.myService.deployForTesting(arg2).pipe(
      catchError(deployError => this.handleDeployError(deployError))
    ))
  )
  .subscribe(
    console.info,
    console.error,
    console.info,
  );
}

handleSaveError(error) {
  // handle error from `save()` call
  return EMPTY;      // also `throwError()` or `of()`
}

handleDeployError(error) {
  // handle error from `deployForTesting()` call
  return EMPTY;      // also `throwError()` or `of()`
}

Remember to return an observable from the catchError.


问:
Appending array with useState hook not working as expected
I am using the below code and expect that I will recieve an array of multiple objects as I am using "...".

```<code>const [csv, setCsv] = useState([]);

useEffect(() => {
    d3.csv(fileName, function(fileContents) { setCsv(
        [...csv,{
            'key': fileContents['Licenseno'],
            'First Name': fileContents['First Name'],
            'Address': fileContents['Street #'] + " " + fileContents['Stname'] + " " + fileContents['Suffix'] + " " + '0' + fileContents['Zip']
        }]);
    });
},[])
</code>```

Instead, console.log reveals that csv[] is being re-written for every fileName row and only ever includes one object at a time.

To see whether this was related to d3 (which I have never used before), I declared a const arrayVar = [] and .appended- this worked the way I wanted. So it seems to be the useState hook... any ideas on how to solve this issue?

答:
Another way of using setState is by passing a function.

```<code>// instead of
setCsv([...csv, { key: '...' });

// use this:
setCsv((currentState) => [ ...currentState, { key: '...' } ]);
</code>```

When you pass a function to setState, the current state will be passed as argument to that function. This way you don't have to add the state to your useEffect dependency array.

You can find more information in the React Docs.

Body:
I am using the below code and expect that I will recieve an array of multiple objects as I am using "...".

const [csv, setCsv] = useState([]);

useEffect(() => {
    d3.csv(fileName, function(fileContents) { setCsv(
        [...csv,{
            'key': fileContents['Licenseno'],
            'First Name': fileContents['First Name'],
            'Address': fileContents['Street #'] + " " + fileContents['Stname'] + " " + fileContents['Suffix'] + " " + '0' + fileContents['Zip']
        }]);
    });
},[])

Instead, console.log reveals that csv[] is being re-written for every fileName row and only ever includes one object at a time.

To see whether this was related to d3 (which I have never used before), I declared a const arrayVar = [] and .appended- this worked the way I wanted. So it seems to be the useState hook... any ideas on how to solve this issue?

Body:
Another way of using setState is by passing a function.

// instead of
setCsv([...csv, { key: '...' });

// use this:
setCsv((currentState) => [ ...currentState, { key: '...' } ]);

When you pass a function to setState, the current state will be passed as argument to that function. This way you don't have to add the state to your useEffect dependency array.

You can find more information in the React Docs.


问:
calculate the mean of every nth list in a list of lists using a loop
I am trying to calculate the mean of every nth list in a list of lists using a loop.
I have been able to do so without a loop, but this will prove laborious to do when the list of lists gets longer.

Im struggling to explain this so heres the code

```<code>import numpy as np
import matplotlib.pyplot as plt

list = []
t_r = np.arange(0,8)
i = 0
a =[[0.98,1.93,2.99,4.01,4.92,6.00,7.08,7.67, 8.00],[0,0,0,1,2,3,3,2,3],[0.93,1.99,2.99,3.91,4.82,6.03,7.01,8.00],[0,1,2,3,4,5,5,6],[0.88,2.09,3.01,4.11,5.65,7.12,8.00],[4,5,6,7,8,7,6]]
#########################
for t in t_r:
    b1 = np.array(a[0]) <= t
    b2 = np.array(a[2]) <= t
    b3 = np.array(a[4]) <= t

    ind1 = [(np.count_nonzero(b1))]
    ind2 = [(np.count_nonzero(b2))]
    ind3 = [(np.count_nonzero(b3))]

    x1 = np.array(a[1])
    x_mean1 = x1[ind1]
    x2 = np.array(a[3])
    x_mean2 = x2[ind2]
    x3 = np.array(a[5])
    x_mean3 = x3[ind2]

    x_mean_list = [x_mean1, x_mean2, x_mean3]
    x_average = np.mean(x_mean_list)
    list.append(x_average)
#########################

no_of_sim = 3
counter = 0
while counter <= ((no_of_sim*2)-1):
    plt.plot(a[counter],a[counter+1], lw = 0.5)
    plt.plot(list, color = "black")
    plt.plot(x_average)
    plt.xlabel('Time (s)')
    plt.ylabel('copy no.')
    counter += 2
plt.show()
</code>```

The bit inbetween the hashtags is the bit I'm trying to write a loop for so I don't have to manually change it when the list if lists gets much longer

Body:
I am trying to calculate the mean of every nth list in a list of lists using a loop.
I have been able to do so without a loop, but this will prove laborious to do when the list of lists gets longer.

Im struggling to explain this so heres the code

import numpy as np
import matplotlib.pyplot as plt

list = []
t_r = np.arange(0,8)
i = 0
a =[[0.98,1.93,2.99,4.01,4.92,6.00,7.08,7.67, 8.00],[0,0,0,1,2,3,3,2,3],[0.93,1.99,2.99,3.91,4.82,6.03,7.01,8.00],[0,1,2,3,4,5,5,6],[0.88,2.09,3.01,4.11,5.65,7.12,8.00],[4,5,6,7,8,7,6]]
#########################
for t in t_r:
    b1 = np.array(a[0]) <= t
    b2 = np.array(a[2]) <= t
    b3 = np.array(a[4]) <= t

    ind1 = [(np.count_nonzero(b1))]
    ind2 = [(np.count_nonzero(b2))]
    ind3 = [(np.count_nonzero(b3))]

    x1 = np.array(a[1])
    x_mean1 = x1[ind1]
    x2 = np.array(a[3])
    x_mean2 = x2[ind2]
    x3 = np.array(a[5])
    x_mean3 = x3[ind2]

    x_mean_list = [x_mean1, x_mean2, x_mean3]
    x_average = np.mean(x_mean_list)
    list.append(x_average)
#########################

no_of_sim = 3
counter = 0
while counter <= ((no_of_sim*2)-1):
    plt.plot(a[counter],a[counter+1], lw = 0.5)
    plt.plot(list, color = "black")
    plt.plot(x_average)
    plt.xlabel('Time (s)')
    plt.ylabel('copy no.')
    counter += 2
plt.show()

The bit inbetween the hashtags is the bit I'm trying to write a loop for so I don't have to manually change it when the list if lists gets much longer

Body:
Your code between the hashes are equivalent to the following:

data = [np.array(x) for x in a[::2]]
idx = [np.array(x) for x in a[1::2]]

lst = [np.mean([x[(d<=t).sum()] for x,d in zip(idx,data)]) for t in t_r ]

Output:

[1.3333333333333333,
 2.0,
 2.3333333333333335,
 3.3333333333333335,
 4.0,
 5.333333333333333,
 5.0,
 5.0]


问:
How to launch the atmx file programmatically in C#?
can someone please tell me why my line of code to execute an atmx file isn't working?
the code doesn't go further after opening the internet explorer :(

```<code>try
                    {
                        switch (status)
                        {
                            case true:
                                IWebDriver driver = new InternetExplorerDriver();
                                driver.Navigate().GoToUrl(@"http://www.rpachallenge.com/");

                                Console.WriteLine("get ATMX file...........");
                                string getATMX = String.Format("C:\\Users\\{0}\\Desktop\\VS Test Environment\\Testing.atmx", Environment.UserName);
                                Process.Start(getATMX);

                                SqlConnection connect = new SqlConnection();
                                connect.Open();
                                SqlCommand

</code>```

the atmx file get info from sql and fills the fields on rpachallenge.com, capture the ending result then saves in sql.

答:
The .atmx file isn't the executable itself, it's an script file which is executed by the Automation Anywhere runtime (AA.Player.exe) instead.
You need to ensure that "AA.Player.exe" is installed and is registered application for files with extension ".atmx" on the machine you're trying to execute. Hope that helps.</p>

Body:
can someone please tell me why my line of code to execute an atmx file isn't working?
the code doesn't go further after opening the internet explorer :(

try
                    {
                        switch (status)
                        {
                            case true:
                                IWebDriver driver = new InternetExplorerDriver();
                                driver.Navigate().GoToUrl(@"http://www.rpachallenge.com/");

                                Console.WriteLine("get ATMX file...........");
                                string getATMX = String.Format("C:\\Users\\{0}\\Desktop\\VS Test Environment\\Testing.atmx", Environment.UserName);
                                Process.Start(getATMX);

                                SqlConnection connect = new SqlConnection();
                                connect.Open();
                                SqlCommand

the atmx file get info from sql and fills the fields on rpachallenge.com, capture the ending result then saves in sql.


答:
The error may occur only in VS if it is a MDA (Managed Debugging Assistant), not a runtime exception.  MDAs are there to tell you when you are doing something that is usually, but not 100% always, something that will get you in trouble in production code (which this will, eventually, even if it seems to work 99% of the time on your machine).

You should be invoking to the UI thread to perform the Add method.

EDIT: To be 100% thorough...  Without Reflector (since mine expired- are you listening Red Gate?!) I am guessing that the Control class checks to see whether you are on the UI thread, throws the exception on the background thread if you are not, and then redraws the UI anyway.  Since the background thread has already added the item, the UI redraw sees it and draws it to the UI as expected, but your background thread is still seeing the exception, and you are either swallowing it silently in a catch block or the background thread is being terminated (which in your app is maybe tolerable, for inst. that BG thread is a threadpool thread).

Title: Cross-Thread Exception - Environment Only


问:
Why doesnt byebug/pry stop at the breakpoint in Rspec ActionMailer?
I try to debug my user_mailer.rb within my test environment. But I dont know why the debugger doesnst stop where it suppose to.

So, the code I roughly have is:
user_mailer_spec.rb

```<code>describe UserMailer do
  describe '#send_notification_letters' do
    # bunch of code omitted here ...
    it 'should record itself to the database'
      expect { UserMailer.send_notification_letters(user) }.to change{SentMail.count}.by(1)
    end
  end
end
</code>```

In user_mailer.rb

```<code>class UserMailer < ActionMailer::Base
  def send_notification_letters(user)
    byebug # should break here but doesnt,
           # also tried binding.pry here, also doesnt work
    # buggy code ...
    # buggy code ...
    # buggy code ...

    SentMail.create(...) # never reached
    mail(to:..., from:...)
  end
end
</code>```

The question is, why is byebug/pry not stopping in the user_mail.rb when i run the test rspec spec/mailer/user_mailer_spec.rb?

And why?

How to make it stop at that break point?

Is there a bug in the debugger?

答:
I had the same problem, just restart the server.

In my case puma, and without spring.

Body:
I try to debug my user_mailer.rb within my test environment. But I dont know why the debugger doesnst stop where it suppose to.

So, the code I roughly have is:
user_mailer_spec.rb

describe UserMailer do
  describe '#send_notification_letters' do
    # bunch of code omitted here ...
    it 'should record itself to the database'
      expect { UserMailer.send_notification_letters(user) }.to change{SentMail.count}.by(1)
    end
  end
end

In user_mailer.rb

class UserMailer < ActionMailer::Base
  def send_notification_letters(user)
    byebug # should break here but doesnt,
           # also tried binding.pry here, also doesnt work
    # buggy code ...
    # buggy code ...
    # buggy code ...

    SentMail.create(...) # never reached
    mail(to:..., from:...)
  end
end

The question is, why is byebug/pry not stopping in the user_mail.rb when i run the test rspec spec/mailer/user_mailer_spec.rb?

And why?

How to make it stop at that break point?

Is there a bug in the debugger?


问:
Select only one result field from two joined tables
I'm trying to select only one field from two tables. Instead of c.cust_name and s.supp_name just only one field name with contend from either customer or supplier table.

SELECT o.id, o.order_nr, o.cust_suppl, c.cust_name, s.supp_name
FROM   Orders AS o LEFT OUTER JOIN
       customer AS c ON o.id = c.id LEFT OUTER JOIN
       supplier AS s ON o.id = s.id
```

<p>Current output:</p>

```id    order_nr   cust_suppl   cust_name   supp_name
1       1100       c            Cust_A      NULL
2       1101       c            Cust_B      NULL
3       2100       s            NULL        Suppl_A
4       2101       s            NULL        Suppl_B
```

答:
you could decode:

```<code>SELECT o.id, o.order_nr, o.cust_suppl
       , decode( c.cust_name, null, s.supp_name, c.cust_name )
FROM   Orders AS o LEFT OUTER JOIN
       customer AS c ON o.id = c.id LEFT OUTER JOIN
       supplier AS s ON o.id = s.id
</code>```

or use a case:

```<code>SELECT o.id, o.order_nr, o.cust_suppl
       , case when c.cust_name is null then s.supp_name else c.cust_name end
FROM   Orders AS o LEFT OUTER JOIN
       customer AS c ON o.id = c.id LEFT OUTER JOIN
       supplier AS s ON o.id = s.id
</code>```

Body:
I'm trying to select only one field from two tables. Instead of c.cust_name and s.supp_name just only one field name with contend from either customer or supplier table.

SELECT o.id, o.order_nr, o.cust_suppl, c.cust_name, s.supp_name
FROM   Orders AS o LEFT OUTER JOIN
       customer AS c ON o.id = c.id LEFT OUTER JOIN
       supplier AS s ON o.id = s.id

Current output:

id    order_nr   cust_suppl   cust_name   supp_name
1       1100       c            Cust_A      NULL
2       1101       c            Cust_B      NULL
3       2100       s            NULL        Suppl_A
4       2101       s            NULL        Suppl_B

Body:
you could decode:

SELECT o.id, o.order_nr, o.cust_suppl
       , decode( c.cust_name, null, s.supp_name, c.cust_name )
FROM   Orders AS o LEFT OUTER JOIN
       customer AS c ON o.id = c.id LEFT OUTER JOIN
       supplier AS s ON o.id = s.id

or use a case:

SELECT o.id, o.order_nr, o.cust_suppl
       , case when c.cust_name is null then s.supp_name else c.cust_name end
FROM   Orders AS o LEFT OUTER JOIN
       customer AS c ON o.id = c.id LEFT OUTER JOIN
       supplier AS s ON o.id = s.id


问:
A dataset is loaded from a csv file, with a schema asking fields to be considered as not nullable. Then, a printSchema() describes the fields nullable
I load a csv file with Apache Spark.

Dataset<Row> csv = session.read().schema(schema()).format("csv")
  .option("header","true").option("delimiter", ";").load("myFile.csv").selectExpr("*");
```

<p>For it, I provided a schema : </p>

<pre class="lang-java prettyprint-override"><code>public StructType schema(boolean renamed) {
   StructType schema = new StructType();

   schema = schema.add("CODGEO", StringType, false)
     .add("P16_POP1564", DoubleType, false)
     .add("P16_POP1524", DoubleType, false)
     .add("P16_POP2554", DoubleType, false)
     .add("P16_POP5564", DoubleType, false)
     .add("P16_H1564", DoubleType, false)
      ....
   return schema;
}
</code>```

The dataset is loaded. A printSchema() on it displays me this on the console :

```<code>root
 |-- CODGEO: string (nullable = true)
 |-- P16_POP1564: double (nullable = true)
 |-- P16_POP1524: double (nullable = true)
 |-- P16_POP2554: double (nullable = true)
 |-- P16_POP5564: double (nullable = true)
 |-- P16_H1564: double (nullable = true)
 ...
</code>```

But every field is tagged as nullable = true.

And I explicitly asked each of them to be not nullable.

What's the problem ?

答:
For me, it is working well-

By default, empty string("") is considered as null while reading csv

Test-1. Dataset having null & Schema nullable=false

  String data = "id  Col_1 Col_2 Col_3 Col_4 Col_5\n" +
                "1    A     B      C     D     E\n" +
                "2    X     Y      Z     P     \"\"";

        List<String> list = Arrays.stream(data.split(System.lineSeparator()))
                .map(s -> s.replaceAll("\\s+", ","))
                .collect(Collectors.toList());
        List<StructField> fields = Arrays.stream("id  Col_1 Col_2 Col_3 Col_4 Col_5".split("\\s+"))
                .map(s -> new StructField(s, DataTypes.StringType, false, Metadata.empty()))
                .collect(Collectors.toList());
        Dataset<Row> df1 = spark.read()
                .schema(new StructType(fields.toArray(new StructField[fields.size()])))
                .option("header", true)
                .option("sep", ",")
                .csv(spark.createDataset(list, Encoders.STRING()));
        df1.show();
        df1.printSchema();
```

<p>Output-</p>

<pre class="lang-java prettyprint-override"><code>java.lang.NullPointerException
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificSafeProjection.createExternalRow_0_0$(Unknown Source)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificSafeProjection.apply(Unknown Source)
    at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$collectFromPlan$1.apply(Dataset.scala:3387)
    at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$collectFromPlan$1.apply(Dataset.scala:3384)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
</code>```

Conclusion- Expected behaviour PASS

2. Dataset having null & Schema nullable=true

  String data = "id  Col_1 Col_2 Col_3 Col_4 Col_5\n" +
                "1    A     B      C     D     E\n" +
                "2    X     Y      Z     P     \"\"";

        List<String> list = Arrays.stream(data.split(System.lineSeparator()))
                .map(s -> s.replaceAll("\\s+", ","))
                .collect(Collectors.toList());
        List<StructField> fields = Arrays.stream("id  Col_1 Col_2 Col_3 Col_4 Col_5".split("\\s+"))
                .map(s -> new StructField(s, DataTypes.StringType, true, Metadata.empty()))
                .collect(Collectors.toList());
        Dataset<Row> df1 = spark.read()
                .schema(new StructType(fields.toArray(new StructField[fields.size()])))
                .option("header", true)
                .option("sep", ",")
                .csv(spark.createDataset(list, Encoders.STRING()));
        df1.show();
        df1.printSchema();
```

<p>Output-</p>

<pre class="lang-java prettyprint-override"><code>+---+-----+-----+-----+-----+-----+
| id|Col_1|Col_2|Col_3|Col_4|Col_5|
+---+-----+-----+-----+-----+-----+
|  1|    A|    B|    C|    D|    E|
|  2|    X|    Y|    Z|    P| null|
+---+-----+-----+-----+-----+-----+

root
 |-- id: string (nullable = true)
 |-- Col_1: string (nullable = true)
 |-- Col_2: string (nullable = true)
 |-- Col_3: string (nullable = true)
 |-- Col_4: string (nullable = true)
 |-- Col_5: string (nullable = true)
</code>```

Conclusion- Expected behaviour PASS

3. Dataset without null & Schema nullable=true

  String data1 = "id  Col_1 Col_2 Col_3 Col_4 Col_5\n" +
                "1    A     B      C     D     E\n" +
                "2    X     Y      Z     P     F";

        List<String> list1 = Arrays.stream(data1.split(System.lineSeparator()))
                .map(s -> s.replaceAll("\\s+", ","))
                .collect(Collectors.toList());
        List<StructField> fields1 = Arrays.stream("id  Col_1 Col_2 Col_3 Col_4 Col_5".split("\\s+"))
                .map(s -> new StructField(s, DataTypes.StringType, true, Metadata.empty()))
                .collect(Collectors.toList());
        Dataset<Row> df2 = spark.read()
                .schema(new StructType(fields1.toArray(new StructField[fields.size()])))
                .option("header", true)
                .option("sep", ",")
                .csv(spark.createDataset(list1, Encoders.STRING()));
        df2.show();
        df2.printSchema();
```

<p>Output-</p>

<pre class="lang-java prettyprint-override"><code>+---+-----+-----+-----+-----+-----+
| id|Col_1|Col_2|Col_3|Col_4|Col_5|
+---+-----+-----+-----+-----+-----+
|  1|    A|    B|    C|    D|    E|
|  2|    X|    Y|    Z|    P|    F|
+---+-----+-----+-----+-----+-----+

root
 |-- id: string (nullable = true)
 |-- Col_1: string (nullable = true)
 |-- Col_2: string (nullable = true)
 |-- Col_3: string (nullable = true)
 |-- Col_4: string (nullable = true)
 |-- Col_5: string (nullable = true)

</code>```

Conclusion- Expected behaviour PASS

Body:
I load a csv file with Apache Spark.

Dataset<Row> csv = session.read().schema(schema()).format("csv")
  .option("header","true").option("delimiter", ";").load("myFile.csv").selectExpr("*");

For it, I provided a schema :

public StructType schema(boolean renamed) {
   StructType schema = new StructType();

   schema = schema.add("CODGEO", StringType, false)
     .add("P16_POP1564", DoubleType, false)
     .add("P16_POP1524", DoubleType, false)
     .add("P16_POP2554", DoubleType, false)
     .add("P16_POP5564", DoubleType, false)
     .add("P16_H1564", DoubleType, false)
      ....
   return schema;
}

The dataset is loaded. A printSchema() on it displays me this on the console :

root
 |-- CODGEO: string (nullable = true)
 |-- P16_POP1564: double (nullable = true)
 |-- P16_POP1524: double (nullable = true)
 |-- P16_POP2554: double (nullable = true)
 |-- P16_POP5564: double (nullable = true)
 |-- P16_H1564: double (nullable = true)
 ...

But every field is tagged as nullable = true.

And I explicitly asked each of them to be not nullable.

What's the problem ?

Body:
For me, it is working well-

By default, empty string("") is considered as null while reading csv

Test-1. Dataset having null & Schema nullable=false

  String data = "id  Col_1 Col_2 Col_3 Col_4 Col_5\n" +
                "1    A     B      C     D     E\n" +
                "2    X     Y      Z     P     \"\"";

        List<String> list = Arrays.stream(data.split(System.lineSeparator()))
                .map(s -> s.replaceAll("\\s+", ","))
                .collect(Collectors.toList());
        List<StructField> fields = Arrays.stream("id  Col_1 Col_2 Col_3 Col_4 Col_5".split("\\s+"))
                .map(s -> new StructField(s, DataTypes.StringType, false, Metadata.empty()))
                .collect(Collectors.toList());
        Dataset<Row> df1 = spark.read()
                .schema(new StructType(fields.toArray(new StructField[fields.size()])))
                .option("header", true)
                .option("sep", ",")
                .csv(spark.createDataset(list, Encoders.STRING()));
        df1.show();
        df1.printSchema();

Output-

java.lang.NullPointerException
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificSafeProjection.createExternalRow_0_0$(Unknown Source)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificSafeProjection.apply(Unknown Source)
    at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$collectFromPlan$1.apply(Dataset.scala:3387)
    at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$collectFromPlan$1.apply(Dataset.scala:3384)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)

Conclusion- Expected behaviour PASS

2. Dataset having null & Schema nullable=true

  String data = "id  Col_1 Col_2 Col_3 Col_4 Col_5\n" +
                "1    A     B      C     D     E\n" +
                "2    X     Y      Z     P     \"\"";

        List<String> list = Arrays.stream(data.split(System.lineSeparator()))
                .map(s -> s.replaceAll("\\s+", ","))
                .collect(Collectors.toList());
        List<StructField> fields = Arrays.stream("id  Col_1 Col_2 Col_3 Col_4 Col_5".split("\\s+"))
                .map(s -> new StructField(s, DataTypes.StringType, true, Metadata.empty()))
                .collect(Collectors.toList());
        Dataset<Row> df1 = spark.read()
                .schema(new StructType(fields.toArray(new StructField[fields.size()])))
                .option("header", true)
                .option("sep", ",")
                .csv(spark.createDataset(list, Encoders.STRING()));
        df1.show();
        df1.printSchema();

Output-

+---+-----+-----+-----+-----+-----+
| id|Col_1|Col_2|Col_3|Col_4|Col_5|
+---+-----+-----+-----+-----+-----+
|  1|    A|    B|    C|    D|    E|
|  2|    X|    Y|    Z|    P| null|
+---+-----+-----+-----+-----+-----+

root
 |-- id: string (nullable = true)
 |-- Col_1: string (nullable = true)
 |-- Col_2: string (nullable = true)
 |-- Col_3: string (nullable = true)
 |-- Col_4: string (nullable = true)
 |-- Col_5: string (nullable = true)

Conclusion- Expected behaviour PASS

3. Dataset without null & Schema nullable=true

  String data1 = "id  Col_1 Col_2 Col_3 Col_4 Col_5\n" +
                "1    A     B      C     D     E\n" +
                "2    X     Y      Z     P     F";

        List<String> list1 = Arrays.stream(data1.split(System.lineSeparator()))
                .map(s -> s.replaceAll("\\s+", ","))
                .collect(Collectors.toList());
        List<StructField> fields1 = Arrays.stream("id  Col_1 Col_2 Col_3 Col_4 Col_5".split("\\s+"))
                .map(s -> new StructField(s, DataTypes.StringType, true, Metadata.empty()))
                .collect(Collectors.toList());
        Dataset<Row> df2 = spark.read()
                .schema(new StructType(fields1.toArray(new StructField[fields.size()])))
                .option("header", true)
                .option("sep", ",")
                .csv(spark.createDataset(list1, Encoders.STRING()));
        df2.show();
        df2.printSchema();

Output-

+---+-----+-----+-----+-----+-----+
| id|Col_1|Col_2|Col_3|Col_4|Col_5|
+---+-----+-----+-----+-----+-----+
|  1|    A|    B|    C|    D|    E|
|  2|    X|    Y|    Z|    P|    F|
+---+-----+-----+-----+-----+-----+

root
 |-- id: string (nullable = true)
 |-- Col_1: string (nullable = true)
 |-- Col_2: string (nullable = true)
 |-- Col_3: string (nullable = true)
 |-- Col_4: string (nullable = true)
 |-- Col_5: string (nullable = true)

Conclusion- Expected behaviour PASS


问:
GitHub Error: Key already in use
I have created two GitHub accounts.  One for my work user and one for my personal self.  I needed to do catch up on some work and as such cloned my work repo onto my personal PC.  In order to do simple "git push origin master" commits without entering my username and password the whole time I simply want to add my public key from my home pc to the work repo.  However Github gives this error:

```<code>Error: Key already use
</code>```

After a bit of Googling I came across this link which states "To resolve the issue, remove the key from the other account or repository and add it to your account"  Of course there is a duplicate key as I've added my home public key to github so that I can code on my own personal projects. After all I want to be able to code to my work repo using both my work pc and personal pc.

How can you add multiple "same" public keys without Github throwing that error and also why in the world, is that error thrown in the first place?

答:
I've found a workaround that works for me:

You cannot add the same SSH key to different accounts, and that is true for GitHub, BitBucket, etc. But you can use different SSH keys for each account. The only downside then is how to easily switch between them?

I use ssh-agent and it can use multiple keys at the same time. I auto add them through .bashrc

```<code>if [ -z "$SSH_AUTH_SOCK" ] ; then
  eval `ssh-agent -s`
  ssh-add ~/.ssh/id_rsa
  ssh-add ~/.ssh/id_rsa2
fi
</code>```

This approach works regardless of which key is added in your GitHub account. I guess ssh-agent makes attempts with each key until it succeeds. And if you don't want to add all keys, you just comment out the relevant line in the .bashrc before starting a new shell.

Title: GitHub Error: Key already in use

Body:
I have created two GitHub accounts.  One for my work user and one for my personal self.  I needed to do catch up on some work and as such cloned my work repo onto my personal PC.  In order to do simple "git push origin master" commits without entering my username and password the whole time I simply want to add my public key from my home pc to the work repo.  However Github gives this error:

Error: Key already use

After a bit of Googling I came across this link which states "To resolve the issue, remove the key from the other account or repository and add it to your account"  Of course there is a duplicate key as I've added my home public key to github so that I can code on my own personal projects. After all I want to be able to code to my work repo using both my work pc and personal pc.

How can you add multiple "same" public keys without Github throwing that error and also why in the world, is that error thrown in the first place?

Body:
I've found a workaround that works for me:

You cannot add the same SSH key to different accounts, and that is true for GitHub, BitBucket, etc. But you can use different SSH keys for each account. The only downside then is how to easily switch between them?

I use ssh-agent and it can use multiple keys at the same time. I auto add them through .bashrc

if [ -z "$SSH_AUTH_SOCK" ] ; then
  eval `ssh-agent -s`
  ssh-add ~/.ssh/id_rsa
  ssh-add ~/.ssh/id_rsa2
fi

This approach works regardless of which key is added in your GitHub account. I guess ssh-agent makes attempts with each key until it succeeds. And if you don't want to add all keys, you just comment out the relevant line in the .bashrc before starting a new shell.


问:
FLUTTER Firestore Creates a new document when merge is used to updata a field
Iam trying to update a field in the document using merge:true.
it fails to update the document not only that i creates a duplicate document of same documentID with only the updated field
 Code

```<code>    await Firestore.instance
    .collection('QuizProfile')
    .document(id)
    .setData({
  'Score': ['asdfg'],
}, merge: true);
}
</code>```

adding a screenshot here

答:
setData with merge:true will update fields in the document or create it if it doesn’t exists while updateData will update fields but will fail if the document doesn’t exist

If the id is equal to the original document id in firestore, then you can use updateData:

```<code>   await Firestore.instance
    .collection('QuizProfile')
    .document(id)
    .updateData({
  'Score': ['asdfg'],
});
}
</code>```

Body:
Iam trying to update a field in the document using merge:true.
it fails to update the document not only that i creates a duplicate document of same documentID with only the updated field
 Code

    await Firestore.instance
    .collection('QuizProfile')
    .document(id)
    .setData({
  'Score': ['asdfg'],
}, merge: true);
}

adding a screenshot here

Body:
setData with merge:true will update fields in the document or create it if it doesn’t exists while updateData will update fields but will fail if the document doesn’t exist

If the id is equal to the original document id in firestore, then you can use updateData:

   await Firestore.instance
    .collection('QuizProfile')
    .document(id)
    .updateData({
  'Score': ['asdfg'],
});
}


问:
How to display a user avatar using the file storage symbolic link?
I'm trying to display the user avatar that is uploaded by the user. The image is being saved on the server But whenever i try to display it gives a 404 not found error.

I'm saving the image using this :

```<code>$path = $request->file('image')->store('avatars');
</code>```

I already created a symbolic link using the php artisan storage:link command as the documentation suggests

My HTML:

```<code>@if(config('adminlte.usermenu_image'))
        <img src="{{ Auth::user()->adminlte_image() }}"
             class="user-image img-circle elevation-2"
             alt="{{ Auth::user()->name }}">
    @endif
</code>```

I'm using the Laravel-adminLTE package and using the function below to send the image URL to the view

```<code>public function adminlte_image()
{
    return Storage::url($this->avatar);
}
</code>```

My folders:

The Error:

```<code> http://localhost:8000/storage/avatars/S8Npk86Zun9FAYBREgxgOh9Ye6xiHVhyAmm3Vhb1.jpeg 404 (Not Found)
</code>```

filesystems.php:

```<code>'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
</code>```

I already look several questions here in SO about the symbolic link but i couldnt find the answer.  I'm clearly missing something here, any help will be appreciated.

答:
The problem was that i was storing the image in the wrong disk. My filesystems.php was pointing to the /public directory. And i stored the image in /avatars.

Changing the path to :

```<code>'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public/avatars'),
</code>```

And the storage method to :

```<code>$path = $request->file('imagem')->store('public/avatars');
</code>```

Solved the problem

Body:
I'm trying to display the user avatar that is uploaded by the user. The image is being saved on the server But whenever i try to display it gives a 404 not found error.

I'm saving the image using this :

$path = $request->file('image')->store('avatars');

I already created a symbolic link using the php artisan storage:link command as the documentation suggests

My HTML:

@if(config('adminlte.usermenu_image'))
        adminlte_image() }}"
             class="user-image img-circle elevation-2"
             alt="{{ Auth::user()->name }}">
    @endif

I'm using the Laravel-adminLTE package and using the function below to send the image URL to the view

public function adminlte_image()
{
    return Storage::url($this->avatar);
}

My folders:

The Error:

 http://localhost:8000/storage/avatars/S8Npk86Zun9FAYBREgxgOh9Ye6xiHVhyAmm3Vhb1.jpeg 404 (Not Found)

filesystems.php:

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

I already look several questions here in SO about the symbolic link but i couldnt find the answer.  I'm clearly missing something here, any help will be appreciated.

Body:
The problem was that i was storing the image in the wrong disk. My filesystems.php was pointing to the /public directory. And i stored the image in /avatars.

Changing the path to :

'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public/avatars'),

And the storage method to :

$path = $request->file('imagem')->store('public/avatars');

Solved the problem


问:
Can someone explain this regular expression?
```<code>(.*)([0-9]{6})|(.*)([0-9]{4})
</code>```

<p>Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ? </p>

答:
the expr says:

```<code>(.*) take any number of arbitrary characters followed by ([0-9]{6}) six numbers
</code>```

-OR-

```<code>(.*) take any number of arbitrary characters followed by ([0-9]{4}) four numbers
</code>```

Body:
(.*)([0-9]{6})|(.*)([0-9]{4})

Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ?

Body:
the expr says:

(.*) take any number of arbitrary characters followed by ([0-9]{6}) six numbers

-OR-

(.*) take any number of arbitrary characters followed by ([0-9]{4}) four numbers


问:
NiFi 1.10.0 - PutFile does not see the destination directory
We are facing a peculiar problem on one of our 2 environments. A PutFile processor throws the following error

```<code>PutFile[id=xxx] Penalizing StandardFlowFileRecord[uuid=xxx,claim=StandardContentClaim [resourceClaim=StandardResourceClaim[id=xxx, container=default, section=1012], offset=94495, length=9778],offset=0,name=xxxxxxxxxxxxxxxx_PROD_20200513020001.json.gz,size=9778] and routing to 'failure' because the output directory /data/home/datadelivery/OUT/Test does not exist and Processor is configured not to create missing directories
</code>```

After enabling the creation of missing directories, the error changes to:

```<code>Could not set create directory with permissions 664 because /data/home/datadelivery/OUT/Test: java.nio.file.AccessDeniedException: /data/home/datadelivery/OUT/TestPutFile[id=xxx...
</code>```

Based on the error message one would think that it is an issue with file and folder permissions, however, the path /data/home/datadelivery/OUT/Test exists, and the nifi user can access and create files and folders in there as well (verified from the command line). The same folder permissions and ownership rights are configured on our DEV environment, where the PutFile processor works as expected. We could change the configuration to use a different location, but I'd rather find the root cause instead.

Where should I start debugging?

Thank you for your help in advance!
Kind regards, Julius

答: Strange issue, I would try to set full permission on the folder/file you want to write (ie chmod 777 + chown nifi:nifi + recursively), and see if the error is still there. If not it's kind of a start ...</p>

Body:
We are facing a peculiar problem on one of our 2 environments. A PutFile processor throws the following error

PutFile[id=xxx] Penalizing StandardFlowFileRecord[uuid=xxx,claim=StandardContentClaim [resourceClaim=StandardResourceClaim[id=xxx, container=default, section=1012], offset=94495, length=9778],offset=0,name=xxxxxxxxxxxxxxxx_PROD_20200513020001.json.gz,size=9778] and routing to 'failure' because the output directory /data/home/datadelivery/OUT/Test does not exist and Processor is configured not to create missing directories

After enabling the creation of missing directories, the error changes to:

Could not set create directory with permissions 664 because /data/home/datadelivery/OUT/Test: java.nio.file.AccessDeniedException: /data/home/datadelivery/OUT/TestPutFile[id=xxx...

Based on the error message one would think that it is an issue with file and folder permissions, however, the path /data/home/datadelivery/OUT/Test exists, and the nifi user can access and create files and folders in there as well (verified from the command line). The same folder permissions and ownership rights are configured on our DEV environment, where the PutFile processor works as expected. We could change the configuration to use a different location, but I'd rather find the root cause instead.

Where should I start debugging?

Thank you for your help in advance!
Kind regards, Julius


问:
PowerShell Sort-Object -top -bottom -stable Sort
I'm trying to get the -top and -bottom parameters to work when using the Sort-Object cmdlet, I'd love some feedback about example 9 in the link, Using Stable Sorts
I thought it would be similar to the Select-Object parameters, -First 5, -last 5
I was Wrong! </p>

```<code>PS C:\Users\NiceTry5> 1..20 | sort-object -bottom 5
Sort-Object : A parameter cannot be found that matches parameter name 'bottom'.
At line:1 char:21
+ 1..20 | sort-object -bottom 5
+                     ~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Sort-Object], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SortObjec
   tCommand
</code>```

答:
If you are getting this error:

```<code>Sort-Object : A parameter cannot be found that matches parameter name 'Top'
</code>```

it is probably because you are using PowerShell 5.x.

Check PowerShell version using command:

```<code>Get-Host | Select-Object Version
</code>```

Download and install msi for releases. Note that it does not replace built-in PowerShell so you might have to run it from install location manually.

Body:
I'm trying to get the -top and -bottom parameters to work when using the Sort-Object cmdlet, I'd love some feedback about example 9 in the link, Using Stable Sorts
I thought it would be similar to the Select-Object parameters, -First 5, -last 5
I was Wrong!

PS C:\Users\NiceTry5> 1..20 | sort-object -bottom 5
Sort-Object : A parameter cannot be found that matches parameter name 'bottom'.
At line:1 char:21
+ 1..20 | sort-object -bottom 5
+                     ~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Sort-Object], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SortObjec
   tCommand

Body:
If you are getting this error:

Sort-Object : A parameter cannot be found that matches parameter name 'Top'

it is probably because you are using PowerShell 5.x.

Check PowerShell version using command:

Get-Host | Select-Object Version

Download and install msi for releases. Note that it does not replace built-in PowerShell so you might have to run it from install location manually.


问:
powershell - split csv into multiple csv by column
I have .csv like that:

but many more lines of course.. (sorry I have added it like picture because text was not able to be formatted correctly)

and I would like to have 4 .csv files like which contains every column separatelly so in x.csv, I will only have data from first column. in y.csv I will have only data from second column (they are separated by ";"

so far I have this code but I'm not able to even loop through columns (looping through rows works..)

```<code>$dataaa = Import-Csv ".\input.csv" -Delimiter ";" | Group ID | %{
    $ID=".\out.csv" -f $_.Name
    $_.Group | export-csv "$CurDir\$ID" -NoType
}

$a=0
echo "$a"

$Results = foreach( $Column in $dataaa ){
$a=$a+1
echo "$a" #echo number of column
#select first column and export into x.csv - have NO idea how to
}

echo "$a"
</code>```

thank you for your help

答:
Its should be straight forward:

1.) Import the data with import-csv into a variable e.g. $tmp (dont forget to set the  delimter correctly

2.) Select the property with $tmp | Select-Object -Property Position x...

3.) Export the selected data with export csv (and maybe the parameter notypeinformation)

Body:
I have .csv like that:

but many more lines of course.. (sorry I have added it like picture because text was not able to be formatted correctly)

and I would like to have 4 .csv files like which contains every column separatelly so in x.csv, I will only have data from first column. in y.csv I will have only data from second column (they are separated by ";"

so far I have this code but I'm not able to even loop through columns (looping through rows works..)

$dataaa = Import-Csv ".\input.csv" -Delimiter ";" | Group ID | %{
    $ID=".\out.csv" -f $_.Name
    $_.Group | export-csv "$CurDir\$ID" -NoType
}

$a=0
echo "$a"

$Results = foreach( $Column in $dataaa ){
$a=$a+1
echo "$a" #echo number of column
#select first column and export into x.csv - have NO idea how to
}

echo "$a"

thank you for your help


问:
AutoLisp 2021 Too few arguments error on (apply (lambda
We have installed the latest Autodesk 2021 and one of our scripts (a modified @Lee Mac) which strips and formats some input text now fails. This script runs perfectly on 2019 and below. I can't seem to work out why there is a difference.

I have substituted the original "vl-catch-all-apply" to "apply" so I could catch the error. The error is:

```<code>Too few arguments
</code>```

This occurs as it hits the '(lambda function call. The code is below with the call:

```<code>(defun GDD:removeinfo (rgx str)
(if
    (null
        (vl-catch-all-error-p
            (setq str
                (apply
                   '(lambda nil
                        (vlax-put-property rgx 'global     actrue)
                        (vlax-put-property rgx 'multiline  actrue)
                        (vlax-put-property rgx 'ignorecase acfalse)
                        (foreach pair
                           '(
                                ("\032"     . "\\\\\\\\")
                                ("\n"        . "\\\\P")
                                ("$1"       . "\\\\(\\\\[ACcFfHKkLlOopQTW])|\\\\[ACcFfHKkLlOopQTW][^\\\\;]*;|\\\\[ACcFfKkHLlOopQTW]")
                                ("$1$2/$3"  . "([^\\\\])\\\\S([^;]*)[/#\\^]([^;]*);")
                                ("$1$2"     . "\\\\(\\\\S)|[\\\\](})|}")
                                ("$1"       . "[\\\\]({)|{")
                                ("\\$1$2$3" . "(\\\\[ACcFfHKkLlOoPpQSTW])|({)|(})")
                                ("\\\\"     . "\032")
                                (""     . "(?:.*\\n)*Const\\s+.*\\n")
                                        (""     . "\\w\\w\\d?\\s+\\d+\\s\\d+-\\d+-\\d+")
                                        (""     . "^\\s+\\n")
                            )
                            (vlax-put-property rgx 'pattern (cdr pair))
                            (setq str (vlax-invoke rgx 'replace str (car pair)))
                        )
                    )
                )
            )
        )
    )
    str
)
)
</code>```

The call to this function is below. I've checked the "input" and it is identical to the 2019 version that works and the str is populated properly using the vlisp (vscode) debugger. I've run the same code and input through both and only the 2021 version fails?

```<code>(setq input (GDD:removeinfo (vlax-get-or-create-object "VBScript.RegExp") input))
</code>```

I'm not that familiar with LISP and I'm stuck. Thanks for your help.

答:
Whoever wrote that code seemed not to be aware of the progn operator.

So that is to say, if we want to evaluate multiple expressions e1, e2, ... for the sake of a side effect that they produce, we do not have to do this:

```<code>;; wrap expressions in a dummy lambda and apply empty arg list to it
(apply (lambda () e1 e2 ...) nil)
</code>```

We can just write this:

```<code>(progn e1 e2 ...)
</code>```

That still leaves us with a strange code smell which looks like this:

```<code>(setq str (progn .... (setq str value)))
</code>```

The code is assigning the variable str twice with the same value. The deeply nested (setq str value) puts value into str and then yields that value as a result. It's the last expression of the progn (originall, of the lambda) and so that value is also returned.  Then the outer setq wastefully stores it in str again. We just need one or the other:

```<code>;; set str as the side effect of the last form in the
;; progn; also yield that value.
(progn e1 e2 ...(setq str value))

;; assign value yielded from progn to str, then also
;; yield that value.
(setq str (progn e1 e2 ... value))
</code>```

Body:
We have installed the latest Autodesk 2021 and one of our scripts (a modified @Lee Mac) which strips and formats some input text now fails. This script runs perfectly on 2019 and below. I can't seem to work out why there is a difference.

I have substituted the original "vl-catch-all-apply" to "apply" so I could catch the error. The error is:

Too few arguments

This occurs as it hits the '(lambda function call. The code is below with the call:

(defun GDD:removeinfo (rgx str)
(if
    (null
        (vl-catch-all-error-p
            (setq str
                (apply
                   '(lambda nil
                        (vlax-put-property rgx 'global     actrue)
                        (vlax-put-property rgx 'multiline  actrue)
                        (vlax-put-property rgx 'ignorecase acfalse)
                        (foreach pair
                           '(
                                ("\032"     . "\\\\\\\\")
                                ("\n"        . "\\\\P")
                                ("$1"       . "\\\\(\\\\[ACcFfHKkLlOopQTW])|\\\\[ACcFfHKkLlOopQTW][^\\\\;]*;|\\\\[ACcFfKkHLlOopQTW]")
                                ("$1$2/$3"  . "([^\\\\])\\\\S([^;]*)[/#\\^]([^;]*);")
                                ("$1$2"     . "\\\\(\\\\S)|[\\\\](})|}")
                                ("$1"       . "[\\\\]({)|{")
                                ("\\$1$2$3" . "(\\\\[ACcFfHKkLlOoPpQSTW])|({)|(})")
                                ("\\\\"     . "\032")
                                (""     . "(?:.*\\n)*Const\\s+.*\\n")
                                        (""     . "\\w\\w\\d?\\s+\\d+\\s\\d+-\\d+-\\d+")
                                        (""     . "^\\s+\\n")
                            )
                            (vlax-put-property rgx 'pattern (cdr pair))
                            (setq str (vlax-invoke rgx 'replace str (car pair)))
                        )
                    )
                )
            )
        )
    )
    str
)
)

The call to this function is below. I've checked the "input" and it is identical to the 2019 version that works and the str is populated properly using the vlisp (vscode) debugger. I've run the same code and input through both and only the 2021 version fails?

(setq input (GDD:removeinfo (vlax-get-or-create-object "VBScript.RegExp") input))

I'm not that familiar with LISP and I'm stuck. Thanks for your help.

Body:
Whoever wrote that code seemed not to be aware of the progn operator.

So that is to say, if we want to evaluate multiple expressions e1, e2, ... for the sake of a side effect that they produce, we do not have to do this:

;; wrap expressions in a dummy lambda and apply empty arg list to it
(apply (lambda () e1 e2 ...) nil)

We can just write this:

(progn e1 e2 ...)

That still leaves us with a strange code smell which looks like this:

(setq str (progn .... (setq str value)))

The code is assigning the variable str twice with the same value. The deeply nested (setq str value) puts value into str and then yields that value as a result. It's the last expression of the progn (originall, of the lambda) and so that value is also returned.  Then the outer setq wastefully stores it in str again. We just need one or the other:

;; set str as the side effect of the last form in the
;; progn; also yield that value.
(progn e1 e2 ...(setq str value))

;; assign value yielded from progn to str, then also
;; yield that value.
(setq str (progn e1 e2 ... value))


问:
How can I convert an XML without attributes to C# properties?
I'm having trouble converting my XML to a C# object.

My XML looks like this:

```<code><metadata>
<item name="Date" type="xs:date"/>
<item name="Hour" type="xs:time"/>
<item name="Group" type="xs:string" length="12"/>
<item name="Status" type="xs:string" length="18"/>
</metadata>
<data>
<row>
<value>2020-05-08</value>
<value>14:00:01</value>
<value>A</value>
<value>Active</value>
</row>
<row>
<value>2020-05-08</value>
<value>14:00:01</value>
<value>B</value>
<value>Inactive</value>
</row>
</data>
</metadata>
</code>```

I want to map the XML to a c# object that looks like this

```<code>public class GroupDto

    {
        public string Date { get; set; }
        public string Hour { get; set; }
        public string Group { get; set; }
        public string Status { get; set; }
    }
</code>```

(the date and hour can be a string, no problem)
 I'm using JsonConvert.SerializeXmlNode(doc), but it's giving me this result:

```<code>   "data": {
      "row": [
         {
            "value": [
               "2020-05-08",
               "14:00:01",
               "A",
               "Active"
            ]
         },
....
</code>```

I like to map the "values" to the corresponding properties of the C# object.
Is there a propper way to achieve this with an XML in this weird format?

答:
If you don't trust the order of the properties, you can try something like this:

```<code>var metadata = doc.Root.Element("metadata");

var mapper = metadata.Elements("item")
    .Select((i, c) => new { Property = i.Attribute("name").Value, Index = c })
    .ToDictionary(i => i.Property, i => i.Index);

var rows = doc.Root.Element("data").Elements("row").Select(r => new GroupDto
{
    Date = r.Elements("value").ElementAt(mapper[nameof(GroupDto.Date)]).Value,
    Hour = r.Elements("value").ElementAt(mapper[nameof(GroupDto.Hour)]).Value,
    Group = r.Elements("value").ElementAt(mapper[nameof(GroupDto.Group)]).Value,
    Status = r.Elements("value").ElementAt(mapper[nameof(GroupDto.Status)]).Value,
}).ToList();
</code>```

It might not be the most optimal solution, but it gives you what you want in a not-so-complex way.

On top of that, if your properties in your xml wouldn't match the properties of your DTO object, you can always introduce an additional mapping layer. For example:

```<code>var metaMapper = metadata.Elements(ns + "item")
    .Select((i, c) => new { Property = i.Attribute("name").Value, Index = c })
    .ToDictionary(i => i.Property, i => i.Index);

var metaPropertyMapper = new Dictionary<string, string>
{
    {  nameof(GroupDto.Date),  "DateInXML" },
    {  nameof(GroupDto.Hour),  "HourInXML" },
    {  nameof(GroupDto.Group), "GroupInXML" },
    {  nameof(GroupDto.Status), "StatusInXML" },
};

var rows = doc.Root.Element(ns + "data").Elements(ns + "row").Select(r => new GroupDto
{
    Date = r.Elements(ns + "value").ElementAt(metaMapper[metaPropertyMapper[nameof(GroupDto.Date)]]).Value,
    Hour = r.Elements(ns + "value").ElementAt(metaMapper[metaPropertyMapper[nameof(GroupDto.Hour)]]).Value,
    Group = r.Elements(ns + "value").ElementAt(metaMapper[metaPropertyMapper[nameof(GroupDto.Group)]]).Value,
    Status = r.Elements(ns + "value").ElementAt(metaMapper[metaPropertyMapper[nameof(GroupDto.Status)]]).Value,
}).ToList();
</code>```

Body:
I'm having trouble converting my XML to a C# object.

My XML looks like this:

<metadata>
<item name="Date" type="xs:date"/>
<item name="Hour" type="xs:time"/>
<item name="Group" type="xs:string" length="12"/>
<item name="Status" type="xs:string" length="18"/>
</metadata>
<data>
<row>
<value>2020-05-08</value>
<value>14:00:01</value>
<value>A</value>
<value>Active</value>
</row>
<row>
<value>2020-05-08</value>
<value>14:00:01</value>
<value>B</value>
<value>Inactive</value>
</row>
</data>
</metadata>

I want to map the XML to a c# object that looks like this

public class GroupDto

    {
        public string Date { get; set; }
        public string Hour { get; set; }
        public string Group { get; set; }
        public string Status { get; set; }
    }

(the date and hour can be a string, no problem)
 I'm using JsonConvert.SerializeXmlNode(doc), but it's giving me this result:

   "data": {
      "row": [
         {
            "value": [
               "2020-05-08",
               "14:00:01",
               "A",
               "Active"
            ]
         },
....

I like to map the "values" to the corresponding properties of the C# object.
Is there a propper way to achieve this with an XML in this weird format?

Body:
If you don't trust the order of the properties, you can try something like this:

var metadata = doc.Root.Element("metadata");

var mapper = metadata.Elements("item")
    .Select((i, c) => new { Property = i.Attribute("name").Value, Index = c })
    .ToDictionary(i => i.Property, i => i.Index);

var rows = doc.Root.Element("data").Elements("row").Select(r => new GroupDto
{
    Date = r.Elements("value").ElementAt(mapper[nameof(GroupDto.Date)]).Value,
    Hour = r.Elements("value").ElementAt(mapper[nameof(GroupDto.Hour)]).Value,
    Group = r.Elements("value").ElementAt(mapper[nameof(GroupDto.Group)]).Value,
    Status = r.Elements("value").ElementAt(mapper[nameof(GroupDto.Status)]).Value,
}).ToList();

It might not be the most optimal solution, but it gives you what you want in a not-so-complex way.

On top of that, if your properties in your xml wouldn't match the properties of your DTO object, you can always introduce an additional mapping layer. For example:

var metaMapper = metadata.Elements(ns + "item")
    .Select((i, c) => new { Property = i.Attribute("name").Value, Index = c })
    .ToDictionary(i => i.Property, i => i.Index);

var metaPropertyMapper = new Dictionary<string, string>
{
    {  nameof(GroupDto.Date),  "DateInXML" },
    {  nameof(GroupDto.Hour),  "HourInXML" },
    {  nameof(GroupDto.Group), "GroupInXML" },
    {  nameof(GroupDto.Status), "StatusInXML" },
};

var rows = doc.Root.Element(ns + "data").Elements(ns + "row").Select(r => new GroupDto
{
    Date = r.Elements(ns + "value").ElementAt(metaMapper[metaPropertyMapper[nameof(GroupDto.Date)]]).Value,
    Hour = r.Elements(ns + "value").ElementAt(metaMapper[metaPropertyMapper[nameof(GroupDto.Hour)]]).Value,
    Group = r.Elements(ns + "value").ElementAt(metaMapper[metaPropertyMapper[nameof(GroupDto.Group)]]).Value,
    Status = r.Elements(ns + "value").ElementAt(metaMapper[metaPropertyMapper[nameof(GroupDto.Status)]]).Value,
}).ToList();


问:
Stacked barplot in UpSetR
I have been looking for a way of having a stacked bar plot in an upsetR graph.
I downloaded the movies data set (from here) and added a column having only two values "M" and "C".
Below, information on how I loaded the data and added the "x" column.

Edit:

```<code>m <- read.csv(system.file("extdata", "movies.csv", package = "UpSetR"),
                           header = T, sep = ";")
nrow(m)
[1] 3883
x<-c(rep("M", 3000), rep("C", 883))
m<-cbind(m, x)
unique(m$x)
[1] M C
</code>```

This is the structure of the data frame:

```<code>str(m)
'data.frame':   3883 obs. of  22 variables:
 $ Name       : Factor w/ 3883 levels "$1,000,000 Duck (1971)",..: 3577 1858 1483 3718 1175 1559 3010 3548 3363 1420 ...
 $ ReleaseDate: int  1995 1995 1995 1995 1995 1995 1995 1995 1995 1995 ...
 $ Action     : int  0 0 0 0 0 1 0 0 1 1 ...
 $ Adventure  : int  0 1 0 0 0 0 0 1 0 1 ...
 $ Children   : int  1 1 0 0 0 0 0 1 0 0 ...
 $ Comedy     : int  1 0 1 1 1 0 1 0 0 0 ...
 $ Crime      : int  0 0 0 0 0 1 0 0 0 0 ...
 $ Documentary: int  0 0 0 0 0 0 0 0 0 0 ...
 $ Drama      : int  0 0 0 1 0 0 0 0 0 0 ...
 $ Fantasy    : int  0 1 0 0 0 0 0 0 0 0 ...
 $ Noir       : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Horror     : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Musical    : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Mystery    : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Romance    : int  0 0 1 0 0 0 1 0 0 0 ...
 $ SciFi      : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Thriller   : int  0 0 0 0 0 1 0 0 0 1 ...
 $ War        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Western    : int  0 0 0 0 0 0 0 0 0 0 ...
 $ AvgRating  : num  4.15 3.2 3.02 2.73 3.01 3.88 3.41 3.01 2.66 3.54 ...
 $ Watches    : int  2077 701 478 170 296 940 458 68 102 888 ...
 $ x          : Factor w/ 2 levels "M","C": 1 1 1 1 1 1 1 1 1 1 ...
</code>```

Now I tried to implement the stacked bar plot as follow:

```<code>upset(m,
  queries = list(
    list(query = elements,
         params = list("x", "M"), color = "#e69f00", active = T),
    list(query = elements,
         params = list("x", "C"), color = "#cc79a7", active = T)))
</code>```

The result looks like this:

As you can see the proportions are wrong as there should be in each bar only two colors (factor) either "M" or "C".
This issue seems to be not a trivial one, as also pointed out here.
Does anyone have an idea on how to implement this in UpsetR?
Thanks a lot

答:
Here is a way to create an upset plot with stacked barplot, but using my ComplexUpset rather than UpSetR:

```<code>library(ComplexUpset)
movies = as.data.frame(ggplot2movies::movies)
genres = colnames(movies)[18:24]

# for simplicity of examples, only use the complete data points
movies[movies$mpaa == '', 'mpaa'] = NA
movies = na.omit(movies)

upset(
    movies,
    genres,
    base_annotations=list(
        'Intersection size'=intersection_size(
            counts=FALSE,
            mapping=aes(fill=mpaa)
        )
    ),
    width_ratio=0.1
)
</code>```

Please see more examples in the documentation.
The Installation instructions are available on GitHub: krassowski/complex-upset (there is also a comparison to UpSetR and other packages).

Title: Stacked barplot in UpSetR

Body:
I have been looking for a way of having a stacked bar plot in an upsetR graph.
I downloaded the movies data set (from here) and added a column having only two values "M" and "C".
Below, information on how I loaded the data and added the "x" column.

Edit:

m <- read.csv(system.file("extdata", "movies.csv", package = "UpSetR"),
                           header = T, sep = ";")
nrow(m)
[1] 3883
x<-c(rep("M", 3000), rep("C", 883))
m<-cbind(m, x)
unique(m$x)
[1] M C

This is the structure of the data frame:

str(m)
'data.frame':   3883 obs. of  22 variables:
 $ Name       : Factor w/ 3883 levels "$1,000,000 Duck (1971)",..: 3577 1858 1483 3718 1175 1559 3010 3548 3363 1420 ...
 $ ReleaseDate: int  1995 1995 1995 1995 1995 1995 1995 1995 1995 1995 ...
 $ Action     : int  0 0 0 0 0 1 0 0 1 1 ...
 $ Adventure  : int  0 1 0 0 0 0 0 1 0 1 ...
 $ Children   : int  1 1 0 0 0 0 0 1 0 0 ...
 $ Comedy     : int  1 0 1 1 1 0 1 0 0 0 ...
 $ Crime      : int  0 0 0 0 0 1 0 0 0 0 ...
 $ Documentary: int  0 0 0 0 0 0 0 0 0 0 ...
 $ Drama      : int  0 0 0 1 0 0 0 0 0 0 ...
 $ Fantasy    : int  0 1 0 0 0 0 0 0 0 0 ...
 $ Noir       : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Horror     : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Musical    : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Mystery    : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Romance    : int  0 0 1 0 0 0 1 0 0 0 ...
 $ SciFi      : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Thriller   : int  0 0 0 0 0 1 0 0 0 1 ...
 $ War        : int  0 0 0 0 0 0 0 0 0 0 ...
 $ Western    : int  0 0 0 0 0 0 0 0 0 0 ...
 $ AvgRating  : num  4.15 3.2 3.02 2.73 3.01 3.88 3.41 3.01 2.66 3.54 ...
 $ Watches    : int  2077 701 478 170 296 940 458 68 102 888 ...
 $ x          : Factor w/ 2 levels "M","C": 1 1 1 1 1 1 1 1 1 1 ...

Now I tried to implement the stacked bar plot as follow:

upset(m,
  queries = list(
    list(query = elements,
         params = list("x", "M"), color = "#e69f00", active = T),
    list(query = elements,
         params = list("x", "C"), color = "#cc79a7", active = T)))

The result looks like this:

As you can see the proportions are wrong as there should be in each bar only two colors (factor) either "M" or "C".
This issue seems to be not a trivial one, as also pointed out here.
Does anyone have an idea on how to implement this in UpsetR?
Thanks a lot

Body:
Here is a way to create an upset plot with stacked barplot, but using my ComplexUpset rather than UpSetR:

library(ComplexUpset)
movies = as.data.frame(ggplot2movies::movies)
genres = colnames(movies)[18:24]

# for simplicity of examples, only use the complete data points
movies[movies$mpaa == '', 'mpaa'] = NA
movies = na.omit(movies)

upset(
    movies,
    genres,
    base_annotations=list(
        'Intersection size'=intersection_size(
            counts=FALSE,
            mapping=aes(fill=mpaa)
        )
    ),
    width_ratio=0.1
)

Please see more examples in the documentation.
The Installation instructions are available on GitHub: krassowski/complex-upset (there is also a comparison to UpSetR and other packages).


问:
Apache Royale : addEventListener / removeEventListener best practice
In Flex, the best practice when using a addEventListener was to call removeEventListener to avoid memory leak and/or event to be called twice if component could be created many times (like popups)

So addEventListener was mainly used in addedToStage event function and removeEventListener was in removedFromStage event function

What is the best practice for Apache Royale ?

It seem that addEventListener should be in a initComplete event. But as Apache Royale component life cycle is not very clear for me, does I need to take care of calling removeEventListener, and if yes when (with a specific event ?) ?

Regards

答: I think the same applies like in Flex. But you just should be care of remove listeners when you create components and can be removed eventually. Like in Flex if the object instance will be created just one time and is permanent through the session, you don't need to worry about it.</p>


问:
Save GIF file to storage
I want to save a GIF file (in android app) in internal or external storage. The file should then be found in the gallery. I downloaded the gif file via glide:</p>

```<code>    Glide.with(getContext())
    .download(imageUrl)
    .listener(new RequestListener<File>() {
    @Override
    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
return false;
}
 @RequiresApi(api = Build.VERSION_CODES.O)
@Override
public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
}
return false;

    }
                                                        })
                                                        .submit();
</code>```

答:
your use ftech

```<code>implementation "com.tonyodev.fetch2:fetch2:3.0.10"
</code>```

Androidx use:

```<code>implementation "androidx.tonyodev.fetch2:xfetch2:3.1.4"
</code>```

download any file

```<code>    if (isStoragePermissionGranted()) {
                    fetch = Fetch.Impl.getInstance(fetchConfiguration);

                    String url = nameFileDownload;

                    String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + nameFileDownload.substring(url.lastIndexOf('/') + 1);
                    ;

                    if (fileExist(file)) {
                        view(null, nameFileDownload.substring(url.lastIndexOf('/') + 1));

                    } else {
                        progress_download.setVisibility(View.VISIBLE);
                        btn_download.setVisibility(View.GONE);
                        final com.tonyodev.fetch2.Request request = new com.tonyodev.fetch2.Request(url, file);
                        request.setPriority(Priority.NORMAL);
                        request.setNetworkType(NetworkType.ALL);

                        fetch.enqueue(request, updatedRequest -> {

                            fetch.addListener(fetchListener);

                            //Request was successfully enqueued for download.
                        }, error -> {
                            progress_download.setVisibility(View.GONE);
                            btn_download.setVisibility(View.VISIBLE);
                            Toast.makeText(MainActivity.this, "feild", Toast.LENGTH_SHORT).show();

                            //An error occurred enqueuing the request.
                        });
                    }

                } else {
                    Toast.makeText(MainActivity.this, "perssion denid", Toast.LENGTH_SHORT).show();
                }

            }
</code>```

isStoragePermissionGranted:

```<code> public boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("TAG", "Permission is granted");
            return true;
        } else {

            Log.v("TAG", "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v("TAG", "Permission is granted");
        return true;
    }
}
</code>```

manifests:

```<code>   <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</code>```

Title: Save GIF file to storage

Body:
I want to save a GIF file (in android app) in internal or external storage. The file should then be found in the gallery. I downloaded the gif file via glide:

    Glide.with(getContext())
    .download(imageUrl)
    .listener(new RequestListener<File>() {
    @Override
    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
return false;
}
 @RequiresApi(api = Build.VERSION_CODES.O)
@Override
public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
}
return false;

    }
                                                        })
                                                        .submit();

Body:
your use ftech

implementation "com.tonyodev.fetch2:fetch2:3.0.10"

Androidx use:

implementation "androidx.tonyodev.fetch2:xfetch2:3.1.4"

download any file

    if (isStoragePermissionGranted()) {
                    fetch = Fetch.Impl.getInstance(fetchConfiguration);

                    String url = nameFileDownload;

                    String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + nameFileDownload.substring(url.lastIndexOf('/') + 1);
                    ;

                    if (fileExist(file)) {
                        view(null, nameFileDownload.substring(url.lastIndexOf('/') + 1));

                    } else {
                        progress_download.setVisibility(View.VISIBLE);
                        btn_download.setVisibility(View.GONE);
                        final com.tonyodev.fetch2.Request request = new com.tonyodev.fetch2.Request(url, file);
                        request.setPriority(Priority.NORMAL);
                        request.setNetworkType(NetworkType.ALL);

                        fetch.enqueue(request, updatedRequest -> {

                            fetch.addListener(fetchListener);

                            //Request was successfully enqueued for download.
                        }, error -> {
                            progress_download.setVisibility(View.GONE);
                            btn_download.setVisibility(View.VISIBLE);
                            Toast.makeText(MainActivity.this, "feild", Toast.LENGTH_SHORT).show();

                            //An error occurred enqueuing the request.
                        });
                    }

                } else {
                    Toast.makeText(MainActivity.this, "perssion denid", Toast.LENGTH_SHORT).show();
                }

            }

isStoragePermissionGranted:

 public boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("TAG", "Permission is granted");
            return true;
        } else {

            Log.v("TAG", "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v("TAG", "Permission is granted");
        return true;
    }
}

manifests:

   <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


问:
Concat multiple lists from a list element for element for the sublist
Given:

```<code>[['A', 'B', 'C'], ['1', '2', '3'], ['Z', 'X']]
</code>```

Is there a way to concatenate every element from the lists in the list for every index 1 to 1 not 1 to many without using a lot of for statements? And the output to be a list with every concatenation as its elements?

Expected output:

```<code>['A1Z','B2X', 'C3']
</code>```

答:
A beginner-friendly solution</p>

```<code>s = [['A', 'B', 'C'], ['1', '2', '3'],['Z', 'X']]
f = []

n = 0
while n != len(s):
    t = ''
    for i in s:
        try: t = t + i[n]
        except IndexError: pass
    f.append(t)

    n = n + 1
print(f)
</code>```

Body:
Given:

[['A', 'B', 'C'], ['1', '2', '3'], ['Z', 'X']]

Is there a way to concatenate every element from the lists in the list for every index 1 to 1 not 1 to many without using a lot of for statements? And the output to be a list with every concatenation as its elements?

Expected output:

['A1Z','B2X', 'C3']

Body:
A beginner-friendly solution

s = [['A', 'B', 'C'], ['1', '2', '3'],['Z', 'X']]
f = []

n = 0
while n != len(s):
    t = ''
    for i in s:
        try: t = t + i[n]
        except IndexError: pass
    f.append(t)

    n = n + 1
print(f)