问:
Quit script if directory already exists
I know this sounds like a stupid question, but I can't get my head around this problem. Basically I want to quit the script only if the folder in the directory already exists but all I get is the blank page with the echo "la cartella esiste" I guess this is because of the exit function. What I want is to have the message displayed on the page itself just like the other errors displayed, but without carrying on with the code. Do you have any suggestion on how to proceed?</p>
```<code><?php

    require('db.php');

    if (isset($_POST['upload'])) {
        $batch_number = stripslashes($_REQUEST['batch_number']);
        $batch_number = mysqli_real_escape_string($con, $batch_number);
        $product_name = stripslashes($_REQUEST['product_name']);
        $product_name = mysqli_real_escape_string($con, $product_name);
        $vial_size = stripslashes($_REQUEST['vial_size']);
        $vial_size = mysqli_real_escape_string($con, $vial_size);
        $Sterile = $_POST['Sterile'];
        $Macchina = $_POST['Macchina'];
        $location = "immagini/$batch_number/";
        $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
        $allowTypes = array('jpg','png','jpeg', 'bmp');
        $img_name = array_filter($_FILES['image']['name']);
        $select = mysqli_query($con, "SELECT * FROM info_flaconi WHERE batch_number = '". $_REQUEST['batch_number']."'");
        if(file_exists($location) && is_dir($location)) {
            exit ("la cartella esiste");

        } else{
            mkdir("immagini/$batch_number/", 0777, true);
            echo "Cartella creata.";

        }

        if(!empty($img_name)){
            foreach($_FILES['image']['tmp_name'] as $key=>$val){
                //file upload path
                $fileName= $_FILES['image']['name'][$key];
                $fileName_tmp= $_FILES['image']['tmp_name'][$key];
                $targetPath = $location .$fileName;
                $ext=strtolower(pathinfo($targetPath, PATHINFO_EXTENSION));
                $uploadDate = date('Y-m-d H:i:s');
                $uploadOk = 1;

                // Check whether file type is valid

                if(in_array($ext, $allowTypes)){
                // Upload file to server
                    if(move_uploaded_file($fileName_tmp, $targetPath)){
                        $sqlVal = $fileName;
                    }  else{
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "File coud not be uploaded.");
                        }
                }else{
                    $response = array(
                    "status" => "alert-danger",
                    "message" => "Only .jpg, .jpeg, .png and bmp file formats allowed.");
                }
                if(!empty($sqlVal)){
                    $query    = "INSERT INTO `info_flaconi` (batch_number, product_name,  vial_size, vial_image, uploaded_on, Sterile_Area, Macchina)
                    VALUES ('$batch_number', '$product_name', '$vial_size', '$sqlVal', '$uploadDate', '$Sterile', '$Macchina')";
                    $result   = mysqli_query($con, $query);
                    if($result){
                        $response = array(
                            "status" => "alert-success",
                            "message" => "Immagini caricate correttamente.");

                    }else{
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "Files coudn't be uploaded due to database error.");
                    }
                }
            }
        }else {
            // Error
            $response = array(
            "status" => "alert-danger",
            "message" => "Per favore seleziona le immagini da caricare.");

        }
    }
    ?>
</code>```
```<code>        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Import Immagini</title>
            <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
            <link rel="stylesheet" href="style_5.css">
        </head>
        <body>
        <header>
            <div class="wrapper">
                <div class="logo">
                    <img src="biotech.png" alt="">
                </div>
        <ul class="nav-area">
        <li><a href="dashboard.php">Home</a></li>
        <li><a href="table/index.html">Contatti</a></li>
        <li><a href="logout.php">Logout</a></li>

        </ul>
        </div>
                <div class="inserimento">
                <h1> Inserisci flaconi da caricare </h1>
                <form action="" method="POST" enctype="multipart/form-data">

                    <input type = "file" name= "image[]"  id="chooseFile" multiple><br>
                    <label> Inserisci numero batch: </label><input type='text' name="batch_number" class='form-control' required placeholder="inserisci batch number"/><br>
                    <label> Inserisci prodotto: </label><input type='text' name="product_name" class='form-control' required placeholder="inserisci nome prodotto "/><br>
                    <label> Inserisci grandezza flacone: </label><input type='text' name="vial_size" class='form-control' required placeholder="inserisci formato flacone"/><br>

                    <select class='form-control' name="Sterile">

                        <option value="" >--Select--</option>
                        <option value="Sterile Area 1" >Sterile Area 1</option>
                        <option value="Sterile Area 2" >Sterile Area 2</option>
                        <option value="Sterile Area 3" >Sterile Area 3</option>
                        <option value="Sterile Area 4" >Sterile Area 4</option>
                        <option value="Sterile Area 5" >Sterile Area 5</option>
                        <option value="Sterile Area 6" >Sterile Area 6</option>
                        <option value="PDS" >PDS</option>
                    </select><br>

                    <select class="form-control" name="Macchina" autofocus="autofocus" required>

                        <option value="" >--Select--</option>
                        <option value="Sedeneider" >Sedeneider</option>
                        <option value="Groheninger" >Groheninger</option>
                        <option value="Optrel400" >Optrel400</option>
                    </select>
                    <input type="submit" name="upload" value="Upload Image/Data"><br>
                </div>

                </form>

                <?php if(!empty($response)) {?>
                <div class="alert <?php echo $response["status"]; ?>">
                   <?php echo $response["message"]; ?>
                </div>
            <?php }?>
        </body>

        </html>

</code>```

