问:
white space appears on right side of page at a screen width of 745px
I'm doing the media queries and I noticed when the screen is at a width of 745px a small gap of white space appears on the right side of the screen. I've hovered over it from top to bottom and can't find any elements sticking out? I also have one media query at 745px and that's not the issue? Any help would be much appreciated. Thank you:)
https://jsfiddle.net/4av5mq13/

const ham = document.querySelector('.nav-box');
const menu = document.querySelector('.menu');
const menuClose = document.querySelector('#menu-close');
const leftArrow = document.querySelector('#left');
const rightArrow = document.querySelector('#right');
const img = document.querySelector('.image-slider');
let num = 1;

ham.addEventListener('click', function() {
 ham.classList.add('ham-open');
 menu.style.marginLeft = '50px';
})

menuClose.addEventListener('click', function() {
 ham.classList.remove('ham-open');
 menu.style.marginLeft = '-700px';
})

leftArrow.addEventListener('click', function() {
 num--;
 if(num > 0) {
  img.style.backgroundImage = 'url(img/fam-' + num + '.jpeg)';
  console.log(num);
  console.log(img.style.backgroundImage);
 } else {
  num = 4;
  img.style.backgroundImage = 'url(img/fam-' + num + '.jpeg)';
 }
})

rightArrow.addEventListener('click', function() {
 num++;
 if(num <= 4) {
  img.style.backgroundImage = 'url(img/fam-' + num + '.jpeg)';
  console.log(num);
  console.log(img.style.backgroundImage);
 } else {
  num = 1;
  img.style.backgroundImage = 'url(img/fam-' + num + '.jpeg)';
 }
})

// window.sr = ScrollReveal();

// sr.reveal('.logo-wrap', {
//  duration: 2000
// });

// sr.reveal('.w1', {
//  duration: 2000,
//  origin: 'bottom'
// });

// sr.reveal('.w2', {
//  duration: 3000,
//  origin: 'bottom'
// });

// sr.reveal('.w3', {
//  duration: 4000,
//  origin: 'bottom'
// });

// sr.reveal('.hours-line-left', {
//  duration: 1000,
//  origin: 'left',
//  distance: '200px'
// });

// sr.reveal('.hours-line-right', {
//  duration: 1000,
//  origin: 'right',
//  distance: '200px'
// });

// sr.reveal('.contact-line', {
//  duration: 1000,
//  origin: 'bottom',
//  distance: '250px'
// });

// sr.reveal('.burrito', {
//  duration: 1000,
//  origin: 'right',
//  distance: '250px'
// });

// sr.reveal('.taco', {
//  duration: 1000,
//  origin: 'right',
//  distance: '250px'
// });

// sr.reveal('.guac', {
//  duration: 1000,
//  origin: 'right',
//  distance: '250px'
// });

// sr.reveal('.nachos', {
//  duration: 1000,
//  origin: 'bottom',
//  distance: '250px'
// });

// sr.reveal('.hot', {
//  duration: 1000,
//  origin: 'left',
//  distance: '250px'
// });

// sr.reveal('.back-to-top', {
//  duration: 1000,
//  origin: 'bottom',
// });

// sr.reveal('.btp-arrow', {
//  duration: 1500,
//  origin: 'top',
//  distance: '250px'
// });```

答:
.map and #right are overflowing the right sides of their ancestors at that viewport width.

Add this rule:

```<code>.image-slider-wrap,
body>footer {
  overflow: hidden;
}
</code>```

Body:
.map and #right are overflowing the right sides of their ancestors at that viewport width.

Add this rule:

.image-slider-wrap,
body>footer {
  overflow: hidden;
}


来源: stackexchange

问:
How to output user input in a different webpage?
I am setting up a website for ordering pizza and want to be able to output the user's orders on the checkout page. I need to know which image the user clicked, each image is a different pizza. The sauce is working perfectly because I can use a form with a submit button, however for the OnlinePizzaOrderingPage.html I cannot use a submit button. I have included the sql tag below because sql is allowed to be used, however I don't know if it will help in this scenario. How do I achieve display the type of pizza the user selected on the ShoppingCart.php page?

I have tried using POST and GET with php and using Javascript.

OnlinePizzaOrderingPage.html

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <title>Online Pizza Ordering Page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
    <script>
    function imageTitle(title){
     alert(title);
     console.log(title);
    }
    </script>
    </head>
    <body>
    <h1>Online Pizza Ordering Page</h1>
    <a href="Detailedsauceandquantitypage.html"><img src="supreme.jpg"
    width="82" height="86" title="Supreme" alt="Supreme"
    onclick="imageTitle(this.title);"></a>
    <a href="Detailedsauceandquantitypage.html"><img src="meatlover.jpg"
    width="82" height="86" title="Meatlover" alt="Meatlover"
    onclick="imageTitle(this.title);"></a>
    <a href="Detailedsauceandquantitypage.html"><img src="hawaii.jpg"
    width="82" height="86" title="Hawaii" alt="Hawaii"
    onclick="imageTitle(this.title);"></a>
    <a href="Detailedsauceandquantitypage.html"><img
src="fourseasons.jpg"
    width="82" height="86" title="Four Seasons" alt="Four Seasons"
    onclick="imageTitle(this.title);"></a>
    <a href="Detailedsauceandquantitypage.html"><img src="vege.jpg"
width="82"
    height="86" title="Vege" alt="Vege"
onclick="imageTitle(this.title);"></a>
    </body>
    </html>
</code>```

DetailedSauceandquantitypage.html

```<code>    <!DOCTYPE html>
    <html>
        <head>
            <script src="script.js"></script>
            <title>Detailed sauce and quantity page</title>
            <link rel="stylesheet" type="text/css" href="mystyle.css">
        </head>
        <body>
            <h1>Detailed sauce and quantity page</h1>
                <form action="ShoppingCartpage.php" method="POST">
                    <img src="bbq.jpg" alt="BBQ">
                    <label for="numberOfSauces">Number of Pizzas
    (0-100):</label>
                    <input type="number" name="bbqPizza" min="0"
    max="100" value="0"><br>
                    <img src="tomato.jpg" alt="Tomato">
                    <label for="numberOfSauces">Number of Pizzas
   (0-100):</label>
                    <input type="number" name="tomatoPizza"
    min="0" max="100" value="0"><br>
                    <img src="salsa.jpg" alt="Salsa">
                    <label for="numberOfSauces">Number of Pizzas
    (0-100):</label>
                    <input type="number" name="salsaPizza" min="0"
    max="100" value="0"><br>
                <input type="submit" value="Add to cart"
    name="submit"><br>
                </form>
        </body>
    </html>
</code>```

ShoppingCartpage.php

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <title>Shopping Cart page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
    <script>
    function imageTitle(title){
     alert(title);
     console.log(title);
    }
    </script>
    </head>
    <body>
    <h1>Shopping Cart page</h1>
    <?php
    // define variables and set to empty values
    $bbqPizza = $tomatoPizza = $salsaPizza = "";

    if ( isset( $_POST['submit'] ) ) {
        $bbq = $_POST["bbqPizza"];
        $tomato = $_POST["tomatoPizza"];
        $salsa = $_POST["salsaPizza"];
        echo $bbq . " pizzas with bbq sauce, " . $tomato . " pizzas with
    tomato sauce and " . $salsa . " pizzas with salsa sauce.";
    }
    ?>
    <br>
    <a href="OnlinePizzaOrderingPage.html">Add more pizzas to cart</a>
    <a href="Checkoutpage.html">Go to checkout</a>
    </body>
    </html>
</code>```

Expected results are the pizza type selected by the user through clicking the images on OnlinePizzaOrderingPage.html to be displayed on the ShoppingCart.php page.

答:
.html has no native way of retrieving or storing request values (post/get) that can then be passed to a PHP file. You would need to change DetailedSauceandquantitypage.html to to a PHP page, and use a querystring in OnlinePizzaOrderingPage.html to determine which link was clicked on, such as href="DetailedSauceandquantitypage.php?pizza=Supreme".

As was mentioned in a previous question you made, you should seriously
  consider converting all of your .html files to .php, to avoid
  having make a ton of changes later, when you want to expand your
  application files to use php code.

For more details please see Variables From External Sources

If you are using Apache web server you could use SSI (server side includes), but as you are using PHP, it would be a lot simpler and less error prone to convert to PHP instead.

Example:

I removed some of the javascript for brevity. I am also not sure how you would like to be able to add on to or checkout the current order, aside from storing it in a database.

OnlinePizzaOrderingPage.html

```<code><!DOCTYPE html>
<html>
<head>
    <title>Online Pizza Ordering Page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
    <h1>Online Pizza Ordering Page</h1>
    <a href="Detailedsauceandquantitypage.php?pizza=supreme">
        <img src="supreme.jpg" width="82" height="86" title="Supreme" alt="Supreme">
    </a>
    <a href="Detailedsauceandquantitypage.php?pizza=meatlover">
        <img src="meatlover.jpg" width="82" height="86" title="Meatlover" alt="Meatlover">
    </a>
    <a href="Detailedsauceandquantitypage.php?pizza=hawaii">
        <img src="hawaii.jpg" width="82" height="86" title="Hawaii" alt="Hawaii">
    </a>
    <a href="Detailedsauceandquantitypage.php?pizza=fourseasons">
        <img src="fourseasons.jpg" width="82" height="86" title="Four Seasons" alt="Four Seasons">
    </a>
    <a href="Detailedsauceandquantitypage.php?pizza=vege">
        <img src="vege.jpg" width="82" height="86" title="Vege" alt="Vege">
    </a>
</body>
</html>
</code>```

DetailedSauceandquantitypage.php

```<code><!DOCTYPE html>
<html>
<head>
    <script src="script.js"></script>
    <title>Detailed sauce and quantity page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
    <h1>Detailed sauce and quantity page</h1>
    <form action="ShoppingCartpage.php" method="POST">
        <!-- set form value to retrieve and pass the selected pizza to the cart -->
        <input type="hidden" name="pizza" value="<?php echo htmlspecialchars($_GET['pizza'], ENT_QUOTES, 'UTF-8', false); ?>">

        <img src="bbq.jpg" alt="BBQ">
        <label for="numberOfSauces">Number of Pizzas (0-100):</label>
        <input type="number" name="bbqPizza" min="0" max="100" value="0">
        <br>
        <img src="tomato.jpg" alt="Tomato">
        <label for="numberOfSauces">Number of Pizzas (0-100):</label>
        <input type="number" name="tomatoPizza" min="0" max="100" value="0">
        <br>
        <img src="salsa.jpg" alt="Salsa">
        <label for="numberOfSauces">Number of Pizzas (0-100):</label>
        <input type="number" name="salsaPizza" min="0" max="100" value="0">
        <br>
        <input type="submit" value="Add to cart" name="submit">
        <br>
    </form>
</body>
</html>
</code>```

ShoppingCartpage.php

```<code><!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
    <h1>Shopping Cart page</h1>
    <?php
    // define variables and set to empty values
    $bbqPizza = $tomatoPizza = $salsaPizza = "";

    if ( isset( $_POST['submit'] ) ) {
        $pizza = $_POST['pizza']; //value from first page
        $bbq = $_POST["bbqPizza"];
        $tomato = $_POST["tomatoPizza"];
        $salsa = $_POST["salsaPizza"];
        echo "A " . $pizza . " pizza, " .  $bbq . " pizzas with bbq sauce, " . $tomato . " pizzas with tomato sauce and " . $salsa . " pizzas with salsa sauce.";

       //where are these stored to Add More or Checkout?
    }
    ?>
    <br>
    <a href="OnlinePizzaOrderingPage.html">Add more pizzas to cart</a>
    <a href="Checkoutpage.html">Go to checkout</a>
</body>
</html>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am setting up a website for ordering pizza and want to be able to output the user's orders on the checkout page. I need to know which image the user clicked, each image is a different pizza. The sauce is working perfectly because I can use a form with a submit button, however for the OnlinePizzaOrderingPage.html I cannot use a submit button. I have included the sql tag below because sql is allowed to be used, however I don't know if it will help in this scenario. How do I achieve display the type of pizza the user selected on the ShoppingCart.php page?

I have tried using POST and GET with php and using Javascript.

OnlinePizzaOrderingPage.html

    <!DOCTYPE html>

    <title>Online Pizza Ordering Page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">

Online Pizza Ordering Page

DetailedSauceandquantitypage.html

    <!DOCTYPE html>

            <title>Detailed sauce and quantity page</title>
            <link rel="stylesheet" type="text/css" href="mystyle.css">

Detailed sauce and quantity page

                <form action="ShoppingCartpage.php" method="POST">

                    Number of Pizzas
    (0-100):
                    <input type="number" name="bbqPizza" min="0"
    max="100" value="0">

                    Number of Pizzas
   (0-100):
                    <input type="number" name="tomatoPizza"
    min="0" max="100" value="0">

                    Number of Pizzas
    (0-100):
                    <input type="number" name="salsaPizza" min="0"
    max="100" value="0">

                <input type="submit" value="Add to cart"
    name="submit">

                </form>

ShoppingCartpage.php

    <!DOCTYPE html>

    <title>Shopping Cart page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">

Shopping Cart page

    <?php
    // define variables and set to empty values
    $bbqPizza = $tomatoPizza = $salsaPizza = "";

    if ( isset( $_POST['submit'] ) ) {
        $bbq = $_POST["bbqPizza"];
        $tomato = $_POST["tomatoPizza"];
        $salsa = $_POST["salsaPizza"];
        echo $bbq . " pizzas with bbq sauce, " . $tomato . " pizzas with
    tomato sauce and " . $salsa . " pizzas with salsa sauce.";
    }
    ?>

    Add more pizzas to cart
    Go to checkout

Expected results are the pizza type selected by the user through clicking the images on OnlinePizzaOrderingPage.html to be displayed on the ShoppingCart.php page.

Body:
.html has no native way of retrieving or storing request values (post/get) that can then be passed to a PHP file. You would need to change DetailedSauceandquantitypage.html to to a PHP page, and use a querystring in OnlinePizzaOrderingPage.html to determine which link was clicked on, such as href="DetailedSauceandquantitypage.php?pizza=Supreme".

As was mentioned in a previous question you made, you should seriously
  consider converting all of your .html files to .php, to avoid
  having make a ton of changes later, when you want to expand your
  application files to use php code.

For more details please see Variables From External Sources

If you are using Apache web server you could use SSI (server side includes), but as you are using PHP, it would be a lot simpler and less error prone to convert to PHP instead.

Example:

I removed some of the javascript for brevity. I am also not sure how you would like to be able to add on to or checkout the current order, aside from storing it in a database.

OnlinePizzaOrderingPage.html

<!DOCTYPE html>
<html>
<head>
    <title>Online Pizza Ordering Page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
    <h1>Online Pizza Ordering Page</h1>
    <a href="Detailedsauceandquantitypage.php?pizza=supreme">
        <img src="supreme.jpg" width="82" height="86" title="Supreme" alt="Supreme">
    </a>
    <a href="Detailedsauceandquantitypage.php?pizza=meatlover">
        <img src="meatlover.jpg" width="82" height="86" title="Meatlover" alt="Meatlover">
    </a>
    <a href="Detailedsauceandquantitypage.php?pizza=hawaii">
        <img src="hawaii.jpg" width="82" height="86" title="Hawaii" alt="Hawaii">
    </a>
    <a href="Detailedsauceandquantitypage.php?pizza=fourseasons">
        <img src="fourseasons.jpg" width="82" height="86" title="Four Seasons" alt="Four Seasons">
    </a>
    <a href="Detailedsauceandquantitypage.php?pizza=vege">
        <img src="vege.jpg" width="82" height="86" title="Vege" alt="Vege">
    </a>
</body>
</html>

DetailedSauceandquantitypage.php

<!DOCTYPE html>
<html>
<head>
    <script src="script.js"></script>
    <title>Detailed sauce and quantity page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
    <h1>Detailed sauce and quantity page</h1>
    <form action="ShoppingCartpage.php" method="POST">
        <!-- set form value to retrieve and pass the selected pizza to the cart -->
        <input type="hidden" name="pizza" value="<?php echo htmlspecialchars($_GET['pizza'], ENT_QUOTES, 'UTF-8', false); ?>">

        <img src="bbq.jpg" alt="BBQ">
        <label for="numberOfSauces">Number of Pizzas (0-100):</label>
        <input type="number" name="bbqPizza" min="0" max="100" value="0">
        <br>
        <img src="tomato.jpg" alt="Tomato">
        <label for="numberOfSauces">Number of Pizzas (0-100):</label>
        <input type="number" name="tomatoPizza" min="0" max="100" value="0">
        <br>
        <img src="salsa.jpg" alt="Salsa">
        <label for="numberOfSauces">Number of Pizzas (0-100):</label>
        <input type="number" name="salsaPizza" min="0" max="100" value="0">
        <br>
        <input type="submit" value="Add to cart" name="submit">
        <br>
    </form>
</body>
</html>

ShoppingCartpage.php

<!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart page</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
    <h1>Shopping Cart page</h1>
    <?php
    // define variables and set to empty values
    $bbqPizza = $tomatoPizza = $salsaPizza = "";

    if ( isset( $_POST['submit'] ) ) {
        $pizza = $_POST['pizza']; //value from first page
        $bbq = $_POST["bbqPizza"];
        $tomato = $_POST["tomatoPizza"];
        $salsa = $_POST["salsaPizza"];
        echo "A " . $pizza . " pizza, " .  $bbq . " pizzas with bbq sauce, " . $tomato . " pizzas with tomato sauce and " . $salsa . " pizzas with salsa sauce.";

       //where are these stored to Add More or Checkout?
    }
    ?>
    <br>
    <a href="OnlinePizzaOrderingPage.html">Add more pizzas to cart</a>
    <a href="Checkoutpage.html">Go to checkout</a>
</body>
</html>


问:
cant get the uitextview height dynamically correct
I am having issue in getting the correct size of uitextview.In my application i am fetching the data from webservice  and i set the height of uitextview as per the data from webservice .But whenever there is space in first 35 letters(frame of my textview is (20,0,255,2000)). then the hjeight calculated is always one line less then correct  height and even the uitext view starts to print the line after space in the new line (may be word is big thats why ??).

So i am getting the wrong text view height.

The text view apears somwethibng like this :

firstword
spacesspacesspacesspaces
spacesspacesspacesspaces
spacesspacesspacesspaces
spacesspacesspacesspaces
spacesspacesspacesspaces

When i enter text which is say without spaces it gives me correct height suppose say the data is  "ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"
Then in the above scenerio Cgsize will generate proper result for me .

Here i am not using UILabel is because i want link detection thats why .
If anyone has anyother suggestions it is highly welcomed.

Regards
Mrugen

答:
Using NSString's sizeWithFont methods doesn't really work for a text view. It works great for a UILabel, but text views seem to have extra padding around the text. If you use that method, you end up with a size that's a little short.

UITextView is a subclass of UIScrollView. After you set the textview's text property, its contentSize property is automatically updated to fit the text. So, if you want to set the text view's height to fit its text just do:

```<code>textView.text    = @"some text";
CGRect rect      = textView.frame;
rect.size.height = textView.contentSize.height;
textView.frame   = rect;
</code>```

That will set your textView's hight so it contains the text.

ContentLicense: CC BY-SA 3.0

Body:
Using NSString's sizeWithFont methods doesn't really work for a text view. It works great for a UILabel, but text views seem to have extra padding around the text. If you use that method, you end up with a size that's a little short.

UITextView is a subclass of UIScrollView. After you set the textview's text property, its contentSize property is automatically updated to fit the text. So, if you want to set the text view's height to fit its text just do:

textView.text    = @"some text";
CGRect rect      = textView.frame;
rect.size.height = textView.contentSize.height;
textView.frame   = rect;

That will set your textView's hight so it contains the text.


问:
How can I isolate the username of an email address using JavaScript?
I have an email list, but in order to assign the username to a new variable, I need to delete all the characters after the @ symbol.
Is there a way to do this via regex in javascript?</p>

```<code>var input = "john@email.com" //this is my input
var result = "john" //this is what I need after stripping all characters after the @ symbol