答:
It looks like you need to set the $response array for other code (which you haven't shown us) to display a message. One way would be to wrap the code you showed us in a do { ... } while (false) block (where "..." is all the code you showed above), and in the spot where you are currently calling exit(), change it to:

```<code>$response = array(
  "status" => "alert-danger",
  "message" => "la cartella esiste"
);
break;
</code>```

The call to break will exit the loop and continue with the rest of the code that draws the page based on the contents of $response.

Here is your code, modified as described:

<?php
require('db.php');

do { // Begin one-time loop

if (isset($_POST['upload'])) {
    $batch_number = stripslashes($_REQUEST['batch_number']);
    $batch_number = mysqli_real_escape_string($con, $batch_number);
    $product_name = stripslashes($_REQUEST['product_name']);
    $product_name = mysqli_real_escape_string($con, $product_name);
    $vial_size = stripslashes($_REQUEST['vial_size']);
    $vial_size = mysqli_real_escape_string($con, $vial_size);
    $Sterile = $_POST['Sterile'];
    $Macchina = $_POST['Macchina'];
    $location = "immagini/$batch_number/";
    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
    $allowTypes = array('jpg', 'png', 'jpeg', 'bmp');
    $img_name = array_filter($_FILES['image']['name']);
    $select = mysqli_query($con, "SELECT * FROM info_flaconi WHERE batch_number = '" . $_REQUEST['batch_number'] . "'");
    if (file_exists($location) && is_dir($location)) {
        $response = array(
            "status" => "alert-danger",
            "message" => "la cartella esiste"
        );
        break;
    } else {
        mkdir("immagini/$batch_number/", 0777, true);
        echo "Cartella creata.";
    }

    if (!empty($img_name)) {
        foreach ($_FILES['image']['tmp_name'] as $key => $val) {
            //file upload path
            $fileName = $_FILES['image']['name'][$key];
            $fileName_tmp = $_FILES['image']['tmp_name'][$key];
            $targetPath = $location . $fileName;
            $ext = strtolower(pathinfo($targetPath, PATHINFO_EXTENSION));
            $uploadDate = date('Y-m-d H:i:s');
            $uploadOk = 1;

            // Check whether file type is valid

            if (in_array($ext, $allowTypes)) {
                // Upload file to server
                if (move_uploaded_file($fileName_tmp, $targetPath)) {
                    $sqlVal = $fileName;
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "File coud not be uploaded."
                    );
                }
            } else {
                $response = array(
                    "status" => "alert-danger",
                    "message" => "Only .jpg, .jpeg, .png and bmp file formats allowed."
                );
            }
            if (!empty($sqlVal)) {
                $query    = "INSERT INTO `info_flaconi` (batch_number, product_name,  vial_size, vial_image, uploaded_on, Sterile_Area, Macchina)
                VALUES ('$batch_number', '$product_name', '$vial_size', '$sqlVal', '$uploadDate', '$Sterile', '$Macchina')";
                $result   = mysqli_query($con, $query);
                if ($result) {
                    $response = array(
                        "status" => "alert-success",
                        "message" => "Immagini caricate correttamente."
                    );
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "Files coudn't be uploaded due to database error."
                    );
                }
            }
        }
    } else {
        // Error
        $response = array(
            "status" => "alert-danger",
            "message" => "Per favore seleziona le immagini da caricare."
        );
    }
}
} while (false); // Loop will only execute once
?>  ```

Title: Quit script if directory already exists

Body:
I know this sounds like a stupid question, but I can't get my head around this problem. Basically I want to quit the script only if the folder in the directory already exists but all I get is the blank page with the echo "la cartella esiste" I guess this is because of the exit function. What I want is to have the message displayed on the page itself just like the other errors displayed, but without carrying on with the code. Do you have any suggestion on how to proceed?

<?php

    require('db.php');

    if (isset($_POST['upload'])) {
        $batch_number = stripslashes($_REQUEST['batch_number']);
        $batch_number = mysqli_real_escape_string($con, $batch_number);
        $product_name = stripslashes($_REQUEST['product_name']);
        $product_name = mysqli_real_escape_string($con, $product_name);
        $vial_size = stripslashes($_REQUEST['vial_size']);
        $vial_size = mysqli_real_escape_string($con, $vial_size);
        $Sterile = $_POST['Sterile'];
        $Macchina = $_POST['Macchina'];
        $location = "immagini/$batch_number/";
        $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
        $allowTypes = array('jpg','png','jpeg', 'bmp');
        $img_name = array_filter($_FILES['image']['name']);
        $select = mysqli_query($con, "SELECT * FROM info_flaconi WHERE batch_number = '". $_REQUEST['batch_number']."'");
        if(file_exists($location) && is_dir($location)) {
            exit ("la cartella esiste");

        } else{
            mkdir("immagini/$batch_number/", 0777, true);
            echo "Cartella creata.";

        }

        if(!empty($img_name)){
            foreach($_FILES['image']['tmp_name'] as $key=>$val){
                //file upload path
                $fileName= $_FILES['image']['name'][$key];
                $fileName_tmp= $_FILES['image']['tmp_name'][$key];
                $targetPath = $location .$fileName;
                $ext=strtolower(pathinfo($targetPath, PATHINFO_EXTENSION));
                $uploadDate = date('Y-m-d H:i:s');
                $uploadOk = 1;

                // Check whether file type is valid

                if(in_array($ext, $allowTypes)){
                // Upload file to server
                    if(move_uploaded_file($fileName_tmp, $targetPath)){
                        $sqlVal = $fileName;
                    }  else{
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "File coud not be uploaded.");
                        }
                }else{
                    $response = array(
                    "status" => "alert-danger",
                    "message" => "Only .jpg, .jpeg, .png and bmp file formats allowed.");
                }
                if(!empty($sqlVal)){
                    $query    = "INSERT INTO `info_flaconi` (batch_number, product_name,  vial_size, vial_image, uploaded_on, Sterile_Area, Macchina)
                    VALUES ('$batch_number', '$product_name', '$vial_size', '$sqlVal', '$uploadDate', '$Sterile', '$Macchina')";
                    $result   = mysqli_query($con, $query);
                    if($result){
                        $response = array(
                            "status" => "alert-success",
                            "message" => "Immagini caricate correttamente.");

                    }else{
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "Files coudn't be uploaded due to database error.");
                    }
                }
            }
        }else {
            // Error
            $response = array(
            "status" => "alert-danger",
            "message" => "Per favore seleziona le immagini da caricare.");

        }
    }
    ?>

        <!DOCTYPE html>

            <meta charset="UTF-8">
            <title>Import Immagini</title>
            <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
            <link rel="stylesheet" href="style_5.css">

Home

Contatti

Logout

 Inserisci flaconi da caricare

                <form action="" method="POST" enctype="multipart/form-data">

                    <input type = "file" name= "image[]"  id="chooseFile" multiple>

                     Inserisci numero batch: <input type='text' name="batch_number" class='form-control' required placeholder="inserisci batch number"/>

                     Inserisci prodotto: <input type='text' name="product_name" class='form-control' required placeholder="inserisci nome prodotto "/>

                     Inserisci grandezza flacone: <input type='text' name="vial_size" class='form-control' required placeholder="inserisci formato flacone"/>

                    <select class='form-control' name="Sterile">

                        <option value="" >--Select--</option>
                        <option value="Sterile Area 1" >Sterile Area 1</option>
                        <option value="Sterile Area 2" >Sterile Area 2</option>
                        <option value="Sterile Area 3" >Sterile Area 3</option>
                        <option value="Sterile Area 4" >Sterile Area 4</option>
                        <option value="Sterile Area 5" >Sterile Area 5</option>
                        <option value="Sterile Area 6" >Sterile Area 6</option>
                        <option value="PDS" >PDS</option>
                    </select>

                    <select class="form-control" name="Macchina" autofocus="autofocus" required>

                        <option value="" >--Select--</option>
                        <option value="Sedeneider" >Sedeneider</option>
                        <option value="Groheninger" >Groheninger</option>
                        <option value="Optrel400" >Optrel400</option>
                    </select>
                    <input type="submit" name="upload" value="Upload Image/Data">

                </form>

                <?php if(!empty($response)) {?>
                <div class="alert <?php echo $response["status"]; ?>">
                   <?php echo $response["message"]; ?>

            <?php }?>

Body:
It looks like you need to set the $response array for other code (which you haven't shown us) to display a message. One way would be to wrap the code you showed us in a do { ... } while (false) block (where "..." is all the code you showed above), and in the spot where you are currently calling exit(), change it to:

$response = array(
  "status" => "alert-danger",
  "message" => "la cartella esiste"
);
break;

The call to break will exit the loop and continue with the rest of the code that draws the page based on the contents of $response.

Here is your code, modified as described:

<?php
require('db.php');

do { // Begin one-time loop

if (isset($_POST['upload'])) {
    $batch_number = stripslashes($_REQUEST['batch_number']);
    $batch_number = mysqli_real_escape_string($con, $batch_number);
    $product_name = stripslashes($_REQUEST['product_name']);
    $product_name = mysqli_real_escape_string($con, $product_name);
    $vial_size = stripslashes($_REQUEST['vial_size']);
    $vial_size = mysqli_real_escape_string($con, $vial_size);
    $Sterile = $_POST['Sterile'];
    $Macchina = $_POST['Macchina'];
    $location = "immagini/$batch_number/";
    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
    $allowTypes = array('jpg', 'png', 'jpeg', 'bmp');
    $img_name = array_filter($_FILES['image']['name']);
    $select = mysqli_query($con, "SELECT * FROM info_flaconi WHERE batch_number = '" . $_REQUEST['batch_number'] . "'");
    if (file_exists($location) && is_dir($location)) {
        $response = array(
            "status" => "alert-danger",
            "message" => "la cartella esiste"
        );
        break;
    } else {
        mkdir("immagini/$batch_number/", 0777, true);
        echo "Cartella creata.";
    }

    if (!empty($img_name)) {
        foreach ($_FILES['image']['tmp_name'] as $key => $val) {
            //file upload path
            $fileName = $_FILES['image']['name'][$key];
            $fileName_tmp = $_FILES['image']['tmp_name'][$key];
            $targetPath = $location . $fileName;
            $ext = strtolower(pathinfo($targetPath, PATHINFO_EXTENSION));
            $uploadDate = date('Y-m-d H:i:s');
            $uploadOk = 1;

            // Check whether file type is valid

            if (in_array($ext, $allowTypes)) {
                // Upload file to server
                if (move_uploaded_file($fileName_tmp, $targetPath)) {
                    $sqlVal = $fileName;
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "File coud not be uploaded."
                    );
                }
            } else {
                $response = array(
                    "status" => "alert-danger",
                    "message" => "Only .jpg, .jpeg, .png and bmp file formats allowed."
                );
            }
            if (!empty($sqlVal)) {
                $query    = "INSERT INTO `info_flaconi` (batch_number, product_name,  vial_size, vial_image, uploaded_on, Sterile_Area, Macchina)
                VALUES ('$batch_number', '$product_name', '$vial_size', '$sqlVal', '$uploadDate', '$Sterile', '$Macchina')";
                $result   = mysqli_query($con, $query);
                if ($result) {
                    $response = array(
                        "status" => "alert-success",
                        "message" => "Immagini caricate correttamente."
                    );
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "Files coudn't be uploaded due to database error."
                    );
                }
            }
        }
    } else {
        // Error
        $response = array(
            "status" => "alert-danger",
            "message" => "Per favore seleziona le immagini da caricare."
        );
    }
}
} while (false); // Loop will only execute once
?>


来源: stackexchange

问:
Why is node-sass being built when I upgrade from npm6 to npm7?
My app uses sass, not node-sass. node-sass is nowhere in my package-lock.json.

I'm currently using npm 6 and everything is working fine and has been for years.

When I try to npm install with npm 7, it fails with the below error.

What's going on? Maybe node-sass is a dev dependency of something else and being built?

```<code>npm ERR! npm ERR! code 1
npm ERR! npm ERR! path /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-sass
npm ERR! npm ERR! command failed
npm ERR! npm ERR! command sh -c node scripts/build.js
npm ERR! npm ERR! Building: /opt/local/bin/node /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! npm ERR!   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.3.6"' -I/Users/john/.node-gyp/14.18.3/include/node -I/Users/john/.node-gyp/14.18.3/src -I/Users/john/.node-gyp/14.18.3/deps/uv/include -I/Users/john/.node-gyp/14.18.3/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/eval.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/eval.o ../src/libsass/src/eval.cpp
### above line repeated many times
npm ERR! npm ERR!
</code>```

答: You might be using a version of Node or npm that are not compatible with the version of node-sass that is being pulled. node-sass publishes this table that shows the range of supported versions for any toolchain version. If one of your dependencies is pulling node-sass, you could force your desired version by explicitly specifying node-sass as a direct dependency. You could also consider upgrading Node or npm as an alternative.

ContentLicense: CC BY-SA 4.0

Body:
My app uses sass, not node-sass. node-sass is nowhere in my package-lock.json.

I'm currently using npm 6 and everything is working fine and has been for years.

When I try to npm install with npm 7, it fails with the below error.

What's going on? Maybe node-sass is a dev dependency of something else and being built?

npm ERR! npm ERR! code 1
npm ERR! npm ERR! path /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-sass
npm ERR! npm ERR! command failed
npm ERR! npm ERR! command sh -c node scripts/build.js
npm ERR! npm ERR! Building: /opt/local/bin/node /Users/john/.npm/_cacache/tmp/git-clonenbaf30/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! npm ERR!   c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.3.6"' -I/Users/john/.node-gyp/14.18.3/include/node -I/Users/john/.node-gyp/14.18.3/src -I/Users/john/.node-gyp/14.18.3/deps/uv/include -I/Users/john/.node-gyp/14.18.3/deps/v8/include -I../src/libsass/include  -O3 -gdwarf-2 -mmacosx-version-min=10.7 -arch arm64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/eval.o.d.raw   -c -o Release/obj.target/libsass/src/libsass/src/eval.o ../src/libsass/src/eval.cpp
### above line repeated many times
npm ERR! npm ERR!


问:
I wrote a topological sort alg and it's not returning an output
I think my topological sort algorithm is correct, but perhaps my node class isn't working. This is my node class and my main function that creates the graph. When I run this, I get no output. I think it's my class or construction of my graph that went wrong because topSort() returns a list, so if it ran incorrectly, then I'd expect an empty list or a list with the wrong topological sort. This leads me to believe that the issue is in my construction.</p>
```<code>class Node:
    def __init__(self, val = 0, neighbors = None) -> None:
        self.val = val
        self.neighbors = neighbors
    def replaceNeighbors(self, neighbors):
        self.neighbors = neighbors

def dfs(vertex, stack, visited):
    #code

def topSort(graph):
    #code

def main():
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node1.replaceNeighbors([node2, node3])
    node2.replaceNeighbors([node4])
    node4.replaceNeighbors([node3])
    root = Node(0, [node1, node2])
    graph = [root, node1, node2, node3, node4]
    order = topSort(graph)
    print(order)
</code>```

答:
The reason your code is not returning a value is because you are not calling the main() method. You should use the strategy below to accomplish this. Also, a better technique to coming back to methods you declared, but haven't defined is using pass.</p>
```<code>class Node:
    def __init__(self, val, neighbors=None) -> None:
        self.val = val
        self.neighbors = neighbors

    def replaceNeighbors(self, neighbors):
        self.neighbors = neighbors

def dfs(vertex, stack, visited):
    pass

def topSort(graph):
    pass

def main():
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node1.replaceNeighbors([node2, node3])
    node2.replaceNeighbors([node4])
    node4.replaceNeighbors([node3])
    root = Node(0, [node1, node2])
    graph = [root, node1, node2, node3, node4]
    order = topSort(graph)
    print(order)

if __name__ == '__main__':
    main()  # calls main method