function strip(input){
this.result =  //how can I strip everything after the @ ??
}
</code>```

答:
If not validation needs to be done on the email string, then you could use

function strip(input){
        var pattern = /(.*?)@.*?/
        var output = input.match(pattern);
        var result =  output && output[1] ? output[1] : ""   //how can I strip everything after the @ ??
        console.log("Input--> " + input + "  Output --> " + result);
    }

    strip("john@email.com");
    strip("@email.com");
    strip("email.com");
    strip("john@");```

But you would still end up with "John" as a result if the input email string is "John@"

Body:
I have an email list, but in order to assign the username to a new variable, I need to delete all the characters after the @ symbol.
Is there a way to do this via regex in javascript?

var input = "john@email.com" //this is my input
var result = "john" //this is what I need after stripping all characters after the @ symbol

function strip(input){
this.result =  //how can I strip everything after the @ ??
}

Body:
If not validation needs to be done on the email string, then you could use

function strip(input){
        var pattern = /(.*?)@.*?/
        var output = input.match(pattern);
        var result =  output && output[1] ? output[1] : ""   //how can I strip everything after the @ ??
        console.log("Input--> " + input + "  Output --> " + result);
    }

    strip("john@email.com");
    strip("@email.com");
    strip("email.com");
    strip("john@");

But you would still end up with "John" as a result if the input email string is "John@"


问:
Upload folder and all its content in JavaScript
How do I upload the content of a folder using JavaScript (client side)? The FileSystem API has not been adopted by browsers other than Chrome; I only get a File item with the name of the folder.

It should be possible, because Google Drive allows to drop a folder and all the content (folders and files) will be uploaded automatically.

答:
For implement the folder upload, you need apply both of JS side and server side:

At JS side I use these methods (from a teacher that posted at StackoverFlow - https://stackoverflow.com/a/47935286/11544097) to loop and file all file, folder content and subfolders:

```<code>function makedir(entries) {
  const systems = entries.map(entry => traverse(entry, {}));
  return Promise.all(systems);

  async function traverse(entry, fs) {
    if (entry.isDirectory) {
      fs[entry.name] = {};
      let dirReader = entry.createReader();
      await new Promise((res, rej) => {
    dirReader.readEntries(async entries => {
      for(let e of entries) {
        await traverse(e, fs[entry.name]);
      }
      res();
    }, rej);
      });
    } else if (entry.isFile) {
      await new Promise((res, rej) => {
    entry.file(file => {
      fs[entry.name] = file;
      res();
    }, rej);
      });
    }
  return fs;
  }
};

function checkFile(obj){
    return obj instanceof File;
};

function exactFile(system_trees, relativePath, files){
    for (var i = 0; i < system_trees.length; i++){
        for (var property in system_trees[i]) {
            if (system_trees[i].hasOwnProperty(property)) {
                if (checkFile(system_trees[i][property])){
                    system_trees[i][property]["relativePath"] = relativePath;
                    files.push(system_trees[i][property]);
                } else {
                    files.concat(exactFile([system_trees[i][property]], (typeof relativePath !== 'undefined' && relativePath !== '' ? (relativePath + '/') : '') + property, files));
                }
            }
        }
    }
    return files;
};

function readDropped(dT,_data) {
  const entries = [...dT.items].map(item => {
      return item.webkitGetAsEntry ? item.webkitGetAsEntry() : null;
    })
    .filter(entry => entry);
  if (entries.length) {
    makedir(entries).then(function(system_trees){
        var files = exactFile(system_trees, "", []);
        c(_data, files);
    }).catch(function(){
        var files = dT.files;
        c(_data, files);
    });
  } else {
        var files = dT.files;
        c(_data, files);
  }
};
</code>```

The 'dT' is drop event (e.originalEvent.dataTransfer) and '_data' that is Ajax upload submit form.

You also need a upload library or write it by yourself to send to file into server by ajax upload. In the code example above, I use formstone upload library (https://formstone.it/components/upload/)

At server side: You need to process the form data that was sent from JS side, al most case you need to process file by file with relative path info enclosed from the File object.

One more note, just set 'multiple' attribute at file upload input, NO need a 'webkitdirectory' or 'directory'. They caused the user can not choose the file (only folder allowed)

The result you will have the uploading system support all folder and files will keeping their structure like Google Drive :).

There is the tool (https://freetoolonline.com/zip-file.html) that I have wrote that supports folder upload based on the ideal I have explained above.

Body:
For implement the folder upload, you need apply both of JS side and server side:

At JS side I use these methods (from a teacher that posted at StackoverFlow - https://stackoverflow.com/a/47935286/11544097) to loop and file all file, folder content and subfolders:

function makedir(entries) {
  const systems = entries.map(entry => traverse(entry, {}));
  return Promise.all(systems);

  async function traverse(entry, fs) {
    if (entry.isDirectory) {
      fs[entry.name] = {};
      let dirReader = entry.createReader();
      await new Promise((res, rej) => {
    dirReader.readEntries(async entries => {
      for(let e of entries) {
        await traverse(e, fs[entry.name]);
      }
      res();
    }, rej);
      });
    } else if (entry.isFile) {
      await new Promise((res, rej) => {
    entry.file(file => {
      fs[entry.name] = file;
      res();
    }, rej);
      });
    }
  return fs;
  }
};

function checkFile(obj){
    return obj instanceof File;
};

function exactFile(system_trees, relativePath, files){
    for (var i = 0; i < system_trees.length; i++){
        for (var property in system_trees[i]) {
            if (system_trees[i].hasOwnProperty(property)) {
                if (checkFile(system_trees[i][property])){
                    system_trees[i][property]["relativePath"] = relativePath;
                    files.push(system_trees[i][property]);
                } else {
                    files.concat(exactFile([system_trees[i][property]], (typeof relativePath !== 'undefined' && relativePath !== '' ? (relativePath + '/') : '') + property, files));
                }
            }
        }
    }
    return files;
};

function readDropped(dT,_data) {
  const entries = [...dT.items].map(item => {
      return item.webkitGetAsEntry ? item.webkitGetAsEntry() : null;
    })
    .filter(entry => entry);
  if (entries.length) {
    makedir(entries).then(function(system_trees){
        var files = exactFile(system_trees, "", []);
        c(_data, files);
    }).catch(function(){
        var files = dT.files;
        c(_data, files);
    });
  } else {
        var files = dT.files;
        c(_data, files);
  }
};

The 'dT' is drop event (e.originalEvent.dataTransfer) and '_data' that is Ajax upload submit form.

You also need a upload library or write it by yourself to send to file into server by ajax upload. In the code example above, I use formstone upload library (https://formstone.it/components/upload/)

At server side: You need to process the form data that was sent from JS side, al most case you need to process file by file with relative path info enclosed from the File object.

One more note, just set 'multiple' attribute at file upload input, NO need a 'webkitdirectory' or 'directory'. They caused the user can not choose the file (only folder allowed)

The result you will have the uploading system support all folder and files will keeping their structure like Google Drive :).

There is the tool (https://freetoolonline.com/zip-file.html) that I have wrote that supports folder upload based on the ideal I have explained above.


问:
is this use of objects redundant and/or inefficient?
I'm fairly inexperienced with using objects so I would really like some input.

I'm trying to remove comments from a list that have certain "unwanted words" in them, both the comments and the list of "unwanted words" are in ArrayList objects.

This is inside of a class called FormHelper, which contains the private member comments as an ArrayList, the auditList ArrayList is created locally in a member function called populateComments(), which then calls this function (below). PopulateComments() is called by the constructor, and so this function only gets called once, when an instance of FormHelper is created.

private void filterComments(ArrayList <String> auditList) {
    for(String badWord : auditList) {
        for (String thisComment : this.comments) {
            if(thisComment.contains(badWord)) {
                int index = this.comments.indexOf(thisComment);
                this.comments.remove(index);
            }
        }
    }
}
```

something about the way I implemented this doesn't feel right, I'm also concerned that I'm using ArrayList functions inefficiently. Is my suspicion correct?

答:
It is not particularly efficient.  However, finding a more efficient solution is not straightforward.

Lets step back to a simpler problem.

```<code>private void findBadWords(List <String> wordList, List <String> auditList) {
    for(String badWord : auditList) {
        for (String word : wordList) {
            if (word.equals(badWord)) {
                System.err.println("Found a bad word");
            }
        }
    }
}
</code>```

Suppose that wordList contains N words and auditList contains M words.  Some simple analysis will show that the inner loop is executed N x M times.   The N factor is unavoidable, but the M factor is disturbing.  It means that the more "bad" words you have to check for the longer it takes to check.

There is a better way to do this:

```<code>private void findBadWords(List <String> wordList, HashSet<String> auditWords) {
    for (String word : wordList) {
        if (auditWords.contains(word))) {
            System.err.println("Found a bad word");
        }
    }
}
</code>```

Why is that better?  It is better (faster) because HashSet::contains doesn't need to check all of the audit words one at a time.  In fact, in the optimal case it will check none of them (!) and the average case just one or two of them.  (I won't go into why, but if you want to understand read the Wikipedia page on hash tables.)

But your problem is more complicated.  You are using String::contains to test if each comment contains each bad word.  That is not a simple string equality test (as per my simplified version).

What to do?

Well one potential solution is to split the the comments into an array of words (e.g. using String::split and then user the HashSet lookup approach.   However:

That changes the behavior of your code.  (In a good way actually: read up on the Scunthorpe problem!)  You will now only match the audit words is they are actual words in the comment text.

Splitting a string into words is not cheap.  If you use String::split it entails creating and using a Pattern object to find the word boundaries, creating substrings for each word and putting them into an array.  You can probably do better, but it is always going to be a non-trivial calculation.

So the real question will be whether the optimization is going to pay off.  That is ultimately going to depend on the value of M; i.e. the number of bad words you are looking for.  The larger M is, the more likely it will be to split the comments into words and use a HashSet to test the words.

Another possible solution doesn't involve splitting the comments.  You could take the list of audit words and assemble them into a single regex like this:  \b(word-1|word-2|...|word-n)\b.  Then use this regex with Matcher::find to search each comment string for bad words.  The performance will depend on the optimizing capability of the regex engine in your Java platform.  It has the potential to be faster than splitting.

My advice would be to benchmark and profile your entire application before you start.  Only optimize:

when the benchmarking says that the overall performance of the requests where this comment checking occurs is concerning.  (If it is OK, don't waste your time optimizing.)

when the profiling says that this method is a performance hotspot.  (There is a good chance that the real hotspots are somewhere else.  If so, you should optimize them rather than this method.)

Note there is an assumption that you have (sufficiently) completed your application and created a realistic benchmark for it before you think about optimizing.  (Premature optimization is a bad idea ... unless you really know what you are doing.)

Body:
I'm fairly inexperienced with using objects so I would really like some input.

I'm trying to remove comments from a list that have certain "unwanted words" in them, both the comments and the list of "unwanted words" are in ArrayList objects.

This is inside of a class called FormHelper, which contains the private member comments as an ArrayList, the auditList ArrayList is created locally in a member function called populateComments(), which then calls this function (below). PopulateComments() is called by the constructor, and so this function only gets called once, when an instance of FormHelper is created.

private void filterComments(ArrayList <String> auditList) {
    for(String badWord : auditList) {
        for (String thisComment : this.comments) {
            if(thisComment.contains(badWord)) {
                int index = this.comments.indexOf(thisComment);
                this.comments.remove(index);
            }
        }
    }
}

something about the way I implemented this doesn't feel right, I'm also concerned that I'm using ArrayList functions inefficiently. Is my suspicion correct?

Body:
It is not particularly efficient.  However, finding a more efficient solution is not straightforward.

Lets step back to a simpler problem.

private void findBadWords(List <String> wordList, List <String> auditList) {
    for(String badWord : auditList) {
        for (String word : wordList) {
            if (word.equals(badWord)) {
                System.err.println("Found a bad word");
            }
        }
    }
}

Suppose that wordList contains N words and auditList contains M words.  Some simple analysis will show that the inner loop is executed N x M times.   The N factor is unavoidable, but the M factor is disturbing.  It means that the more "bad" words you have to check for the longer it takes to check.

There is a better way to do this:

private void findBadWords(List <String> wordList, HashSet<String> auditWords) {
    for (String word : wordList) {
        if (auditWords.contains(word))) {
            System.err.println("Found a bad word");
        }
    }
}

Why is that better?  It is better (faster) because HashSet::contains doesn't need to check all of the audit words one at a time.  In fact, in the optimal case it will check none of them (!) and the average case just one or two of them.  (I won't go into why, but if you want to understand read the Wikipedia page on hash tables.)

But your problem is more complicated.  You are using String::contains to test if each comment contains each bad word.  That is not a simple string equality test (as per my simplified version).

What to do?

Well one potential solution is to split the the comments into an array of words (e.g. using String::split and then user the HashSet lookup approach.   However:

That changes the behavior of your code.  (In a good way actually: read up on the Scunthorpe problem!)  You will now only match the audit words is they are actual words in the comment text.

Splitting a string into words is not cheap.  If you use String::split it entails creating and using a Pattern object to find the word boundaries, creating substrings for each word and putting them into an array.  You can probably do better, but it is always going to be a non-trivial calculation.

So the real question will be whether the optimization is going to pay off.  That is ultimately going to depend on the value of M; i.e. the number of bad words you are looking for.  The larger M is, the more likely it will be to split the comments into words and use a HashSet to test the words.

Another possible solution doesn't involve splitting the comments.  You could take the list of audit words and assemble them into a single regex like this:  \b(word-1|word-2|...|word-n)\b.  Then use this regex with Matcher::find to search each comment string for bad words.  The performance will depend on the optimizing capability of the regex engine in your Java platform.  It has the potential to be faster than splitting.

My advice would be to benchmark and profile your entire application before you start.  Only optimize:

when the benchmarking says that the overall performance of the requests where this comment checking occurs is concerning.  (If it is OK, don't waste your time optimizing.)

when the profiling says that this method is a performance hotspot.  (There is a good chance that the real hotspots are somewhere else.  If so, you should optimize them rather than this method.)

Note there is an assumption that you have (sufficiently) completed your application and created a realistic benchmark for it before you think about optimizing.  (Premature optimization is a bad idea ... unless you really know what you are doing.)


问:
Iterate an enum in ion-select
How to iterate an enum with ion-select using ngModel

```<code>export enum Escolaridade {
    ANALFABETO = "Analfabeto",
    DE_1_A_3ANOS = "de 1 a 3 anos",
    DE_4_A_7ANOS = "de 4 a 3 anos",
    MAIS_DE_8ANOS = "mais de 8 anos"
}

class Pessoa {
    ...
    public escolaridade:typeof Escolaridade =  Escolaridade;
}

export class CadastroPage {
    ...
    this.p = new Pessoa();
}

home.html
<ion-select interface="popover" [(ngModel)]="p.escolaridade">
<ion-select-option *ngFor="let escolaridade of p.escolaridade">
    {{escolaridade}}
</ion-select-option>
</ion-select>
</code>```

I need list items in ion-select-option and submit item selected to "this.p"

答:
To iterate values on an enum. You can write a function to extract values from the enum.</p>

```<code>extractValuesFromEnum(enum)
{
  const retVal = [];
  const keys = Object.keys(enum);
  for(let i=0; i < keys.length; i++)
  {
    if(i %2 !== 0 )  // odd elements in the array will be the values.
      {
        retVal.push(keys[i])
      }
  }
  return retVal
}
</code>```

Title: Iterate an enum in ion-select

Body:
How to iterate an enum with ion-select using ngModel

export enum Escolaridade {
    ANALFABETO = "Analfabeto",
    DE_1_A_3ANOS = "de 1 a 3 anos",
    DE_4_A_7ANOS = "de 4 a 3 anos",
    MAIS_DE_8ANOS = "mais de 8 anos"
}

class Pessoa {
    ...
    public escolaridade:typeof Escolaridade =  Escolaridade;
}

export class CadastroPage {
    ...
    this.p = new Pessoa();
}

home.html
<ion-select interface="popover" [(ngModel)]="p.escolaridade">
<ion-select-option *ngFor="let escolaridade of p.escolaridade">
    {{escolaridade}}
</ion-select-option>
</ion-select>

I need list items in ion-select-option and submit item selected to "this.p"

Body:
To iterate values on an enum. You can write a function to extract values from the enum.

extractValuesFromEnum(enum)
{
  const retVal = [];
  const keys = Object.keys(enum);
  for(let i=0; i < keys.length; i++)
  {
    if(i %2 !== 0 )  // odd elements in the array will be the values.
      {
        retVal.push(keys[i])
      }
  }
  return retVal
}


问:
Connecting Form Dropdown to Backend
I'm trying to add a feature to a web application where users can rate courses. Within the rating feature, there is a pre-set list of instructors that taught each course. This is stored within a postgres db as an array.

The course model (which the list of instructors is part of) and the review model are separate.

I have successfully created a form which shows the list of instructors as a dropdown when writing a review, but I have been unsuccessful in saving the name of the instructor in the column for the database.

I am unsure what to put in the last line for the following code for the data to save.

reviews_controller.rb

```<code>def create
    @review = Review.new(review_params)
    @review.user_id = current_user.id
    @review.course_id = @course.id
    @review.instructor_name =
</code>```

This is how I have displayed it in the front-end to allow users to select the instructors.

_form.html.erb

```<code><%= form.label "Instructor" %>
<%= select_tag :instructor_name, options_for_select(@course.instructors) %>
</code>```

I am expecting the name of the instructor selected to be saved in the database as opposed to the value as opposed to the index of the name.

答:
Try this</p>

```<code><%= select_tag :instructor_name, options_for_select(@course.instructors.collect { |i| [i, i] }) %>
</code>```

Title: Connecting Form Dropdown to Backend

Body:
I'm trying to add a feature to a web application where users can rate courses. Within the rating feature, there is a pre-set list of instructors that taught each course. This is stored within a postgres db as an array.

The course model (which the list of instructors is part of) and the review model are separate.

I have successfully created a form which shows the list of instructors as a dropdown when writing a review, but I have been unsuccessful in saving the name of the instructor in the column for the database.

I am unsure what to put in the last line for the following code for the data to save.

reviews_controller.rb

def create
    @review = Review.new(review_params)
    @review.user_id = current_user.id
    @review.course_id = @course.id
    @review.instructor_name =

This is how I have displayed it in the front-end to allow users to select the instructors.

_form.html.erb

<%= form.label "Instructor" %>
<%= select_tag :instructor_name, options_for_select(@course.instructors) %>

I am expecting the name of the instructor selected to be saved in the database as opposed to the value as opposed to the index of the name.

Body:
Try this

<%= select_tag :instructor_name, options_for_select(@course.instructors.collect { |i| [i, i] }) %>


问:
Why does .Net care when an assembly was built?
We had a situation where we were having issues with a DLL that was build in our office which is located in the Central time zone and then deployed onto a server located on the west coast (Pacific time zone).  We'd have issues with "UTCDate out of range" when trying to retrieve embedded resources from our DLL (via WebResource.axd).  Once we discovered this and updated the DLL's file time to match the web server's time, everything worked fine.

My question is: Why does .Net care when an assembly was built?

Thanks.

答:
This behavior connected to WebResource.axd caching algorithm.

Also you can look at nice touch solution of this problem.


问:
Flask blueprint error - Could not build url for endpoint
I am setting up a python/flask app that uses blueprints. I am currently getting the skeletal "hello world" app going, and when it works I will extend it. But I am stuck and getting an error "werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you mean 'main.index' instead?"

My app is based on Miguel Grinberg's "mega Tutorial" and I can't see any difference between my cut down code and his. I have read some documentation and searched for help but nothing quite fits. I think it is the type of error which will be obvious to an expert.

Below I list what I think is the relevant code.

The application structure is

```<code>\myapp
  myapp.py
  \app
    __init__.py
    \main
      __init__.py
      routes.py
      ...
    \...
      __init__.py
      routes.py
      ...
</code>```

where each subfolder of \app will be a blueprint.

```<code>myapp.py

from app import create_app
app = create_app()
</code>```

```<code>\app\__init__.py

from flask import Flask, request, current_app
from config import Config

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

#   Register blueprints
    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from app.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')

    from app.meta import bp as meta_bp
    app.register_blueprint(meta_bp)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    return app
</code>```

```<code>\app\main\__init__.py

from flask import Blueprint

bp = Blueprint('main', __name__)

from app.main import routes
</code>```

```<code>\app\main\routes.py

from app.main import bp
from flask import render_template

@bp.route('/')
@bp.route('/index')
def index():
    msg = "Hello World!"
    return render_template('index.html', title='Home', msg=msg)
</code>```

An the html template extends base.html and is trivial

```<code>\app\templates\index.html

{% extends "base.html" %}
{% block content %}
    <div><h1>{{ msg }}</h1></div>
{% endblock %}
</code>```

And here is base. html

```<code><html>
    <head>
        {% if title %}
            <title>{{ title }} - Metapplica</title>
        {% else %}
            <title>Welcome to Metapplica</title>
        {% endif %}
    </head>
    <body>
        <div>
            Meta:
            <a href="{{ url_for('index') }}">Home</a>
        </div>
        <hr>
        {% with messages = get_flashed_messages() %}
            {% if messages %}
                <ul>
                    {% for message in messages %}
                        <li>{{ message }}</li>
                    {% endfor %}
                </ul>
            {% endif %}
        {% endwith %}
        {% block content %}{% endblock %}
    </body>
</html>
</code>```

When I open this in a browser I get

"werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you mean 'main.index' instead?"

which implies somehow I am getting my name leveling wrong or?

The full error page is here (slightly different names because I simplified the code a tad).

Traceback (most recent call last)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 2328, in call
return self.wsgi_app(environ, start_response)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 2314, in wsgi_app
response = self.handle_exception(e)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1760, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask_compat.py", line 36, in reraise
raise value
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask_compat.py", line 36, in reraise
raise value
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1818, in dispatch_request
return self.view_functionsrule.endpoint
File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\main\routes.py", line 16, in index
return render_template('index.html', title='Home', msg=msg)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\templating.py", line 135, in render_template
context, ctx.app)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\templating.py", line 117, in _render
rv = template.render(context)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\jinja2\environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\jinja2_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\templates\index.html", line 1, in top-level template code
{% extends "base.html" %}
File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\templates\base.html", line 12, in top-level template code
Home
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\helpers.py", line 356, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 2080, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask_compat.py", line 36, in reraise
raise value
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\helpers.py", line 345, in url_for
force_external=external)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\werkzeug\routing.py", line 2007, in build
Open an interactive python shell in this frameraise BuildError(endpoint, values, method, self)

答: The blueprint you're using is scoped to main, so the url_for() in base.html needs to reference main.index.

Body:
I am setting up a python/flask app that uses blueprints. I am currently getting the skeletal "hello world" app going, and when it works I will extend it. But I am stuck and getting an error "werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you mean 'main.index' instead?"

My app is based on Miguel Grinberg's "mega Tutorial" and I can't see any difference between my cut down code and his. I have read some documentation and searched for help but nothing quite fits. I think it is the type of error which will be obvious to an expert.

Below I list what I think is the relevant code.

The application structure is

\myapp
  myapp.py
  \app
    __init__.py
    \main
      __init__.py
      routes.py
      ...
    \...
      __init__.py
      routes.py
      ...

where each subfolder of \app will be a blueprint.

myapp.py

from app import create_app
app = create_app()

\app\__init__.py

from flask import Flask, request, current_app
from config import Config

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

#   Register blueprints
    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from app.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')

    from app.meta import bp as meta_bp
    app.register_blueprint(meta_bp)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    return app

\app\main\__init__.py

from flask import Blueprint

bp = Blueprint('main', __name__)

from app.main import routes

\app\main\routes.py

from app.main import bp
from flask import render_template

@bp.route('/')
@bp.route('/index')
def index():
    msg = "Hello World!"
    return render_template('index.html', title='Home', msg=msg)

An the html template extends base.html and is trivial

\app\templates\index.html

{% extends "base.html" %}
{% block content %}

{{ msg }}

{% endblock %}

And here is base. html

        {% if title %}
            <title>{{ title }} - Metapplica</title>
        {% else %}
            <title>Welcome to Metapplica</title>
        {% endif %}

            Meta:
            Home

        {% with messages = get_flashed_messages() %}
            {% if messages %}

                    {% for message in messages %}

{{ message }}

                    {% endfor %}

            {% endif %}
        {% endwith %}
        {% block content %}{% endblock %}

When I open this in a browser I get

"werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you mean 'main.index' instead?"

which implies somehow I am getting my name leveling wrong or?

The full error page is here (slightly different names because I simplified the code a tad).

Traceback (most recent call last)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 2328, in call
return self.wsgi_app(environ, start_response)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 2314, in wsgi_app
response = self.handle_exception(e)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1760, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask_compat.py", line 36, in reraise
raise value
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask_compat.py", line 36, in reraise
raise value
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 1818, in dispatch_request
return self.view_functionsrule.endpoint
File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\main\routes.py", line 16, in index
return render_template('index.html', title='Home', msg=msg)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\templating.py", line 135, in render_template
context, ctx.app)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\templating.py", line 117, in _render
rv = template.render(context)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\jinja2\environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\jinja2_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\templates\index.html", line 1, in top-level template code
{% extends "base.html" %}
File "C:\Users\Mark Kortink\Dropbox\Python\projects\metapplica\app\templates\base.html", line 12, in top-level template code
Home
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\helpers.py", line 356, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\app.py", line 2080, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask_compat.py", line 36, in reraise
raise value
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\flask\helpers.py", line 345, in url_for
force_external=external)
File "c:\users\markko~1\dropbox\python\projects\metapp~1\venv\lib\site-packages\werkzeug\routing.py", line 2007, in build
Open an interactive python shell in this frameraise BuildError(endpoint, values, method, self)


问:
Categorical attribute splitting for Classification and Regression Tree (CART)
I know we can split numerical attributes multiple times in different levels for Classification and Regression Tree (CART) which is a binary tree. How about categorical attributes? Can we split multiple times or only one time? if not, what is the reason?</p>

答:
If the categorical predictors have more than 2 categories; you can split it again as you do in case of a numerical variable.

For Example;

If one of the predictors is 'Marital Status' with 3 categories: 'Married', 'Unmarried' and 'Divorced'.

You can have one binary split like 'Unmarried' Vs 'Others' where the latter group consists of the observations of both the groups 'Married' and 'Divorced'.

Further, if required at some stage, you can split 'Other' group into two categories 'Married' and 'Divorced'.

Based on some splitting rule, you can extend this idea for more than 3 categories too.


问:
Running a script that contain a image
I am creating a script for personal use and would like to insert an image in code, so when I run the program the script display the image on my end and my code below.

It is possible to insert and display the image inside the terminal with script?

My script(code) run in terminal, my OS is Linux(Ubuntu).

答:
w3mimgdisplay

The w3m web-browser provides a utility w3mimgdisplay that can be used to display images on some terminals. For example, you could run it as a bash coproc.

It's not very well documented but see information at:

https://blog.z3bra.org/2014/01/images-in-terminal.html

https://www.mail-archive.com/mutt-users@mutt.org/msg34447.html

Title: Running a script that contain a image


问:
Linking two or more assembly files
I am developing a simple and small 64bit OS. Until now I've used a single file and compile it with NASM:

```<code>nasm -f bin os.asm -o os.bin
</code>```

Then tested the .bin file with qemu.

Now I need to use multiple files so in my os.bin file. I've inserted this line:

```<code>extern helper_func
</code>```

Then called it in the code. In another .asm file i've created this function or procedure. The problem is that the bin format does not support extern, so I've tried to use the ELF format to create the .obj files and then link them with gcc:

```<code>gcc -m32 -nostdlib -nodefaultlibs -lgcc os.obj helper.obj -t linker.ld
</code>```

with this linker file:

```<code>ENTRY(_start)

SECTIONS
{
    . = 0x7C00;

    .text :
    {
        *(.text);
    }
}
</code>```

But when I try to run the .bin that has been created, qemu does not recognize the file. What have I done wrong?

(I've used gcc because I plan to use C code in the future)

Actually, I don't even know what all the flags do in gcc; I've copied them from the internet XD.

This is what i've done so far:

```<code>nasm -f elf os.asm -o os.obj
nasm -f elf helper.asm -o helper.obj
gcc -m32 -nostdlib -nodefaultlibs -lgcc os.obj helper.obj -t linker.ld -o myos.bin
objcopy --input-target=elf32-little --output-target=binary myos.bin myos.bin.new
qemu-system-x86_64 myos.bin.new
</code>```

No errors from any of those compilation. But when i run qemu i get this:

os.asm:

```<code>[bits 16]

section .text

    global _start

_start:

    ; Zero segment
    cli
    jmp 0x0000:.zero_seg
    .zero_seg:
    xor ax, ax
        mov ss, ax
        mov ds, ax
        mov es, ax
        mov fs, ax
        mov gs, ax
        mov sp, _start
        cld
    sti

    ; Reset disk
    call reset_disk

    ; Load disk sectors
    mov al, 2               ; sectors to read
    mov cl, 2               ; start sector
    mov bx, second_sector   ; offset to load
    call read_disk

    ; Enable A20 line
    call enable_a20

    jmp second_sector

_end1:
    jmp $

%include "liba/disk.asm"
%include "liba/a20.asm"

; padding and magic number
times 510-($-$$) db 0
dw 0xaa55

second_sector:

    call check_long
    call switch_long

_hang:
    jmp $

%include "liba/long.asm"
%include "liba/gdt.asm"

[bits 64]

extern helper_func

long_mode:

    jmp kernel_code

_end2:
    jmp $

times 512-($-$$-512) db 0

kernel_code:

    ; two byte
    call helper_func
</code>```

helper.asm:

```<code>[bits 64]

section .text

    global helper_func

helper_func:

    kernel_end:
    hlt
    jmp .kernel_end

ret
</code>```

Inside os.asm i've used this libs:

disk.asm:

```<code>read_disk:
    pusha

    mov ah, 0x02
    mov dl, 0x80    ; 0x00 Floppy/FlashDrive -- 0x80 HardDisk
    mov ch, 0       ; cylinder
    mov dh, 0       ; head

    int 0x13

    jc .disk_err
    popa
    ret

    .disk_err:
        jmp $

reset_disk:
    xor ax, ax
    mov bx, second_sector
    mov dl, 0x80
    int 0x13
    ret
</code>```

a20.asm:

```<code>test_a20:
    pusha

    mov ax, [0x7dfe]

    push bx
    mov bx, 0xffff
    mov es, bx
    pop bx

    mov bx, 0x7e0e

    mov dx, [es:bx]

    cmp ax, dx
    je .cont

    popa
    mov ax, 1
    ret

    .cont:
        mov ax, [0x7dff]

        push bx
        mov bx, 0xffff
        mov es, bx
        pop bx

        mov bx, 0x7e0f
        mov dx, [es:bx]

        cmp ax, dx
        je .exit

        popa
        mov ax, 1
        ret

    .exit:
        popa
        xor ax, ax
        ret

enable_a20:
    pusha

    ;BIOS
    mov ax, 0x2401
    int 0x15

    call test_a20
    cmp ax, 1
    je .done

    ;Keyboard
    sti

    call wait_c
    mov al, 0xad
    out 0x64, al

    call wait_c
    mov al, 0xd0
    out 0x64, al

    call wait_d
    in al, 0x60
    push ax

    call wait_d
    mov al, 0xd1
    out 0x64, al

    call wait_c
    pop ax
    or al, 2
    out 0x60, al

    call wait_c
    mov al, 0xae
    out 0x64, al

    call wait_c

    sti

    call test_a20
    cmp ax, 1
    je .done

    ;FastA20
    in al, 0x92
    or al, 2
    out 0x92, al

    call test_a20
    cmp al, 1
    je .done

    jmp $

    .done:
        popa
        ret

wait_c:
    in al, 0x64
    test al, 2

    jnz wait_c
    ret

wait_d:
    in al, 0x64
    test al, 1

    jz wait_d
    ret
</code>```

long.asm:

```<code>enable_long:
    cli

    call check_long

    mov edi, 0x1000
    mov cr3, edi
    xor eax, eax
    mov ecx, 4096
    rep stosd
    mov edi, 0x1000

    mov dword [edi], 0x2003
    add edi, 0x1000
    mov dword [edi], 0x3003
    add edi, 0x1000
    mov dword [edi], 0x4003
    add edi, 0x1000

    mov dword ebx, 3
    mov ecx, 512

    .setEntry:
        mov dword [edi], ebx
        add ebx, 0x1000
        add edi, 8
    loop .setEntry

    mov eax, cr4
    or eax, 1 << 5
    mov cr4, eax

    mov ecx, 0xc0000080
    rdmsr
    or eax, 1 << 8
    wrmsr

    mov eax, cr0
    or eax, 1 << 31
    or eax, 1 << 0
    mov cr0, eax

    ret

switch_long:

    call enable_long

    lgdt [GDT.Pointer]
    jmp GDT.Code:long_mode

    ret

check_long:
    pusha

    pushfd
    pop eax
    mov ecx, eax

    xor eax, 1 << 21

    push eax
    popfd

    pushfd
    pop eax

    xor eax, ecx
    jz .done

    mov eax, 0x80000000
    cpuid
    cmp eax, 0x80000001
    jb .done

    mov eax, 0x80000001
    cpuid
    test edx, 1 << 29
    jz .done

    popa
    ret

    .done:
        popa
        jmp $
</code>```

gdt.asm:

```<code>extern helper_func
</code>```0

答:
I don't know anything about the environment you are building with. I strongly recommend building an x86-64 cross compiler.

I can make a reasonable guess at some of the possible problems. Using GCC to link will generate a .note.gnu.build-id section and place it before all other sections in your binary. This will have the effect of moving your disk boot signature (0xaa55) to a location beyond the last 2 bytes in the first sector. It is the only reason I can think that your disk wouldn't be identified as bootable which appears to be the case in your screenshots. You need to add -Wl,build-id=none to your GCC link options to prevent this section from being generated.

To build a custom 64-bit bootloader in the fashion you are you should be generating everything as 64-bit objects and not 32-bit objects. Use -m64 when compiling/linking with GCC, and -felf64 when assembling with NASM (--64 if assembling with as GNU Assembler).

Ensure that you aren't generating relocatable code with -static and I recommend eliminating the .eh_frame sections with the option -fno-asynchronous-unwind-tables.

The linker script is passed using the -T option, not the -t option. In your linking options you have-t linker.ldand it should be -T linker.ld

You can simplify OBJCOPY arguments by letting it determine the source object/executable type. You can do objcopy -O binary myos.bin myos.bin.new instead.

The commands that I think you should use could look like:

```<code>nasm -f elf64 os.asm -o os.obj
nasm -f elf64 helper.asm -o helper.obj
gcc -m64 -wl,--build-id=none -static -fno-asynchronous-unwind-tables \
        -nostdlib -nodefaultlibs -lgcc os.obj helper.obj -T linker.ld -o myos.bin
objcopy -O binary myos.bin myos.bin.new
</code>```

Observations and Notes

In disk.asm you hard code the drive number. You can reuse/save the value of the DL register when your bootloader first starts. The BIOS passes the boot drive number in DL for you. If you reuse that value you don't need to change your code depending on the drive type you boot as (floppy, hard drive etc.)

I have some General Bootloader Tips that may be of value.

In the future when you start compiling C files I recommend these options:

```<code>gcc -m64 -ffreestanding -mcmodel=kernel -mno-red-zone \
    -mno-mmx -mno-sse -mno-sse2 -c filename.c -o filename.o
</code>```

Title: Linking two or more assembly files

Body:
I am developing a simple and small 64bit OS. Until now I've used a single file and compile it with NASM:

nasm -f bin os.asm -o os.bin

Then tested the .bin file with qemu.

Now I need to use multiple files so in my os.bin file. I've inserted this line:

extern helper_func

Then called it in the code. In another .asm file i've created this function or procedure. The problem is that the bin format does not support extern, so I've tried to use the ELF format to create the .obj files and then link them with gcc:

gcc -m32 -nostdlib -nodefaultlibs -lgcc os.obj helper.obj -t linker.ld

with this linker file:

ENTRY(_start)

SECTIONS
{
    . = 0x7C00;

    .text :
    {
        *(.text);
    }
}

But when I try to run the .bin that has been created, qemu does not recognize the file. What have I done wrong?

(I've used gcc because I plan to use C code in the future)

Actually, I don't even know what all the flags do in gcc; I've copied them from the internet XD.

This is what i've done so far:

nasm -f elf os.asm -o os.obj
nasm -f elf helper.asm -o helper.obj
gcc -m32 -nostdlib -nodefaultlibs -lgcc os.obj helper.obj -t linker.ld -o myos.bin
objcopy --input-target=elf32-little --output-target=binary myos.bin myos.bin.new
qemu-system-x86_64 myos.bin.new

No errors from any of those compilation. But when i run qemu i get this:

os.asm:

[bits 16]

section .text

    global _start

_start:

    ; Zero segment
    cli
    jmp 0x0000:.zero_seg
    .zero_seg:
    xor ax, ax
        mov ss, ax
        mov ds, ax
        mov es, ax
        mov fs, ax
        mov gs, ax
        mov sp, _start
        cld
    sti

    ; Reset disk
    call reset_disk

    ; Load disk sectors
    mov al, 2               ; sectors to read
    mov cl, 2               ; start sector
    mov bx, second_sector   ; offset to load
    call read_disk

    ; Enable A20 line
    call enable_a20

    jmp second_sector

_end1:
    jmp $

%include "liba/disk.asm"
%include "liba/a20.asm"

; padding and magic number
times 510-($-$$) db 0
dw 0xaa55

second_sector:

    call check_long
    call switch_long

_hang:
    jmp $

%include "liba/long.asm"
%include "liba/gdt.asm"

[bits 64]

extern helper_func

long_mode:

    jmp kernel_code

_end2:
    jmp $

times 512-($-$$-512) db 0

kernel_code:

    ; two byte
    call helper_func

helper.asm:

[bits 64]

section .text

    global helper_func

helper_func:

    kernel_end:
    hlt
    jmp .kernel_end

ret

Inside os.asm i've used this libs:

disk.asm:

read_disk:
    pusha

    mov ah, 0x02
    mov dl, 0x80    ; 0x00 Floppy/FlashDrive -- 0x80 HardDisk
    mov ch, 0       ; cylinder
    mov dh, 0       ; head

    int 0x13

    jc .disk_err
    popa
    ret

    .disk_err:
        jmp $

reset_disk:
    xor ax, ax
    mov bx, second_sector
    mov dl, 0x80
    int 0x13
    ret

a20.asm:

test_a20:
    pusha

    mov ax, [0x7dfe]

    push bx
    mov bx, 0xffff
    mov es, bx
    pop bx

    mov bx, 0x7e0e

    mov dx, [es:bx]

    cmp ax, dx
    je .cont

    popa
    mov ax, 1
    ret

    .cont:
        mov ax, [0x7dff]

        push bx
        mov bx, 0xffff
        mov es, bx
        pop bx

        mov bx, 0x7e0f
        mov dx, [es:bx]

        cmp ax, dx
        je .exit

        popa
        mov ax, 1
        ret

    .exit:
        popa
        xor ax, ax
        ret

enable_a20:
    pusha

    ;BIOS
    mov ax, 0x2401
    int 0x15

    call test_a20
    cmp ax, 1
    je .done

    ;Keyboard
    sti

    call wait_c
    mov al, 0xad
    out 0x64, al

    call wait_c
    mov al, 0xd0
    out 0x64, al

    call wait_d
    in al, 0x60
    push ax

    call wait_d
    mov al, 0xd1
    out 0x64, al

    call wait_c
    pop ax
    or al, 2
    out 0x60, al

    call wait_c
    mov al, 0xae
    out 0x64, al

    call wait_c

    sti

    call test_a20
    cmp ax, 1
    je .done

    ;FastA20
    in al, 0x92
    or al, 2
    out 0x92, al

    call test_a20
    cmp al, 1
    je .done

    jmp $

    .done:
        popa
        ret

wait_c:
    in al, 0x64
    test al, 2

    jnz wait_c
    ret

wait_d:
    in al, 0x64
    test al, 1

    jz wait_d
    ret

long.asm:

enable_long:
    cli

    call check_long

    mov edi, 0x1000
    mov cr3, edi
    xor eax, eax
    mov ecx, 4096
    rep stosd
    mov edi, 0x1000

    mov dword [edi], 0x2003
    add edi, 0x1000
    mov dword [edi], 0x3003
    add edi, 0x1000
    mov dword [edi], 0x4003
    add edi, 0x1000

    mov dword ebx, 3
    mov ecx, 512

    .setEntry:
        mov dword [edi], ebx
        add ebx, 0x1000
        add edi, 8
    loop .setEntry

    mov eax, cr4
    or eax, 1 << 5
    mov cr4, eax

    mov ecx, 0xc0000080
    rdmsr
    or eax, 1 << 8
    wrmsr

    mov eax, cr0
    or eax, 1 << 31
    or eax, 1 << 0
    mov cr0, eax

    ret

switch_long:

    call enable_long

    lgdt [GDT.Pointer]
    jmp GDT.Code:long_mode

    ret

check_long:
    pusha

    pushfd
    pop eax
    mov ecx, eax

    xor eax, 1 << 21

    push eax
    popfd

    pushfd
    pop eax

    xor eax, ecx
    jz .done

    mov eax, 0x80000000
    cpuid
    cmp eax, 0x80000001
    jb .done

    mov eax, 0x80000001
    cpuid
    test edx, 1 << 29
    jz .done

    popa
    ret

    .done:
        popa
        jmp $

gdt.asm:

GDT:
    .Null: equ $ - GDT
        dw 0
        dw 0
        db 0
        db 0
        db 0
        db 0

    .Code: equ $ - GDT
        dw 0
        dw 0
        db 0
        db 10011000b
        db 00100000b
        db 0

    .Data: equ $ -GDT
        dw 0
        dw 0
        db 0
        db 10000000b
        db 0
        db 0

    .Pointer:
        dw $ - GDT - 1
        dq GDT

Body:
I don't know anything about the environment you are building with. I strongly recommend building an x86-64 cross compiler.

I can make a reasonable guess at some of the possible problems. Using GCC to link will generate a .note.gnu.build-id section and place it before all other sections in your binary. This will have the effect of moving your disk boot signature (0xaa55) to a location beyond the last 2 bytes in the first sector. It is the only reason I can think that your disk wouldn't be identified as bootable which appears to be the case in your screenshots. You need to add -Wl,build-id=none to your GCC link options to prevent this section from being generated.

To build a custom 64-bit bootloader in the fashion you are you should be generating everything as 64-bit objects and not 32-bit objects. Use -m64 when compiling/linking with GCC, and -felf64 when assembling with NASM (--64 if assembling with as GNU Assembler).

Ensure that you aren't generating relocatable code with -static and I recommend eliminating the .eh_frame sections with the option -fno-asynchronous-unwind-tables.

The linker script is passed using the -T option, not the -t option. In your linking options you have-t linker.ldand it should be -T linker.ld

You can simplify OBJCOPY arguments by letting it determine the source object/executable type. You can do objcopy -O binary myos.bin myos.bin.new instead.

The commands that I think you should use could look like:

nasm -f elf64 os.asm -o os.obj
nasm -f elf64 helper.asm -o helper.obj
gcc -m64 -wl,--build-id=none -static -fno-asynchronous-unwind-tables \
        -nostdlib -nodefaultlibs -lgcc os.obj helper.obj -T linker.ld -o myos.bin
objcopy -O binary myos.bin myos.bin.new

Observations and Notes

In disk.asm you hard code the drive number. You can reuse/save the value of the DL register when your bootloader first starts. The BIOS passes the boot drive number in DL for you. If you reuse that value you don't need to change your code depending on the drive type you boot as (floppy, hard drive etc.)

I have some General Bootloader Tips that may be of value.

In the future when you start compiling C files I recommend these options:

gcc -m64 -ffreestanding -mcmodel=kernel -mno-red-zone \
    -mno-mmx -mno-sse -mno-sse2 -c filename.c -o filename.o


问:
R Loop To New Data Frame Summary Weighted
I have a tall data frame as such:

```<code>data = data.frame("id"=c(1,2,3,4,5,6,7,8,9,10),
                  "group"=c(1,1,2,1,2,2,2,2,1,2),
                  "type"=c(1,1,2,3,2,2,3,3,3,1),
                  "score1"=c(sample(1:4,10,r=T)),
                  "score2"=c(sample(1:4,10,r=T)),
                  "score3"=c(sample(1:4,10,r=T)),
                  "score4"=c(sample(1:4,10,r=T)),
                  "score5"=c(sample(1:4,10,r=T)),
                  "weight1"=c(173,109,136,189,186,146,173,102,178,174),
                  "weight2"=c(147,187,125,126,120,165,142,129,144,197),
                  "weight3"=c(103,192,102,159,128,179,195,193,135,145),
                  "weight4"=c(114,182,199,101,111,116,198,123,119,181),
                  "weight5"=c(159,125,104,171,166,154,197,124,180,154))

library(reshape2)
library(plyr)

data1 <- reshape(data, direction = "long",
                 varying = list(c(paste0("score",1:5)),c(paste0("weight",1:5))),
                 v.names = c("score","weight"),
                 idvar = "id", timevar = "count", times = c(1:5))
data1 <- data1[order(data1$id), ]
</code>```

And what I want to create is a new data frame like so:

```<code>want = data.frame("score"=rep(1:4,6),
                  "group"=rep(1:2,12),
                  "type"=rep(1:3,8),
                  "weightedCOUNT"=NA) # how to calculate this? count(data1, score, wt = weight)
</code>```

I am just not sure how to calculate weightedCOUNT which should apply the weights to the score variable so then it gives in column 'weightedCOUNT' a weighted count that is aggregated by score and group and type.

答:
An option would be to melt (from data.table - which can take multiple measure patterns, and then grouped by 'group', 'type' get the count

```<code>library(data.table)
library(dplyr)
melt(setDT(data), measure = patterns('^score', "^weight"),
   value.name = c("score", "weight")) %>%
   group_by(group, type) %>%
   count(score, wt = weight)
</code>```

If we need to have a complete set of combinations

```<code>library(tidyr)
melt(setDT(data), measure = patterns('^score', "^weight"),
       value.name = c("score", "weight")) %>%
   group_by(group, type) %>%
   ungroup %>%
   complete(group, type, score, fill = list(n = 0))
</code>```

Body:
I have a tall data frame as such:

data = data.frame("id"=c(1,2,3,4,5,6,7,8,9,10),
                  "group"=c(1,1,2,1,2,2,2,2,1,2),
                  "type"=c(1,1,2,3,2,2,3,3,3,1),
                  "score1"=c(sample(1:4,10,r=T)),
                  "score2"=c(sample(1:4,10,r=T)),
                  "score3"=c(sample(1:4,10,r=T)),
                  "score4"=c(sample(1:4,10,r=T)),
                  "score5"=c(sample(1:4,10,r=T)),
                  "weight1"=c(173,109,136,189,186,146,173,102,178,174),
                  "weight2"=c(147,187,125,126,120,165,142,129,144,197),
                  "weight3"=c(103,192,102,159,128,179,195,193,135,145),
                  "weight4"=c(114,182,199,101,111,116,198,123,119,181),
                  "weight5"=c(159,125,104,171,166,154,197,124,180,154))

library(reshape2)
library(plyr)

data1 <- reshape(data, direction = "long",
                 varying = list(c(paste0("score",1:5)),c(paste0("weight",1:5))),
                 v.names = c("score","weight"),
                 idvar = "id", timevar = "count", times = c(1:5))
data1 <- data1[order(data1$id), ]

And what I want to create is a new data frame like so:

want = data.frame("score"=rep(1:4,6),
                  "group"=rep(1:2,12),
                  "type"=rep(1:3,8),
                  "weightedCOUNT"=NA) # how to calculate this? count(data1, score, wt = weight)

I am just not sure how to calculate weightedCOUNT which should apply the weights to the score variable so then it gives in column 'weightedCOUNT' a weighted count that is aggregated by score and group and type.

Body:
An option would be to melt (from data.table - which can take multiple measure patterns, and then grouped by 'group', 'type' get the count

library(data.table)
library(dplyr)
melt(setDT(data), measure = patterns('^score', "^weight"),
   value.name = c("score", "weight")) %>%
   group_by(group, type) %>%
   count(score, wt = weight)

If we need to have a complete set of combinations

library(tidyr)
melt(setDT(data), measure = patterns('^score', "^weight"),
       value.name = c("score", "weight")) %>%
   group_by(group, type) %>%
   ungroup %>%
   complete(group, type, score, fill = list(n = 0))


问:
HTML that's both server-side and javascript generated - how to combine?
I'm usually a creative gal, but right now I just can't find any good solution. There's HTML (say form rows or table rows) that's both generated javascript-based and server-sided, it's exactly the same in both cases. It's generated server-sided when you open the page (and it has to stay server-sided for Google) and it's generated by AJAX, to show live updates or to extend the form by new, empty rows.

Problem is: The HTML generation routines are existing twice now, and you know DRY (don't repeat yourself), aye? Each time something's changed I have to edit 2 places and this just doesn't fit my idea of good software.

What's your best strategy to combine the javascript-based and server-sided HTML generation?

PS: Server-sided language is always different (PHP, RoR, C++).

PPS: Please don't give me an answer for Node.JS, I could figure that out on my own ;-)

答:
What's your best strategy to combine the javascript-based and server-sided HTML generation?

If you want to stay DRY, don't try to combine them. Stick with generating the HTML only on the server (clearly the preferable option for SEO), or only on the client.


问:
Can not find module “@angular-devkit/build-angular”
Using npm, I followed the getting started directions on the Angular CLI quick start page.

Angular CLI Quickstart

Running ng serve --open after creating and going into my new project "frontend" gave this error:

```<code>Could not find module "@angular-devkit/build-angular" from "C:\\Users\\Brandon\\project-name\\frontend".
Error: Could not find module "@angular-devkit/build-angular" from "C:\\Users\\Brandon\\project-name\\frontend".
 at Object.resolve (C:\Users\Brandon\project-name\node_modules\@angular-devkit\core\node\resolve.js:141:11)
 at Observable.rxjs_1.Observable [as _subscribe] (C:\Users\Brandon\project-name\node_modules\@angular-devkit\architect\src\architect.js:132:40)
</code>```

I have tried suggestions from the other question similar to mine but it did not work. Answer was to run npm install --save-dev @angular-devkit/build-angular.

Similar Question

I have also deleted modules, cleared cache, then did an install which also did not work.

package.json:

```<code>{
 "name": "frontend",
 "version": "0.0.0",
 "scripts": {
   "ng": "ng",
   "start": "ng serve",
   "build": "ng build",
   "test": "ng test",
   "lint": "ng lint",
   "e2e": "ng e2e"
 },
"private": true,
"dependencies": {
  "@angular/animations": "^6.0.2",
  "@angular/common": "^6.0.2",
  "@angular/compiler": "^6.0.2",
  "@angular/core": "^6.0.2",
  "@angular/forms": "^6.0.2",
  "@angular/http": "^6.0.2",
  "@angular/platform-browser": "^6.0.2",
  "@angular/platform-browser-dynamic": "^6.0.2",
  "@angular/router": "^6.0.2",
  "core-js": "^2.5.4",
  "rxjs": "^6.0.0",
  "zone.js": "^0.8.26"
 },
"devDependencies": {
  "@angular/compiler-cli": "^6.0.2",
  "@angular-devkit/build-angular": "~0.6.3",
  "typescript": "~2.7.2",
  "@angular/cli": "^6.0.3",
  "@angular/language-service": "^6.0.2",
  "@types/jasmine": "~2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/node": "~8.9.4",
  "codelyzer": "~4.2.1",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~1.7.1",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~1.4.2",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~5.3.0",
  "ts-node": "~5.0.1",
  "tslint": "~5.9.1"
 }
}
</code>```

angular.json:

```<code> {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "frontend": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/frontend",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "frontend:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "frontend:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "frontend:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "frontend-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "frontend:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "frontend"
}
</code>```

答: This worked for me: Type npm audit fix in the commandline. Afterwards I was able to use ng serve --open again.

Body:
Using npm, I followed the getting started directions on the Angular CLI quick start page.

Angular CLI Quickstart

Running ng serve --open after creating and going into my new project "frontend" gave this error:

Could not find module "@angular-devkit/build-angular" from "C:\\Users\\Brandon\\project-name\\frontend".
Error: Could not find module "@angular-devkit/build-angular" from "C:\\Users\\Brandon\\project-name\\frontend".
 at Object.resolve (C:\Users\Brandon\project-name\node_modules\@angular-devkit\core\node\resolve.js:141:11)
 at Observable.rxjs_1.Observable [as _subscribe] (C:\Users\Brandon\project-name\node_modules\@angular-devkit\architect\src\architect.js:132:40)

I have tried suggestions from the other question similar to mine but it did not work. Answer was to run npm install --save-dev @angular-devkit/build-angular.

Similar Question

I have also deleted modules, cleared cache, then did an install which also did not work.

package.json:

{
 "name": "frontend",
 "version": "0.0.0",
 "scripts": {
   "ng": "ng",
   "start": "ng serve",
   "build": "ng build",
   "test": "ng test",
   "lint": "ng lint",
   "e2e": "ng e2e"
 },
"private": true,
"dependencies": {
  "@angular/animations": "^6.0.2",
  "@angular/common": "^6.0.2",
  "@angular/compiler": "^6.0.2",
  "@angular/core": "^6.0.2",
  "@angular/forms": "^6.0.2",
  "@angular/http": "^6.0.2",
  "@angular/platform-browser": "^6.0.2",
  "@angular/platform-browser-dynamic": "^6.0.2",
  "@angular/router": "^6.0.2",
  "core-js": "^2.5.4",
  "rxjs": "^6.0.0",
  "zone.js": "^0.8.26"
 },
"devDependencies": {
  "@angular/compiler-cli": "^6.0.2",
  "@angular-devkit/build-angular": "~0.6.3",
  "typescript": "~2.7.2",
  "@angular/cli": "^6.0.3",
  "@angular/language-service": "^6.0.2",
  "@types/jasmine": "~2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/node": "~8.9.4",
  "codelyzer": "~4.2.1",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~1.7.1",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~1.4.2",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~5.3.0",
  "ts-node": "~5.0.1",
  "tslint": "~5.9.1"
 }
}

angular.json:

 {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "frontend": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/frontend",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "frontend:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "frontend:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "frontend:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "frontend-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "frontend:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "frontend"
}