</code>```

Body:
I think my topological sort algorithm is correct, but perhaps my node class isn't working. This is my node class and my main function that creates the graph. When I run this, I get no output. I think it's my class or construction of my graph that went wrong because topSort() returns a list, so if it ran incorrectly, then I'd expect an empty list or a list with the wrong topological sort. This leads me to believe that the issue is in my construction.

class Node:
    def __init__(self, val = 0, neighbors = None) -> None:
        self.val = val
        self.neighbors = neighbors
    def replaceNeighbors(self, neighbors):
        self.neighbors = neighbors

def dfs(vertex, stack, visited):
    #code

def topSort(graph):
    #code

def main():
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node1.replaceNeighbors([node2, node3])
    node2.replaceNeighbors([node4])
    node4.replaceNeighbors([node3])
    root = Node(0, [node1, node2])
    graph = [root, node1, node2, node3, node4]
    order = topSort(graph)
    print(order)

Body:
The reason your code is not returning a value is because you are not calling the main() method. You should use the strategy below to accomplish this. Also, a better technique to coming back to methods you declared, but haven't defined is using pass.

class Node:
    def __init__(self, val, neighbors=None) -> None:
        self.val = val
        self.neighbors = neighbors

    def replaceNeighbors(self, neighbors):
        self.neighbors = neighbors

def dfs(vertex, stack, visited):
    pass

def topSort(graph):
    pass

def main():
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node1.replaceNeighbors([node2, node3])
    node2.replaceNeighbors([node4])
    node4.replaceNeighbors([node3])
    root = Node(0, [node1, node2])
    graph = [root, node1, node2, node3, node4]
    order = topSort(graph)
    print(order)

if __name__ == '__main__':
    main()  # calls main method


问:
How do you add custom text to an SMS in flutter?
I'm trying to send an SMS from my flutter app when a user wants to interact with another user. I already have the phone number and I know I can open the SMS window using url_launcher package but that package doesn't let me add my own custom message to it. I do not want the text to be automatically sent though.

Basically what I want is when the url_launcher launches the SMS window, there is already a custom message that I have provided, so that the user can add on or remove stuff if they want to and then send the text themselves.

Thanks a lot!

答:
Try https://pub.dev/packages/flutter_sms.

It allows opening an SMS app with prepopulated phone and text fields.


问:
Stripping ints from a string in pandas column
I have a column like this:

```<code>      Age
15-20 years old
20-25 years old
</code>```

I want this as output:

```<code>Age_Min   Age_Max
  15         20
  20         25
</code>```

I am trying to use str.strip() but no success so far.

I tried d[['Age_Min','Age_Max']]=d['Age'].str.split('-',expand=True)

and the result is almost there.  Is there a way to get only the integers and remove the string?

Any tips?

答:
Use Series.str.split with expand=True:

```<code>In [858]: out = df['Age'].str.split('-', expand=True).rename(columns={0:'Age_Min', 1: 'Age_Max'})

In [860]: out['Age_Max'] = out['Age_Max'].str.split().str[0]

In [861]: out
Out[861]:
  Age_Min Age_Max
0      15      20
1      20      25
</code>```

OR using regex:

```<code>In [870]: out = df['Age'].str.extract("(\d*\-?\d+)")[0].str.split('-', expand=True).rename(columns={0:'Age_Min', 1: 'Age_Max'})

In [871]: out
Out[871]:
  Age_Min Age_Max
0      15      20
1      20      25
</code>```

Body:
I have a column like this:

      Age
15-20 years old
20-25 years old

I want this as output:

Age_Min   Age_Max
  15         20
  20         25

I am trying to use str.strip() but no success so far.

I tried d[['Age_Min','Age_Max']]=d['Age'].str.split('-',expand=True)

and the result is almost there.  Is there a way to get only the integers and remove the string?

Any tips?

Body:
Use Series.str.split with expand=True:

In [858]: out = df['Age'].str.split('-', expand=True).rename(columns={0:'Age_Min', 1: 'Age_Max'})

In [860]: out['Age_Max'] = out['Age_Max'].str.split().str[0]

In [861]: out
Out[861]:
  Age_Min Age_Max
0      15      20
1      20      25

OR using regex:

In [870]: out = df['Age'].str.extract("(\d*\-?\d+)")[0].str.split('-', expand=True).rename(columns={0:'Age_Min', 1: 'Age_Max'})

In [871]: out
Out[871]:
  Age_Min Age_Max
0      15      20
1      20      25


问:
React pass fetched data from API to another component
I am fetching few products from an API, and displaying them in card. There is a More Details link on the cards, where if the user clicks on it, it will take the user to the selected product details page. My routing to productDetails page works, But I am having troubles to find a way to pass the fetched data to the productDetails page as props.

This is what I have so far:
My FeaturedProduct.js:

```<code>import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (
    <div>
      <h1> Your Products List is shown below:</h1>
      <div className="item-container">

        {products.map((product) => (
          <div className="card" key={product.id}>
            {" "}

            <h3>{product.item}</h3>
            <p>
              {product.city}, {product.state}
            </p>
            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails" component={ProductDetails} />
              </Switch>
            </Router>
          </div>
        ))}
      </div>
    </div>
  );
}

export default FeaturedProduct;
</code>```

My Product Details Page:

```<code>import React from "react";
import FeaturedProduct from "./FeaturedProduct";

function ProductDetails(props) {
  return (
    <div>
      <div>
        <h1>{props.name}</h1>
        <h1>{props.color}</h1>
      </div>
    </div>
  );
}
export default  ProductDetails;
</code>```

答:
Pass it as an element with props, if you are using v 6; sorry I didn't ask which version. >

```<code><Switch>
<Route path="/productdetails"  element={<ProductDetails {...props} />}/>
</Switch>
</code>```

if version v4/5 use the render method >

```<code><Route path="/productdetails" render={(props) => (
{ <ProductDetails {...props} />} )}/>
</code>```

Body:
I am fetching few products from an API, and displaying them in card. There is a More Details link on the cards, where if the user clicks on it, it will take the user to the selected product details page. My routing to productDetails page works, But I am having troubles to find a way to pass the fetched data to the productDetails page as props.

This is what I have so far:
My FeaturedProduct.js:

import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (

 Your Products List is shown below:

        {products.map((product) => (

            {" "}

{product.item}

              {product.city}, {product.state}

            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails" component={ProductDetails} />
              </Switch>
            </Router>

        ))}

  );
}

export default FeaturedProduct;

My Product Details Page:

import React from "react";
import FeaturedProduct from "./FeaturedProduct";

function ProductDetails(props) {
  return (

{props.name}

{props.color}

  );
}
export default  ProductDetails;

Body:
Pass it as an element with props, if you are using v 6; sorry I didn't ask which version. >

<Switch>
<Route path="/productdetails"  element={<ProductDetails {...props} />}/>
</Switch>

if version v4/5 use the render method >

<Route path="/productdetails" render={(props) => (
{ <ProductDetails {...props} />} )}/>


问:
my on click function is not working in ursina
I don't know how to do that when the user clicks on Settings so that everything is invisible.  I tried

```<code>Play.on_click = Settings.visible = False
Play.on_click = quit.visible = False
Play.on_click = Play.visible = False
</code>```

but it doesn't work

答:
on_click expects a function but you assigned a value. Try this instead:

```<code>def play_onclick():
    Settings.visible = False
    quit.visible = False
    Play.visible = False

Play.on_click = play_onclick # without parentheses!
</code>```

Also, I'm assuming that Play is a ursina.Button instance. If that's the case, you should follow the Python naming convention of having its name start with a lowercase letter, i.e. play.

Body:
I don't know how to do that when the user clicks on Settings so that everything is invisible.  I tried

Play.on_click = Settings.visible = False
Play.on_click = quit.visible = False
Play.on_click = Play.visible = False

but it doesn't work

Body:
on_click expects a function but you assigned a value. Try this instead:

def play_onclick():
    Settings.visible = False
    quit.visible = False
    Play.visible = False

Play.on_click = play_onclick # without parentheses!

Also, I'm assuming that Play is a ursina.Button instance. If that's the case, you should follow the Python naming convention of having its name start with a lowercase letter, i.e. play.


问:
python regex to select everything before and after a particular string
I am trying to apply regex on one of the columns in pandas dataframe, this column has text data in it, I am trying to extract a specific block. This is a sample of how my data will look like,

```<code>Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.
</code>```

I am trying to extract text from the beginning of the given string up to the first blank line following the first line containing 'Patient Referred from'., the entities may or may not appear in same order except the "Patient Referred from" which will always be the first entity, but there wont be any empty line until that entire block is finished. I have tried this below one,

```<code>import re
def extract_patient_details(s):

    match = re.search('(?s)Patient Referred(.*?)(?:(?:\r*\n){2})', s)
    return match.group(0)

extract_patient_details(s)
</code>```

The above snippet works fine and gives me this output:

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head
```
<p>But what I want is:</p>
<pre class="lang-none prettyprint-override"><code>Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head
</code>```

答:
It's because your regex is:

```<code>(?s)Patient Referred(.*?)(?:(?:\r*\n){2})
</code>```

It's matching everything you told it to - your string start looks for "Patient Referred" and not Patient name, ie everything between patient referred + ct head. Try this instead:

```<code>match = re.search('(?s)(Patient Name).*?( CT Head)', s)
</code>```

output:

```<code>Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head
</code>```

Entire code:

```<code>import re

def extract_patient_details(s):

    match = re.search('(?s)(Patient Name).*?( CT Head)', s)
    return match.group(0)

s = """
Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.
"""

s = extract_patient_details(s)
print(s)
</code>```

Body:
I am trying to apply regex on one of the columns in pandas dataframe, this column has text data in it, I am trying to extract a specific block. This is a sample of how my data will look like,

Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.

I am trying to extract text from the beginning of the given string up to the first blank line following the first line containing 'Patient Referred from'., the entities may or may not appear in same order except the "Patient Referred from" which will always be the first entity, but there wont be any empty line until that entire block is finished. I have tried this below one,

import re
def extract_patient_details(s):

    match = re.search('(?s)Patient Referred(.*?)(?:(?:\r*\n){2})', s)
    return match.group(0)

extract_patient_details(s)

The above snippet works fine and gives me this output:

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

But what I want is:

Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

Body:
It's because your regex is:

(?s)Patient Referred(.*?)(?:(?:\r*\n){2})

It's matching everything you told it to - your string start looks for "Patient Referred" and not Patient name, ie everything between patient referred + ct head. Try this instead:

match = re.search('(?s)(Patient Name).*?( CT Head)', s)

output:

Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

Entire code:

import re

def extract_patient_details(s):

    match = re.search('(?s)(Patient Name).*?( CT Head)', s)
    return match.group(0)

s = """
Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.
"""

s = extract_patient_details(s)
print(s)


问:
checking if list contains same element in straight row
so,I have a list [5. 5. 5. 5. 0. 0.] I want to check if it contains same elements in straight row (atleast 4 )

I came up with this

```<code>for i in list:
    w = []
    for x in range(len(i)-4):
        if (i[x] == i[x+1] == i[x+2] == i[x+3] != 0) :
            print(i[x])
            break
</code>```

I gives me desired output,

but , what would the efficient way to achieving the same result ,without much looping ?

答:
In numpy it's worth to find indices of value changes and return every index that preceeds another index that differs not less than 4.

```<code>x = np.array([6,6,6,6,7,7,8,8,4,4,4,4,4,4,4,3,3,3,3])
div_points = np.flatnonzero(np.diff(x, prepend=x[0]+1, append=x[-1]+1))
idx = np.r_[np.diff(div_points)>=4, False]
x[div_points[idx]]
>>> array([6, 4, 3])
</code>```

And if you're quite lazy, you could just 'slide' all the comparisons:

```<code>view = np.lib.stride_tricks.sliding_window_view(x, 4)
view
array([[6, 6, 6, 6],
       [6, 6, 6, 7],
       [6, 6, 7, 7],
       [6, 7, 7, 8],
       [7, 7, 8, 8],
       [7, 8, 8, 4],
       [8, 8, 4, 4],
       [8, 4, 4, 4],
       [4, 4, 4, 4],
       [4, 4, 4, 4],
       [4, 4, 4, 4],
       [4, 4, 4, 4],
       [4, 4, 4, 3],
       [4, 4, 3, 3],
       [4, 3, 3, 3],
       [3, 3, 3, 3]])

r = np.all(x[:-3, None] == view, axis=1)
x[:-3][r]
>>> array([6, 4, 4, 4, 4, 3])
</code>```

Body:
so,I have a list [5. 5. 5. 5. 0. 0.] I want to check if it contains same elements in straight row (atleast 4 )

I came up with this

for i in list:
    w = []
    for x in range(len(i)-4):
        if (i[x] == i[x+1] == i[x+2] == i[x+3] != 0) :
            print(i[x])
            break

I gives me desired output,

but , what would the efficient way to achieving the same result ,without much looping ?

Body:
In numpy it's worth to find indices of value changes and return every index that preceeds another index that differs not less than 4.

x = np.array([6,6,6,6,7,7,8,8,4,4,4,4,4,4,4,3,3,3,3])
div_points = np.flatnonzero(np.diff(x, prepend=x[0]+1, append=x[-1]+1))
idx = np.r_[np.diff(div_points)>=4, False]
x[div_points[idx]]
>>> array([6, 4, 3])

And if you're quite lazy, you could just 'slide' all the comparisons:

view = np.lib.stride_tricks.sliding_window_view(x, 4)
view
array([[6, 6, 6, 6],
       [6, 6, 6, 7],
       [6, 6, 7, 7],
       [6, 7, 7, 8],
       [7, 7, 8, 8],
       [7, 8, 8, 4],
       [8, 8, 4, 4],
       [8, 4, 4, 4],
       [4, 4, 4, 4],
       [4, 4, 4, 4],
       [4, 4, 4, 4],
       [4, 4, 4, 4],
       [4, 4, 4, 3],
       [4, 4, 3, 3],
       [4, 3, 3, 3],
       [3, 3, 3, 3]])

r = np.all(x[:-3, None] == view, axis=1)
x[:-3][r]
>>> array([6, 4, 4, 4, 4, 3])


答:
Here's a one-liner that will return the indexes of all items in the specified 1D array that are identical to the next N items. Note that it requires the array be of floats because it uses NaN.

```<code>import functools as ft

N = 3
indexes = np.where(ft.reduce(lambda prev, cur: prev.astype(bool) & (cur == a), [np.pad(a, (0,i), constant_values=np.nan)[i:] for i in range(1, N+1)]))[0]
</code>```

Example:

```<code>>>> import functools as ft
>>> a = np.array([1, 2, 3, 3, 3, 3, 4, 5, 10, 10, 10, 10, 10, 2, 4], dtype=float)
>>> N = 3
>>> indexes = np.where(ft.reduce(lambda prev, cur: prev.astype(bool) & (cur == a), [np.pad(a, (0,i), constant_values=np.nan)[i:] for i in range(1, N+1)]))[0]
>>> indexes
array([2, 8, 9])
</code>```

Now, if we look at the array and the indexes:

```<code>[1, 2, 3, 3, 3, 3, 4, 5, 10, 10, 10, 10, 10, 2, 4]
       ^ 2               ^^ 8
                             ^^ 9
</code>```

Title: checking if list contains same element in straight row

Body:
Here's a one-liner that will return the indexes of all items in the specified 1D array that are identical to the next N items. Note that it requires the array be of floats because it uses NaN.

import functools as ft

N = 3
indexes = np.where(ft.reduce(lambda prev, cur: prev.astype(bool) & (cur == a), [np.pad(a, (0,i), constant_values=np.nan)[i:] for i in range(1, N+1)]))[0]

Example:

>>> import functools as ft
>>> a = np.array([1, 2, 3, 3, 3, 3, 4, 5, 10, 10, 10, 10, 10, 2, 4], dtype=float)
>>> N = 3
>>> indexes = np.where(ft.reduce(lambda prev, cur: prev.astype(bool) & (cur == a), [np.pad(a, (0,i), constant_values=np.nan)[i:] for i in range(1, N+1)]))[0]
>>> indexes
array([2, 8, 9])

Now, if we look at the array and the indexes:

[1, 2, 3, 3, 3, 3, 4, 5, 10, 10, 10, 10, 10, 2, 4]
       ^ 2               ^^ 8
                             ^^ 9


问:
Evaluate a variable inside a variable with thymeleaf
I am receiving bin data as json. The number of bins in each section is different, but for instance it might be:

```<code>var jsonmsg={"1": "SIXTY", "2": "DISCONNECTED", "3": "TWENTY", "4": "FULL", "5": "TEN"});
</code>```

I already know the number of bins in each section so bins=5 is known

So I am trying to pass the bin number and json values as class
eg: class="bin3 TWENTY"

This is my thymeleaf code

```<code><th:block th:each="i : ${#numbers.sequence( 1, bins, 1)}">
    <div class="grid-item">something else</div>
    <div class="grid-item">something else</div>
    <div class="grid-item"><div th:class="bin+${i}" th:classappend="${jsonmsg.[[${i}]]}"></div></div>
</th:block>
</code>```

class="bin3" works fine, but I can't work out how to request jsonmsg.* correctly. I have also tried without [[]].

I have also tried:

```<code>th:classappend="${jsonmsg[i]}"
</code>```

I always get the message:

Exception evaluating SpringEL expression

答:
Sorry I think this premise is flawed.

I am trying to manipulate a server side process with client side data. The server side rendering is already complete by then so instead I need client side data to be processed client side with javascript, (not thymeleaf). So I will use javascipt classList.add to update classes as required.

I should be iterating though the jsonmsg directly, not using integers.

I will leave this flawed question as is, in case anyone else tries to use client side data (like stomp) to manipulate Thymeleaf templates.

Body:
I am receiving bin data as json. The number of bins in each section is different, but for instance it might be:

var jsonmsg={"1": "SIXTY", "2": "DISCONNECTED", "3": "TWENTY", "4": "FULL", "5": "TEN"});

I already know the number of bins in each section so bins=5 is known

So I am trying to pass the bin number and json values as class
eg: class="bin3 TWENTY"

This is my thymeleaf code

something else

something else

class="bin3" works fine, but I can't work out how to request jsonmsg.* correctly. I have also tried without [[]].

I have also tried:

th:classappend="${jsonmsg[i]}"

I always get the message:

Exception evaluating SpringEL expression


问:
Get the title from a popup
This is a jQuery tooltip.

In a nutshell, the jQuery creates the popup from another HTML page.

EDIT
   i put up an example. HERE

So I need to grab the title from the popup. When I use the document.title or whatever, it echos the title from the current page and not the popup.

```<code><div id='JT_close_right'>"+title+"</div>
</code>```

I need the title in a variable:

```<code>var title = (pop-up page's title)
</code>```

答:
simply use:

```<code>var title = $('#JT_close_right').html();
</code>```

Since you are populating that element with the title in the function, you just need to grab that element by its id. The popup you are creating is not a separate window, but just using a div as an overlay overtop of the current content, so it does not have its own document.title for example, or document object for that matter.

ContentLicense: CC BY-SA 3.0

Title: Get the title from a popup

Body:
This is a jQuery tooltip.

In a nutshell, the jQuery creates the popup from another HTML page.

EDIT
   i put up an example. HERE

So I need to grab the title from the popup. When I use the document.title or whatever, it echos the title from the current page and not the popup.

"+title+"

I need the title in a variable:

var title = (pop-up page's title)

Body:
simply use:

var title = $('#JT_close_right').html();

Since you are populating that element with the title in the function, you just need to grab that element by its id. The popup you are creating is not a separate window, but just using a div as an overlay overtop of the current content, so it does not have its own document.title for example, or document object for that matter.


答:
Can you try re.match(r'(?sm).+CT Head', st).group(0)?

(?sm) turns ON re.DOTALL and re.MULTILINE

We're using re.match() as we're matching from the beginning of the string

Title: python regex to select everything before and after a particular string


问:
How to reverse a list of words in a shell string?
I have a list of words in a string:

```<code>str="SaaaaE SeeeeE SbbbbE SffffE SccccE"
</code>```

I want to reverse it in order to get

```<code>"SccccE SffffE SbbbbE SeeeeE SaaaaE"
</code>```

How I can do that with ash?

答:
Reverses string but keeps endmark in place.

```<code>#!/bin/bash

#set -x

read -p "Enter a sentence: " sentence

myArray=( $sentence )

counter="${#myArray[@]}"

i=0

for word in "${myArray[@]}"
do
        if [ $counter -lt 1 ]
        then break
        fi

reverseArray[$i]="${myArray[$counter-1]}"

letterCounter=0

while read -n 1 letter
do
if [ "$letter" == '?' ] || [ "$letter" == '!' ] || [ "$letter" == '.' ]
then
endmark="$letter"
reverseArray[$i]=$(echo "${reverseArray[$i]}" | head -c "$letterCounter")
fi
((letterCounter++))
done < <(echo "${reverseArray[$i]}")

((i++))
((counter--))
done

echo "${reverseArray[*]}$endmark"

exit

</code>```

INPUT:
hello world?

OUTPUT:
world hello?

Body:
I have a list of words in a string:

str="SaaaaE SeeeeE SbbbbE SffffE SccccE"

I want to reverse it in order to get

"SccccE SffffE SbbbbE SeeeeE SaaaaE"

How I can do that with ash?

Body:
Reverses string but keeps endmark in place.

#!/bin/bash

#set -x

read -p "Enter a sentence: " sentence

myArray=( $sentence )

counter="${#myArray[@]}"

i=0

for word in "${myArray[@]}"
do
        if [ $counter -lt 1 ]
        then break
        fi

reverseArray[$i]="${myArray[$counter-1]}"

letterCounter=0

while read -n 1 letter
do
if [ "$letter" == '?' ] || [ "$letter" == '!' ] || [ "$letter" == '.' ]
then
endmark="$letter"
reverseArray[$i]=$(echo "${reverseArray[$i]}" | head -c "$letterCounter")
fi
((letterCounter++))
done < <(echo "${reverseArray[$i]}")

((i++))
((counter--))
done

echo "${reverseArray[*]}$endmark"

exit

INPUT:
hello world?

OUTPUT:
world hello?


问:
How to select multiple text parts with Scrapy inside of a tag with subtags?
I have this sample-html:

```<code><div class="classname1">
  "This is text inside of"
  <b>"a subtag"</b>
  "I would like to select."
  <br>
  "More text I don't need"
  </br>

  (more br and b tags on the same level)

</div>

</code>```

The result should be a list containing:

```<code>["This is text inside of a subtag I would like to select."]
</code>```

I tried:

```<code>response.xpath('//div[@class="classname1"]//text()[1]').getall()
</code>```

but this gives me only the first part "This is text inside".

There are two challenges:

Sometimes there is no b tag

There is even more text after the desired section that should be expluded

Maybe a loop?
If anyone has an approach it would be really helpful.

答:
What about this (used More text I don't need as a stopword):

```<code>parts = []
for text in response.xpath('//div[@class="classname1"]//text()').getall():
    if 'More text I don't need' in text:
        break
    parts.append(text)
result = ' '.join(parts)
</code>```

UPDATE For example, you need to extract all text before Ort: :

```<code>def parse(self, response):
    for card_node in response.xpath('//div[@class="col-md-8 col-sm-12 card-place-container"]'):
        parts = []
        for text in card_node.xpath('.//text()').getall():
            if 'Ort: ' in text:
                break
            parts.append(text)
        before_ort = '\n'.join(parts)
        print(before_ort)
</code>```

Body:
I have this sample-html:

  "This is text inside of"
  "a subtag"
  "I would like to select."

  "More text I don't need"

  (more br and b tags on the same level)

The result should be a list containing:

["This is text inside of a subtag I would like to select."]

I tried:

response.xpath('//div[@class="classname1"]//text()[1]').getall()

but this gives me only the first part "This is text inside".

There are two challenges:

Sometimes there is no b tag

There is even more text after the desired section that should be expluded

Maybe a loop?
If anyone has an approach it would be really helpful.

Body:
What about this (used More text I don't need as a stopword):

parts = []
for text in response.xpath('//div[@class="classname1"]//text()').getall():
    if 'More text I don't need' in text:
        break
    parts.append(text)
result = ' '.join(parts)

UPDATE For example, you need to extract all text before Ort: :

def parse(self, response):
    for card_node in response.xpath('//div[@class="col-md-8 col-sm-12 card-place-container"]'):
        parts = []
        for text in card_node.xpath('.//text()').getall():
            if 'Ort: ' in text:
                break
            parts.append(text)
        before_ort = '\n'.join(parts)
        print(before_ort)


问:
Problems with RSelenium and ChromeDriver - "This version of ChromeDriver only supports Chrome version X"
I'm having a difficult time getting RSelenium to work with my ChromeDriver in R v4.1.2. Initially, I installed the ChromeDriver v97 because I had Chrome v97 running on my Mac as my browser. However, despite installing the v97 ChromeDriver, I would get an error every time that read

Selenium message:session not created: This version of ChromeDriver only supports Chrome version 98

So I did some research and everything I read said I could either upgrade Google Chrome or downgrade my driver. I tried both. I uninstalled the driver and installed an earlier version (v96) but it still gave me the exact same error. Then I tried upgrading my Chrome browser, but it said it was up to date and that no upgrade was available. So I just figured I'd wait until v98 was ready to install. As soon as v98 was out, I upgraded my browser to Chrome v98 and Selenium with the ChromeDriver ran smoothly without issues. I haven't changed anything since. It ran for a couple of days, but now, all of a sudden, I'm getting the error again but now it says

```<code> "This version of ChromeDriver only supports Chrome version 99"
</code>```

But I have not upgraded my ChromeDriver since installing the v97 driver. It seems as though the driver must have some code in it that checks what the most current version of Chrome is (even if that is a Beta release) and requires that I have it, regardless of which driver or browser I have installed. Has anyone come across this issue before? Any idea of how I can resolve this? I cannot upgrade to v99, it's not available yet, and uninstalling my ChromeDriver and reinstalling a previous version doesn't seem to do anything either.

Thank you in advance.

答:
To know the chrome version use,

```<code>binman::list_versions("chromedriver")

$win32
 [1] "85.0.4183.87"  "86.0.4240.22"  "87.0.4280.20"  "87.0.4280.88"  "88.0.4324.27"  "91.0.4472.101" "91.0.4472.19"  "92.0.4515.107" "92.0.4515.43"
</code>```

Then you can try the versions which works for you,

```<code>library(RSelenium)
driver <- rsDriver(browser = "chrome",port = 9537L, chromever = "96.0.4664.45")
</code>```

or else you can use firefox,

```<code>driver = rsDriver(port = 4841L, browser = c("firefox"))
</code>```

Body:
I'm having a difficult time getting RSelenium to work with my ChromeDriver in R v4.1.2. Initially, I installed the ChromeDriver v97 because I had Chrome v97 running on my Mac as my browser. However, despite installing the v97 ChromeDriver, I would get an error every time that read

Selenium message:session not created: This version of ChromeDriver only supports Chrome version 98

So I did some research and everything I read said I could either upgrade Google Chrome or downgrade my driver. I tried both. I uninstalled the driver and installed an earlier version (v96) but it still gave me the exact same error. Then I tried upgrading my Chrome browser, but it said it was up to date and that no upgrade was available. So I just figured I'd wait until v98 was ready to install. As soon as v98 was out, I upgraded my browser to Chrome v98 and Selenium with the ChromeDriver ran smoothly without issues. I haven't changed anything since. It ran for a couple of days, but now, all of a sudden, I'm getting the error again but now it says

 "This version of ChromeDriver only supports Chrome version 99"

But I have not upgraded my ChromeDriver since installing the v97 driver. It seems as though the driver must have some code in it that checks what the most current version of Chrome is (even if that is a Beta release) and requires that I have it, regardless of which driver or browser I have installed. Has anyone come across this issue before? Any idea of how I can resolve this? I cannot upgrade to v99, it's not available yet, and uninstalling my ChromeDriver and reinstalling a previous version doesn't seem to do anything either.

Thank you in advance.

Body:
To know the chrome version use,

binman::list_versions("chromedriver")

$win32
 [1] "85.0.4183.87"  "86.0.4240.22"  "87.0.4280.20"  "87.0.4280.88"  "88.0.4324.27"  "91.0.4472.101" "91.0.4472.19"  "92.0.4515.107" "92.0.4515.43"

Then you can try the versions which works for you,

library(RSelenium)
driver <- rsDriver(browser = "chrome",port = 9537L, chromever = "96.0.4664.45")

or else you can use firefox,

driver = rsDriver(port = 4841L, browser = c("firefox"))


问:
Spring Boot gradle build - invalid source release: 11
I am trying to build my spring boot project with this command:

```<code>./gradlew build
</code>```

But it continuously throws this error:

```<code>'Execution failed for task ':compileJava'. invalid source release: 11'.
</code>```

My project is using Java version 11, and the IntelliJ Java version is set to 11 as well.

This is the Java version settings on my IntelliJ that I have done so far:

Settings - Build, Execution, Deployment - Build Tools - Gradle

-> set to 11.

Settings - Build, Execution, Deployment - Compiler - Java Compiler - Project bytecode version

-> set to 11.

java -version command on IntelliJ Terminal

-> set to 11.0.12

Project Structure - Project Settings - Project - Project SDK:
-> set to 11.

Project Structure - Project Settings - Modules - Module SDK:
-> set to 11.

Project Structure - Platform Settings - SDKs - JDK home path:

-> set to 11.

System Environment path - JAVA_HOME

-> set to 11.

build.gradle - sourceCompatibility, targetCompatibility

-> set to 11.

After all of this when I run

```<code>./gradlew build
</code>```

result

I think I've done everything possible. Is there any other settings that I can try ??

答:
In my case it's my sdkman which no longer supports adoptopenjdk 11 and the project got renamed to Temurin.

Reference: https://sdkman.io/jdks

So my gradle build was trying to resolve the missing adoptopenjdk 11 and it couldn't.
I reinstalled the jdk 11 from Temurin

```<code>sdk install java 11.0.14-tem
</code>```

And voila it solved the build issue and my gradle build is successful.

Body:
I am trying to build my spring boot project with this command:

./gradlew build

But it continuously throws this error:

'Execution failed for task ':compileJava'. invalid source release: 11'.

My project is using Java version 11, and the IntelliJ Java version is set to 11 as well.

This is the Java version settings on my IntelliJ that I have done so far:

Settings - Build, Execution, Deployment - Build Tools - Gradle

-> set to 11.

Settings - Build, Execution, Deployment - Compiler - Java Compiler - Project bytecode version

-> set to 11.

java -version command on IntelliJ Terminal

-> set to 11.0.12

Project Structure - Project Settings - Project - Project SDK:
-> set to 11.

Project Structure - Project Settings - Modules - Module SDK:
-> set to 11.

Project Structure - Platform Settings - SDKs - JDK home path:

-> set to 11.

System Environment path - JAVA_HOME

-> set to 11.

build.gradle - sourceCompatibility, targetCompatibility

-> set to 11.

After all of this when I run

./gradlew build

result

I think I've done everything possible. Is there any other settings that I can try ??

Body:
In my case it's my sdkman which no longer supports adoptopenjdk 11 and the project got renamed to Temurin.

Reference: https://sdkman.io/jdks

So my gradle build was trying to resolve the missing adoptopenjdk 11 and it couldn't.
I reinstalled the jdk 11 from Temurin

sdk install java 11.0.14-tem

And voila it solved the build issue and my gradle build is successful.


问:
Android emulator looks bad on retina display (pixelated)
All my emulations have pixelated text and images like this on retina display. I've tried adjusting numerous setting to no avail. Does anyone know a solution to get it crystal clear?

Here are the settings I've tried using:

And...

Note that use Host GPU is checked for both.

答:
Let's say we have 1920x1080 OS display resolution device, then
choose Nexus 5X, with 1920x1080 resolution that is identical to your OS display resolution

enter image description here


问:
Why is Dialogflow CX referencing gcloud's project (project-number)?
I am working the Dialogflow CX Java SDK to execute a list agents command.  When, I try to list the agents, I get this exception.

```<code>io.grpc.StatusRuntimeException: PERMISSION_DENIED: Dialogflow API has not been used in project project-number before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/dialogflow.googleapis.com/overview?project=project-number then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.
</code>```

Relevant code snippet:

```<code>AgentsSettings agentsSettings = AgentsSettings.newBuilder().build();

AgentsClient client = AgentsClient.create(agentsSettings)
LocationName parent = LocationName.of("my project id", "US-CENTRAL1");
AgentsClient.ListAgentsPagedResponse agents = client.listAgents(parent);
</code>```

Any help appreciated.

答: This error may indicate that the GOOGLE_APPLICATION_CREDENTIALS and/or GOOGLE_CLOUD_PROJECT environment variables were not properly set. Reviewing the Dialogflow CX Setup documentation may help.

Body:
I am working the Dialogflow CX Java SDK to execute a list agents command.  When, I try to list the agents, I get this exception.

io.grpc.StatusRuntimeException: PERMISSION_DENIED: Dialogflow API has not been used in project project-number before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/dialogflow.googleapis.com/overview?project=project-number then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

Relevant code snippet:

AgentsSettings agentsSettings = AgentsSettings.newBuilder().build();

AgentsClient client = AgentsClient.create(agentsSettings)
LocationName parent = LocationName.of("my project id", "US-CENTRAL1");
AgentsClient.ListAgentsPagedResponse agents = client.listAgents(parent);

Any help appreciated.


问:
How to use markdown for python with PyCharm?
I'm new to python and I've been using PyCharm (4.5 Community Edition) as my IDE on a Mac OS X v11 system.  I've installed the markdown plug-in and enabled the package in pycharm (Actions>Plugins>Markdown is checked, program restart complete).

When I create a new markdown file (test.md or test.markdown) I can see the preview tab.  But I don't see anything in the preview tab. Also, I can't "run / execute" this file.  So seeing a preview would be nice.  Ideally, I would like to be able to execute python chunks with markdown comments in-between and see the output rendered in a local browser if this at all is possible.

This was really easy in the Rstudio IDE and a super powerful way to communicate findings.

Any suggestions?  Help much appreciated.

答:
Currently PyCharm has two plugin options for .md format: PlantUML and Mermaid.

According to the official docs, in order to enable md support:

Go to File -> Settings -> Languages & Frameworks -> Markdown.

(in recent versions: Pycharm -> Preferences -> Languages & Frameworks -> Markdown)

Install either of these plugins.

Close and Reopen PyCharm (it did not work instantly for me)

In order to see a file preview move a mouse to the upper right corner and select this option.


问:
Why doesn't Java's JIT compiler translate everything to native code?
I have been looking into the Java JIT compiler and i cannot figure out why some of the code is still interpreted. Why doesn't the JIT compiler translate everything to native code? Interpretation is much slower, am I missing something?</p>

答:
If you are running a JVM like HotSpot, it JIT-compiles opportunistically, only focusing on code that executes frequently. It determines which code to optimise on the fly by counting frequency of each code block (or method — I'm not sure which). Consequently, at startup time, everything is interpreted.

The intent behind this is allow for much more aggressive and expensive optimisations by only requiring a small fraction of the code to be optimised.


问:
CSS Animations are not smooth on Chrome (iOS)
I have a problem with CSS animations on Chrome browser, on iOS device.
Animations are snapping into place and are not smooth.
On Safari, Firefox or desktop Chrome everything works great.

Here is a simple example which is laggy on iOS version of Chrome:

.test {
  width: 50px;
  height: 50px;
  background: pink;
  transition: 2s;
}

.test:hover {
  width: 100px;
  height: 100px;
  background: yellow;
  transform: translateX(30px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test"></div></code>```

Fiddle

Is there any way to make such animations more smooth?

答:
My animations were choppy in chrome (like 2 frames per second). Maybe because traumatic experiences with bug fixing in the past has trained me to expect that its never this easy - but it took me a few minutes before I decided to restart Chrome on my iPhone.

I had over 10 tabs open. Once I closed them and restarted Chrome the animation was all good.

Hopefully this helps someone to feel slightly less silly.

Body:
I have a problem with CSS animations on Chrome browser, on iOS device.
Animations are snapping into place and are not smooth.
On Safari, Firefox or desktop Chrome everything works great.

Here is a simple example which is laggy on iOS version of Chrome:

.test {
  width: 50px;
  height: 50px;
  background: pink;
  transition: 2s;
}

.test:hover {
  width: 100px;
  height: 100px;
  background: yellow;
  transform: translateX(30px);
}

Fiddle

Is there any way to make such animations more smooth?


问:
Polynomial Multiplication using divide and conquer
I'm trying to write code that performs polynomial multiplication using a divide and conquer method. It uses a trick to do only 3 multiplications instead of 4 multiplications, involving splitting each polynomial into two halves and factoring out an x^n/2 from one of the two halves. My code is returning the wrong answer with some test cases and I'm not sure what I'm doing wrong.

Edit: Adding naive multiply function and test cases.

Here's what I've tried so far:

```<code>class Polynom:
    """stores polynomial object"""

    def __init__(self, coefficients):
        """pass coefficient list in increasing order, i.e. x^0 + x^1 + x^2 + ... + x^n"""
        self.coefficients = coefficients
        self.length = len(coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)

    def __add__(self, other):
        for i in range(0,other.length):
            try:
                self.coefficients[i] = self.coefficients[i] + other.coefficients[i]
            except:
                self.coefficients.append(0)
                self.coefficients[i] = self.coefficients[i] + other.coefficients[i]
        self.length = len(self.coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)
        return self

    def __sub__(self, other):
        for i in range(0,other.length):
            self.coefficients[i] = self.coefficients[i] - other.coefficients[i]
        self.length = len(self.coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)
        return self

    def split(self):
        first_max_ind = int((self.length-1)/2)
        first_coefs = self.coefficients[:first_max_ind]
        first = Polynom(first_coefs)
        second_coefs = self.coefficients[first_max_ind:]
        second = Polynom(second_coefs)
        return first, second

def divideAndConquer(a,b):
    """simple divide and conquer algorithm for multiplication"""

    if a.nonZero == 2 and b.nonZero == 2:
        c = naiveMultiply(a,b)
        return c
    else:
        a0, a1 = a.split()
        b0, b1 = b.split()

        # calculate y, u, and z
        y = divideAndConquer(a0 + a1, b0 + b1)
        u = divideAndConquer(a0, b0)
        z = divideAndConquer(a1, b1)
        middleTerm = y - u - z

        NOver2 = int(max(a.length/2, b.length/2))
        lyst = [0] * int(NOver2 + 1)
        lyst[NOver2] = 1
        xNOver2 = Polynom(lyst)

        return u + naiveMultiply(middleTerm, xNOver2) + naiveMultiply(z, xNOver2)

def naiveMultiply(a,b):
    """takes two polynomials and multiplies using naive approach"""

    maxLength = a.length + b.length - 1
    coefficientList = [0] * maxLength

    for i in range(0,a.length):
        for j in range(0, b.length):
            power = i + j
            coefficient = a.coefficients[i] * b.coefficients[j]
            coefficientList[power] += coefficient

    return Polynom(coefficientList)

a = Polynom([1,2,3,4,5])
b = Polynom([1,2,3,4,5])

naiveMultiply(a,b)
divideAndConquer(a,b)
</code>```

The correct answer for test case: (1 + 2x + 3x^2 + 4x^3 + 5x^4)^2
should be:
1 + 4x + 10x^2 + 20x^3 + 35x^4 + 44x^5 + 46x^6 + 40x^7 + 25x^8

but I'm getting:
100 + 100x + 25x^2 + 0x^3 + 0x^4 + 0x^5

答:
Your __add__ and __sub__ methods alter the self instance (note the assignments to self.coefficients).

Further down in the divideAndConquer method, I see that you are using a variable a0 in an expression a0 + a1, which would alter the value of a0 to become a0 + a1. You then use the same (altered) a0 variable in further expressions, possibly not aware that the variable now has a different value.

In general, overloaded operator methods should probably create a new instance instead of altering self, this will make them much safer to use.

in this case, for example, a safe implementation of __add__ would be

```<code>def __add__(self, other):
    coefficients = list(self.coefficients)
    for i in range(0,other.length):
        try:
            coefficients[i] = coefficients[i] + other.coefficients[i]
        except:
            coefficients.append(0)
            coefficients[i] = coefficients[i] + other.coefficients[i]
    return Polynom(coefficients)
</code>```

(I've minimally fixed the self-altering; there are several further improvements that should be made to the method including what has been suggested in the comments.)

Body:
I'm trying to write code that performs polynomial multiplication using a divide and conquer method. It uses a trick to do only 3 multiplications instead of 4 multiplications, involving splitting each polynomial into two halves and factoring out an x^n/2 from one of the two halves. My code is returning the wrong answer with some test cases and I'm not sure what I'm doing wrong.

Edit: Adding naive multiply function and test cases.

Here's what I've tried so far:

class Polynom:
    """stores polynomial object"""

    def __init__(self, coefficients):
        """pass coefficient list in increasing order, i.e. x^0 + x^1 + x^2 + ... + x^n"""
        self.coefficients = coefficients
        self.length = len(coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)

    def __add__(self, other):
        for i in range(0,other.length):
            try:
                self.coefficients[i] = self.coefficients[i] + other.coefficients[i]
            except:
                self.coefficients.append(0)
                self.coefficients[i] = self.coefficients[i] + other.coefficients[i]
        self.length = len(self.coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)
        return self

    def __sub__(self, other):
        for i in range(0,other.length):
            self.coefficients[i] = self.coefficients[i] - other.coefficients[i]
        self.length = len(self.coefficients)
        self.nonZero = np.count_nonzero(self.coefficients)
        return self

    def split(self):
        first_max_ind = int((self.length-1)/2)
        first_coefs = self.coefficients[:first_max_ind]
        first = Polynom(first_coefs)
        second_coefs = self.coefficients[first_max_ind:]
        second = Polynom(second_coefs)
        return first, second

def divideAndConquer(a,b):
    """simple divide and conquer algorithm for multiplication"""

    if a.nonZero == 2 and b.nonZero == 2:
        c = naiveMultiply(a,b)
        return c
    else:
        a0, a1 = a.split()
        b0, b1 = b.split()

        # calculate y, u, and z
        y = divideAndConquer(a0 + a1, b0 + b1)
        u = divideAndConquer(a0, b0)
        z = divideAndConquer(a1, b1)
        middleTerm = y - u - z

        NOver2 = int(max(a.length/2, b.length/2))
        lyst = [0] * int(NOver2 + 1)
        lyst[NOver2] = 1
        xNOver2 = Polynom(lyst)

        return u + naiveMultiply(middleTerm, xNOver2) + naiveMultiply(z, xNOver2)

def naiveMultiply(a,b):
    """takes two polynomials and multiplies using naive approach"""

    maxLength = a.length + b.length - 1
    coefficientList = [0] * maxLength

    for i in range(0,a.length):
        for j in range(0, b.length):
            power = i + j
            coefficient = a.coefficients[i] * b.coefficients[j]
            coefficientList[power] += coefficient

    return Polynom(coefficientList)

a = Polynom([1,2,3,4,5])
b = Polynom([1,2,3,4,5])

naiveMultiply(a,b)
divideAndConquer(a,b)

The correct answer for test case: (1 + 2x + 3x^2 + 4x^3 + 5x^4)^2
should be:
1 + 4x + 10x^2 + 20x^3 + 35x^4 + 44x^5 + 46x^6 + 40x^7 + 25x^8

but I'm getting:
100 + 100x + 25x^2 + 0x^3 + 0x^4 + 0x^5

Body:
Your __add__ and __sub__ methods alter the self instance (note the assignments to self.coefficients).

Further down in the divideAndConquer method, I see that you are using a variable a0 in an expression a0 + a1, which would alter the value of a0 to become a0 + a1. You then use the same (altered) a0 variable in further expressions, possibly not aware that the variable now has a different value.

In general, overloaded operator methods should probably create a new instance instead of altering self, this will make them much safer to use.

in this case, for example, a safe implementation of __add__ would be

def __add__(self, other):
    coefficients = list(self.coefficients)
    for i in range(0,other.length):
        try:
            coefficients[i] = coefficients[i] + other.coefficients[i]
        except:
            coefficients.append(0)
            coefficients[i] = coefficients[i] + other.coefficients[i]
    return Polynom(coefficients)

(I've minimally fixed the self-altering; there are several further improvements that should be made to the method including what has been suggested in the comments.)


问:
Where are saved files in Google Colab located?
I'm trying to access a VTK file where the solution to the heat equation is saved, but I've no idea where it's saved in Colab.

```<code>from fenics import *
import time
T = 2.0            # final time
num_steps = 50     # number of time steps
dt = T / num_steps # time step size
# Create mesh and define function space
nx = ny = 30
mesh = RectangleMesh(Point(-2, -2), Point(2, 2), nx, ny)
V = FunctionSpace(mesh, 'P', 1)
# Define boundary condition
def boundary(x, on_boundary):
    return on_boundary
bc = DirichletBC(V, Constant(0), boundary)
# Define initial value
u_0 = Expression('exp(-a*pow(x[0], 2) - a*pow(x[1], 2))',
                 degree=2, a=5)
u_n = interpolate(u_0, V)
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(0)
F = u*v*dx + dt*dot(grad(u), grad(v))*dx - (u_n + dt*f)*v*dx
a, L = lhs(F), rhs(F)
# Create VTK file for saving solution
vtkfile = File('heat_gaussian/solution.pvd')
# Time-stepping
u = Function(V)
t=0
for n in range(num_steps):
    # Update current time
    t += dt
    # Compute solution
    solve(a == L, u, bc)
    # Save to file and plot solution
    vtkfile << (u, t)
    plot(u)
    # Update previous solution
    u_n.assign(u)
# Hold plot
#interactive()
</code>```

I've tried;

```<code>from google.colab import files
plt.savefig("vtkfile")
files.download("vtkfile")
</code>```

And

```<code>from google.colab import files files.upload()
from google.colab import drive drive.mount('vtkfile')
</code>```

But still getting errors. Where are files created in the notebook stored?

答: If you accidentally clicked on a folder and it opened and you have no idea where the old folders went and there doesn't seem to be a way to go back, check the content folder - it may have what you're looking for.

Body:
I'm trying to access a VTK file where the solution to the heat equation is saved, but I've no idea where it's saved in Colab.

from fenics import *
import time
T = 2.0            # final time
num_steps = 50     # number of time steps
dt = T / num_steps # time step size
# Create mesh and define function space
nx = ny = 30
mesh = RectangleMesh(Point(-2, -2), Point(2, 2), nx, ny)
V = FunctionSpace(mesh, 'P', 1)
# Define boundary condition
def boundary(x, on_boundary):
    return on_boundary
bc = DirichletBC(V, Constant(0), boundary)
# Define initial value
u_0 = Expression('exp(-a*pow(x[0], 2) - a*pow(x[1], 2))',
                 degree=2, a=5)
u_n = interpolate(u_0, V)
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(0)
F = u*v*dx + dt*dot(grad(u), grad(v))*dx - (u_n + dt*f)*v*dx
a, L = lhs(F), rhs(F)
# Create VTK file for saving solution
vtkfile = File('heat_gaussian/solution.pvd')
# Time-stepping
u = Function(V)
t=0
for n in range(num_steps):
    # Update current time
    t += dt
    # Compute solution
    solve(a == L, u, bc)
    # Save to file and plot solution
    vtkfile << (u, t)
    plot(u)
    # Update previous solution
    u_n.assign(u)
# Hold plot
#interactive()

I've tried;

from google.colab import files
plt.savefig("vtkfile")
files.download("vtkfile")

And

from google.colab import files files.upload()
from google.colab import drive drive.mount('vtkfile')

But still getting errors. Where are files created in the notebook stored?


问:
Perl: Removing leftover anchor tags from a string
I wrote a script to check all URLs in an HTML file and remove them with HTTP::Tiny and delete, but it left a bunch of incomplete anchor tags like text here throughout the database. These changes have already been made and the script doesn't need to be run again.

The script read from a database where this info is stored.

The goal now is to strip the text here while leaving everything else in the buffer plus the "text here" text.

I wrote another script that reads the database and includes the following regex:

```<code>$html_buffer =~ s/(.*?)<a>(.*?)<\/a>(.*?)/$1$2$3/g;
</code>```

but it doesn't work and I don't know why. Here's an example buffer:

```<code>This week, perhaps the most interesting articles include "<a>Finding \r\n  that Windows is superior to Linux is biased</a>," "<a href=\"http://www.example.com/content/view/118693\">How \r\n  to set up DNS for Linux VPNs</a>," and "<a href=\"http://www.example.com/content/view/118664
\">Writing \r\n  an Incident Handling and Recovery Plan</a>."
</code>```

Of course I want the regex to operate throughout the string, but also match multiple occurrences within the string.

Is this the most effective way to do this? How can I be sure to not remove the  at the end of the string like in the above example?

答:
In principle, it is always advisable to use a proper parser.  An example is in the second part

That regex needs the /s modifier so that . matches linefeeds as well, and then it works.  Without it the pattern .*? stops at newlines. It's only by happenstance that the as it is regex still manages to match some of the string, appearing to "work but not right."

The point is that that string, with \ns in it, has newlines if it's assigned as double-quoted

```<code>my $html_buffer = " ... ";   # or:  = qq(...);
</code>```

because then \n is interpreted as a linefeed.  If that string is given with single quotes,

```<code>my $html_buffer = ' ... ';   # or:  = q(...);
</code>```

then there are no newlines in it, just occasional characters \ and n one after antoher, and .*? works as intended.

Finally: The substitution operator affects only the part of the string that has been matched (or less, if the pattern is written so to "drop" some of the match, for example with \K), so there is no reason for the leading and trailing (.*?).  All that's needed is

```<code>$html_buffer =~ s{<a>(.*?)</a>}{$1}sg;
</code>```

And for a little extra safety add little extra spaces in all these patterns, for <\s*a\s*> so

```<code>$html_buffer =~ s{<\s*a\s*>(.*?)<\s*/a\s*>}{$1}sg;
</code>```

To note, I'd find it a far superior solution to fix that original script so that it doesn't leave unintended bits and pieces behind.  I'd hazard a guess that that happened by using regex for HTML? It would be very surprising that any of the major libraries written to parse HTML/XML would cripple (valid I presume) HTML like that.

On the other hand, that can be done now, as well. If the remaining text and its not-links ( with no href attribute technically isn't a hyperlink) are exceedingly simple then it may be simpler to use a regex (fingers crossed) as asked; just this one time.

In all other cases, here's a very basic take with Mojo::DOM

```<code>use warnings;
use strict;
use feature 'say';

use Mojo::DOM;

my $html = q(<p> a link: <a>no href</a>, not. <p> OK: <a href="#">hoho</a>);

my $dom = Mojo::DOM->new( $html );
say $dom;

foreach my $link ($dom->find("a")->each) {

    if (not defined $link->attr->{href}) {
        # Replace this node with its text
        $link->replace( $link->text );
    }

}
say $dom;  # object stringifies to just its HTML
</code>```

(or $link->strip; to remove the HTML element but leave its content, with the same result)

This prints

```<code><p> a link: <a>no href</a>, not. </p><p> OK: <a href="#">hoho</a></p>
<p> a link: no href, not. </p><p> OK: <a href="#">hoho</a></p>
</code>```

I've used a shorter made-up HTML string, but I checked with the question's example as well.  There are other ways to do this with Mojo and it's fun (and useful) exploring them.

For example, process only the links for which href attribute isn't defined, by filtering first

```<code>$_->replace($_->text) for
    $dom -> find("a")
         -> grep( sub { not defined $_->attr->{href} } )
         -> each;
</code>```

Or, process directly

```<code>$dom -> find("a")
     -> each( sub {
            $_->replace($_->text) if not defined $_->attr->{href}
        });
</code>```

Body:
I wrote a script to check all URLs in an HTML file and remove them with HTTP::Tiny and delete, but it left a bunch of incomplete anchor tags like text here throughout the database. These changes have already been made and the script doesn't need to be run again.

The script read from a database where this info is stored.

The goal now is to strip the text here while leaving everything else in the buffer plus the "text here" text.

I wrote another script that reads the database and includes the following regex:

$html_buffer =~ s/(.*?)(.*?)<\/a>(.*?)/$1$2$3/g;

but it doesn't work and I don't know why. Here's an example buffer:

This week, perhaps the most interesting articles include "Finding \r\n  that Windows is superior to Linux is biased," "How \r\n  to set up DNS for Linux VPNs," and "Writing \r\n  an Incident Handling and Recovery Plan."

Of course I want the regex to operate throughout the string, but also match multiple occurrences within the string.

Is this the most effective way to do this? How can I be sure to not remove the  at the end of the string like in the above example?

Body:
In principle, it is always advisable to use a proper parser.  An example is in the second part

That regex needs the /s modifier so that . matches linefeeds as well, and then it works.  Without it the pattern .*? stops at newlines. It's only by happenstance that the as it is regex still manages to match some of the string, appearing to "work but not right."

The point is that that string, with \ns in it, has newlines if it's assigned as double-quoted

my $html_buffer = " ... ";   # or:  = qq(...);

because then \n is interpreted as a linefeed.  If that string is given with single quotes,

my $html_buffer = ' ... ';   # or:  = q(...);

then there are no newlines in it, just occasional characters \ and n one after antoher, and .*? works as intended.

Finally: The substitution operator affects only the part of the string that has been matched (or less, if the pattern is written so to "drop" some of the match, for example with \K), so there is no reason for the leading and trailing (.*?).  All that's needed is

$html_buffer =~ s{<a>(.*?)</a>}{$1}sg;

And for a little extra safety add little extra spaces in all these patterns, for <\s*a\s*> so

$html_buffer =~ s{<\s*a\s*>(.*?)<\s*/a\s*>}{$1}sg;

To note, I'd find it a far superior solution to fix that original script so that it doesn't leave unintended bits and pieces behind.  I'd hazard a guess that that happened by using regex for HTML? It would be very surprising that any of the major libraries written to parse HTML/XML would cripple (valid I presume) HTML like that.

On the other hand, that can be done now, as well. If the remaining text and its not-links (<a> with no href attribute technically isn't a hyperlink) are exceedingly simple then it may be simpler to use a regex (fingers crossed) as asked; just this one time.

In all other cases, here's a very basic take with Mojo::DOM

use warnings;
use strict;
use feature 'say';

use Mojo::DOM;

my $html = q(<p> a link: <a>no href</a>, not. <p> OK: <a href="#">hoho</a>);

my $dom = Mojo::DOM->new( $html );
say $dom;

foreach my $link ($dom->find("a")->each) {

    if (not defined $link->attr->{href}) {
        # Replace this node with its text
        $link->replace( $link->text );
    }

}
say $dom;  # object stringifies to just its HTML

(or $link->strip; to remove the HTML element but leave its content, with the same result)

This prints

<p> a link: <a>no href</a>, not. </p><p> OK: <a href="#">hoho</a></p>
<p> a link: no href, not. </p><p> OK: <a href="#">hoho</a></p>

I've used a shorter made-up HTML string, but I checked with the question's example as well.  There are other ways to do this with Mojo and it's fun (and useful) exploring them.

For example, process only the links for which href attribute isn't defined, by filtering first

$_->replace($_->text) for
    $dom -> find("a")
         -> grep( sub { not defined $_->attr->{href} } )
         -> each;

Or, process directly

$dom -> find("a")
     -> each( sub {
            $_->replace($_->text) if not defined $_->attr->{href}
        });


问:
Why is MySQL code not accepting the relation for my table on SQL fiddle?
```<code>CREATE TABLE EMPLOYEE (
    EMPLOYEE_ID INT,
    FIRST_NAME VARCHAR(30),
    LAST_NAME VARCHAR(30),
    HIRE_DATE DATE,
    JOB_TITLE VARCHAR(30),
    SHOP_ID INT,
    PRIMARY KEY(EMPLOYEE_ID),
    FOREIGN KEY (EMPLOYEE_ID) REFERENCES COFFEE_SHOP(SHOP_ID)
);
CREATE TABLE COFFEE_SHOP(
    SHOP_ID INT AUTO_INCREMENT,
    SHOP_NAME VARCHAR(50),
    CITY VARCHAR(50),
    STATE CHAR(2),
    PRIMARY KEY(SHOP_ID)
);
CREATE TABLE COFFEE (
    COFFEE_ID INT AUTO_INCREMENT,
    SHOP_ID INT,
    SUPPLIER_ID INT,
    COFFEE_NAME VARCHAR(30),
    PRICE_PER_POUND NUMERIC(2,5),
    PRIMARY KEY(COFFEE_ID),
    FOREIGN KEY (SHOP_ID) REFERENCES COFFEE_SHOP(SHOP_ID),
    FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER(SUPPLIER_ID)
);
CREATE TABLE SUPPLIER (
    SUPPLIER_ID INT AUTO_INCREMENT,
    COMPANY_NAME VARCHAR(50),
    COUNTRY VARCHAR(30),
    SALES_CONTACT_NAME VARCHAR(60),
    EMAIL VARCHAR(50) NOT NULL,
    PRIMARY KEY(SUPPLIER_ID)
);
ERROR: relation "coffee_shop" does not exist
</code>```

答:
When you add a reference to another table, that other table must exist. In this case the error can be solved by reordering the creation of tables.

For example:

```<code>CREATE TABLE COFFEE_SHOP(
    SHOP_ID INT AUTO_INCREMENT,
    SHOP_NAME VARCHAR(50),
    CITY VARCHAR(50),
    STATE CHAR(2),
    PRIMARY KEY(SHOP_ID)
);

CREATE TABLE EMPLOYEE (
    EMPLOYEE_ID INT,
    FIRST_NAME VARCHAR(30),
    LAST_NAME VARCHAR(30),
    HIRE_DATE DATE,
    JOB_TITLE VARCHAR(30),
    SHOP_ID INT,
    PRIMARY KEY(EMPLOYEE_ID),
    FOREIGN KEY (EMPLOYEE_ID) REFERENCES COFFEE_SHOP(SHOP_ID)
);

CREATE TABLE SUPPLIER (
    SUPPLIER_ID INT AUTO_INCREMENT,
    COMPANY_NAME VARCHAR(50),
    COUNTRY VARCHAR(30),
    SALES_CONTACT_NAME VARCHAR(60),
    EMAIL VARCHAR(50) NOT NULL,
    PRIMARY KEY(SUPPLIER_ID)
);

CREATE TABLE COFFEE (
    COFFEE_ID INT AUTO_INCREMENT,
    SHOP_ID INT,
    SUPPLIER_ID INT,
    COFFEE_NAME VARCHAR(30),
    PRICE_PER_POUND NUMERIC(5,2),
    PRIMARY KEY(COFFEE_ID),
    FOREIGN KEY (SHOP_ID) REFERENCES COFFEE_SHOP(SHOP_ID),
    FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER(SUPPLIER_ID)
);
</code>```

See running example at DB Fiddle.

Body:
When you add a reference to another table, that other table must exist. In this case the error can be solved by reordering the creation of tables.

For example:

CREATE TABLE COFFEE_SHOP(
    SHOP_ID INT AUTO_INCREMENT,
    SHOP_NAME VARCHAR(50),
    CITY VARCHAR(50),
    STATE CHAR(2),
    PRIMARY KEY(SHOP_ID)
);

CREATE TABLE EMPLOYEE (
    EMPLOYEE_ID INT,
    FIRST_NAME VARCHAR(30),
    LAST_NAME VARCHAR(30),
    HIRE_DATE DATE,
    JOB_TITLE VARCHAR(30),
    SHOP_ID INT,
    PRIMARY KEY(EMPLOYEE_ID),
    FOREIGN KEY (EMPLOYEE_ID) REFERENCES COFFEE_SHOP(SHOP_ID)
);

CREATE TABLE SUPPLIER (
    SUPPLIER_ID INT AUTO_INCREMENT,
    COMPANY_NAME VARCHAR(50),
    COUNTRY VARCHAR(30),
    SALES_CONTACT_NAME VARCHAR(60),
    EMAIL VARCHAR(50) NOT NULL,
    PRIMARY KEY(SUPPLIER_ID)
);

CREATE TABLE COFFEE (
    COFFEE_ID INT AUTO_INCREMENT,
    SHOP_ID INT,
    SUPPLIER_ID INT,
    COFFEE_NAME VARCHAR(30),
    PRICE_PER_POUND NUMERIC(5,2),
    PRIMARY KEY(COFFEE_ID),
    FOREIGN KEY (SHOP_ID) REFERENCES COFFEE_SHOP(SHOP_ID),
    FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER(SUPPLIER_ID)
);

See running example at DB Fiddle.


问:
RTFMP - Remote stream not showing
I'm trying to create a 2-way videochat. Your own webcam shows perfectly fine, but the other doesn't. I used this page as an example: http://www.adobe.com/devnet/flashmediaserver/articles/p2p_apps_cirrus_lccs.html

Following the steps on the page doesn't seem to work for me. I exchange the peer IDs via PHP. I make my Flash visit a page, which stores the peer ID in the database using a POST request. To fetch the peer ID of the partner, I use PHP sessions, which store both your ID, and that of your partner. I can then use these variables to visit another PHP page, which echoes the partner's peer ID. Both are the same as in the database, so there's nothing wrong with that.

The NetConnection:

```<code>Connection = new NetConnection();
Connection.addEventListener(NetStatusEvent.NET_STATUS, CheckConnect);
Connection.connect(RTFMP + DevKey);
</code>```

This is how I set up your own webcam plus its NetStream:

```<code>StreamOut = new NetStream(Connection, NetStream.DIRECT_CONNECTIONS);
var SelfCam:DynamicStreamingVideoSource = new DynamicStreamingVideoSource();
var VideoItems:Vector.<DynamicStreamingVideoItem>;
VideoItems = new Vector.<DynamicStreamingVideoItem>();
VideoItems[0] = new DynamicStreamingVideoItem();

SelfCam.host = "";
SelfCam.streamType = StreamType.LIVE;
SelfCam.streamItems = VideoItems;

Self.source = SelfCam;

var Cam:Camera = Camera.getCamera();
var Mic:Microphone = Microphone.getMicrophone();
Cam.setMode(380, 255, 15);
Cam.setQuality(0, 80);
Self.videoObject.attachCamera(Cam);

StreamOut.attachAudio(Mic);
StreamOut.attachCamera(Cam);
StreamOut.publish("vids");
</code>```

And this is how I receive the published stream "vids":

```<code>StreamIn = new NetStream(Connection, OtherID);
StreamIn.play("vids");
StreamIn.client = this;
Other.videoObject.attachNetStream(StreamIn);
</code>```

The Other and Self objects are of type <s:VideoDisplay>.

I'm sure it must be something pretty damn simple, but I can't seem to lay my finger on it.

答: Never mind, I had to use mx:VideoDisplay rather than s:VideoDisplay.</p>

Title: RTFMP - Remote stream not showing

Body:
I'm trying to create a 2-way videochat. Your own webcam shows perfectly fine, but the other doesn't. I used this page as an example: http://www.adobe.com/devnet/flashmediaserver/articles/p2p_apps_cirrus_lccs.html

Following the steps on the page doesn't seem to work for me. I exchange the peer IDs via PHP. I make my Flash visit a page, which stores the peer ID in the database using a POST request. To fetch the peer ID of the partner, I use PHP sessions, which store both your ID, and that of your partner. I can then use these variables to visit another PHP page, which echoes the partner's peer ID. Both are the same as in the database, so there's nothing wrong with that.

The NetConnection:

Connection = new NetConnection();
Connection.addEventListener(NetStatusEvent.NET_STATUS, CheckConnect);
Connection.connect(RTFMP + DevKey);

This is how I set up your own webcam plus its NetStream:

StreamOut = new NetStream(Connection, NetStream.DIRECT_CONNECTIONS);
var SelfCam:DynamicStreamingVideoSource = new DynamicStreamingVideoSource();
var VideoItems:Vector.<DynamicStreamingVideoItem>;
VideoItems = new Vector.<DynamicStreamingVideoItem>();
VideoItems[0] = new DynamicStreamingVideoItem();

SelfCam.host = "";
SelfCam.streamType = StreamType.LIVE;
SelfCam.streamItems = VideoItems;

Self.source = SelfCam;

var Cam:Camera = Camera.getCamera();
var Mic:Microphone = Microphone.getMicrophone();
Cam.setMode(380, 255, 15);
Cam.setQuality(0, 80);
Self.videoObject.attachCamera(Cam);

StreamOut.attachAudio(Mic);
StreamOut.attachCamera(Cam);
StreamOut.publish("vids");

And this is how I receive the published stream "vids":

StreamIn = new NetStream(Connection, OtherID);
StreamIn.play("vids");
StreamIn.client = this;
Other.videoObject.attachNetStream(StreamIn);

The Other and Self objects are of type <s:VideoDisplay>.

I'm sure it must be something pretty damn simple, but I can't seem to lay my finger on it.