问:
How to fix no variables echoed in PHP Post Request?
I am setting up a website and want to be able to obtain the customer number input for how many pizzas they want to order in Detailedsauceandquantitypage.html and post the number onto the ShoppingCartpage.php

I have already tried making my file a php file. I have already tried using POST.
The problem I am facing right now is not being able to output the number of pizzas ordered to the ShoppingCart.php page.

Detailedsauceandquantitypage.html

```<code><!DOCTYPE html>
    <html>
        <head>
            <script src="script.js"></script>
            <title>Detailed sauce and quantity page</title>
        </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">
                <input type="submit" value="Add this sauce to pizza">

                <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">
                <input type="submit" value="Add this sauce to pizza">

                <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">
                <input type="submit" value="Add this sauce to pizza">

                <br>
            </form>
        </body>
    </html>
</code>```

ShoppingCartpage.php

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Shopping Cart page</title>
    </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 . " " . $tomato . $salsa . "\n"; die("Please
        work!");
        }
        ?>
        <a href="OnlinePizzaOrderingPage.html">Add more pizzas to cart</a>
        <a href="Checkoutpage.html">Go to checkout</a>
    </body>
</html>
</code>```

答:
You should add name of your input button like this.

```<code><input type="submit" value="Add this sauce to pizza." name="submit">
</code>```

POST is read the name of the input not the type so you need to add name.

Body:
I am setting up a website and want to be able to obtain the customer number input for how many pizzas they want to order in Detailedsauceandquantitypage.html and post the number onto the ShoppingCartpage.php

I have already tried making my file a php file. I have already tried using POST.
The problem I am facing right now is not being able to output the number of pizzas ordered to the ShoppingCart.php page.

Detailedsauceandquantitypage.html

<!DOCTYPE html>

            <title>Detailed sauce and quantity page</title>

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">
                <input type="submit" value="Add this sauce to pizza">

                Number of Pizzas (0-100):
                <input type="number" name="tomatoPizza" min="0" max="100">
                <input type="submit" value="Add this sauce to pizza">

                Number of Pizzas (0-100):
                <input type="number" name="salsaPizza" min="0" max="100">
                <input type="submit" value="Add this sauce to pizza">

            </form>

ShoppingCartpage.php

<!DOCTYPE html>

        <title>Shopping Cart page</title>

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 . " " . $tomato . $salsa . "\n"; die("Please
        work!");
        }
        ?>
        Add more pizzas to cart
        Go to checkout

Body:
You should add name of your input button like this.

<input type="submit" value="Add this sauce to pizza." name="submit">

POST is read the name of the input not the type so you need to add name.


来源: stackexchange

问:
ASP.NET Core MVC Show hide partial views
I have a Contact/Index page split into two columns (for each column one PartialView). On the left I show the list of all my contacts and on the right the details of the selected/clicked contact from the said list.

...and the preview works great -> after a user clicks a record from the list I just call a '@Url.Action' for an action in my controller that returns a partial view with the details.

          @{await Html.RenderPartialAsync("_PartialList", Model.Contacts);}

          @{await Html.RenderPartialAsync("_PartialPreview", Model.Contact);}

          @{await Html.RenderPartialAsync("_PartialEdit", Model.Contact);}

```

But I'm having a problem with 'edit'. On the details form I have a button for EDIT and when a users clicks it I want to HIDE the PartialView for preview (id="sectionPreview") and SHOW the one for edit (id="sectionEdit").

I already tried playing around with saving different styles (disply: block or none) to ViewBag and applying that to each section, but it doesn't feel like the right approach, because all the PartialViews (even with display set to none) still get rendered.

What is the best way/practice to make this work?

答:
Another approach is to use ajax to load the partial view .On client side use ajax to call server side function and pass the filter parameter(id) . On server side , you can query the database with ID and return PartialView with models .

Then in success callback function of Ajax , you can load the html of partial view to related area in page using jQuery :

```<code>success: function (result) {
    $("#searchResultsGrid").html(result);
}
</code>```

And hide related div like :

```<code>$("#sectionPreview").hide();
</code>```

You can click here for code sample .

ContentLicense: CC BY-SA 4.0

Body:
I have a Contact/Index page split into two columns (for each column one PartialView). On the left I show the list of all my contacts and on the right the details of the selected/clicked contact from the said list.

...and the preview works great -> after a user clicks a record from the list I just call a '@Url.Action' for an action in my controller that returns a partial view with the details.

          @{await Html.RenderPartialAsync("_PartialList", Model.Contacts);}

          @{await Html.RenderPartialAsync("_PartialPreview", Model.Contact);}

          @{await Html.RenderPartialAsync("_PartialEdit", Model.Contact);}

But I'm having a problem with 'edit'. On the details form I have a button for EDIT and when a users clicks it I want to HIDE the PartialView for preview (id="sectionPreview") and SHOW the one for edit (id="sectionEdit").

I already tried playing around with saving different styles (disply: block or none) to ViewBag and applying that to each section, but it doesn't feel like the right approach, because all the PartialViews (even with display set to none) still get rendered.

What is the best way/practice to make this work?

Body:
Another approach is to use ajax to load the partial view .On client side use ajax to call server side function and pass the filter parameter(id) . On server side , you can query the database with ID and return PartialView with models .

Then in success callback function of Ajax , you can load the html of partial view to related area in page using jQuery :

success: function (result) {
    $("#searchResultsGrid").html(result);
}

And hide related div like :

$("#sectionPreview").hide();

You can click here for code sample .


问:
NSString stringWithContentsOfURL is deprecated. What should I do?
I've written some code that uses stringWithContentsOfURL, but it turns out that it is now deprecated. Can you help me replace it? Here's my code:

```<code>NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:@","];
</code>```

Additionally, can someone have some sample code to show how it works? What encoding was the original code done in (in my 2 lines above)?

I want to maintain compatibility so what should I choose for the encoding? What does error mean and what is it used for?

答:
Use stringWithContentsOfURL:encoding:error:

EDIT: Here's your code using the above method:

```<code>NSError *error = nil;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSUTF8StringEncoding error:&error];
NSArray *listItems = [locationString componentsSeparatedByString:@","];
</code>```

You can change NSUTF8StringEncoding accordingly for whatever data you're importing.

ContentLicense: CC BY-SA 3.0

Body:
I've written some code that uses stringWithContentsOfURL, but it turns out that it is now deprecated. Can you help me replace it? Here's my code:

NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:@","];

Additionally, can someone have some sample code to show how it works? What encoding was the original code done in (in my 2 lines above)?

I want to maintain compatibility so what should I choose for the encoding? What does error mean and what is it used for?

Body:
Use stringWithContentsOfURL:encoding:error:

EDIT: Here's your code using the above method:

NSError *error = nil;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSUTF8StringEncoding error:&error];
NSArray *listItems = [locationString componentsSeparatedByString:@","];

You can change NSUTF8StringEncoding accordingly for whatever data you're importing.


问:
Organize multiple projects (AWS)
In our team, we are using AWS as our main cloud provider and currently, we have 3 projects hosted on their platform.

We are about to have 2 more projects in the next weeks, but first, we want to organize our projects, because our current organization is a little bit disordered.

We want our projects to be organized following these rules:

Each project must have a staging and production environment.

Each project is independent of each other so that it is not possible to see the resources of a project from within another project, i.e., VPC and S3 Buckets.

The client is responsible for paying the bills of the project (staging and production environment).

Even though the client is responsible for paying the bills, we must have access to the environments to deploy our code and to do other tasks related to development, testing, and operations.

We can assign a team of developers to each project. It should be possible for a developer to be in one or more projects at the same time. Plus, it should be possible to move our developers between projects and to remove their access from a project.

So, is it possible to organize projects in AWS under the rules previously mentioned?
If so, what are good resources to learn how to do this?
If not, what cloud providers allow to organize projects the way we want?

Thanks for your attention and time. I'm looking forward to your replies.

答:
The fact that you want project-specific charges to go to customers and you want each project to be independent indicates that your best choice would be to use a separate AWS Account for each project (or each client).

By keeping projects in separate AWS accounts:

Each account will only have costs associated with a particular project

Resources in each account will be kept separate

User permissions in each account will be kept separate

You can create staging and production environments within the same account (see below)

You can have multiple accounts joined together by using AWS Organizations:

AWS Organizations is an account management service that enables you to consolidate multiple AWS accounts into an organization that you create and centrally manage. AWS Organizations includes account management and consolidated billing capabilities that enable you to better meet the budgetary, security, and compliance needs of your business. As an administrator of an organization, you can create accounts in your organization and invite existing accounts to join the organization.

Some companies go one step further and also keep staging and production in separate AWS accounts. They do this because they wish to keep production resources and users away from non-production resources and users. This reduces the chance of somebody accidentally changing Production when they meant to update Staging. While you can use IAM permissions to reduce such a thing from happening, keeping staging and production in separate accounts guarantees that people with only staging permissions will not be able to impact production.

Your company should maintain ownership of all of the accounts so that you can manage and control them. Each month, you will receive a consolidated bill, but it will show costs broken down by account. Thus, you will know how much to charge your clients.

The developers will need separate logins to each AWS account. So, if they wish to work on Project 1, they will need to login to the AWS account for Project 1. They then have access to the resources in Project 1, but not any of the other projects. When they wish to work on another project, they will need to re-login with credentials for the other project's AWS account. You might think that this adds extra work, but it also adds extra security and ensures that each client's resources are kept totally separate.

A final benefit of using separate accounts is that, in future, if a client wishes to take control of their systems, you can assign the AWS account to them without having to do any work to separate their resources from other clients. It is like handing over the keys of a house — they can move in without anyone having to move out.

Title: Organize multiple projects (AWS)


问:
Xamarin.Android DateTime related crashes on Samsung devices
We are experiencing DateTime parsing/instantiating related app crashes on Android in a Xamarin based cross platform app. The crashes only occur on Samung devices, mainly S8, S8+ and Note8 with Android 8 and 9. Unfortunately the stacktraces in the crash reports only consist of a couple of lines. Sadly it is not possible to contact the user to get more information because we do not have any information on who it is.

There are different manifestations of the issue, all somewhat connected:

The DateTime constructor is called with invalid parameters

```<code>System.ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime.
  Module "System.DateTime", line 0, in DateToTicks
    DateToTicks(System.Int32 year, System.Int32 month, System.Int32 day)
  Module "System.DateTime.", line 0, in ctor
    ctor(System.Int32 year, System.Int32 month, System.Int32 day, System.Int32 hour, System.Int32 minute, System.Int32 second)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()
</code>```

NullReferenceException in the DateTime constructor

```<code>System.NullReferenceException: Object reference not set to an instance of an object
  Module "System.DateTime.", line 0, in ctor
    ctor(System.Int32 year, System.Int32 month, System.Int32 day, System.Int32 hour, System.Int32 minute, System.Int32 second)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()
</code>```

However, there are also some related crashes that point towards the JSON library

NullReferenceException in Json DateTimeParser ParseZone

```<code>System.NullReferenceException: Object reference not set to an instance of an object
  Module "Newtonsoft.Json.Utilities.DateTimeParser", line 0, in ParseZone
    ParseZone(System.Int32 start)
  Module "Newtonsoft.Json.Utilities.DateTimeParser", line 0, in ParseTimeAndZoneAndWhitespace
    ParseTimeAndZoneAndWhitespace(System.Int32 start)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()
</code>```

IndexOutOfRangeException in Json DateTimeParser Parse2Digit

```<code>System.IndexOutOfRangeException: Index was outside the bounds of the array.
  Module "Newtonsoft.Json.Utilities.DateTimeParser", line 0, in Parse2Digit
    Parse2Digit(System.Int32 start, System.Int32& num)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()
</code>```

NullReferenceException in Json DateTimeParser ParseChar

```<code>System.NullReferenceException: Object reference not set to an instance of an object
  Module "Newtonsoft.Json.Utilities.DateTimeParser", line 0, in ParseChar
    ParseChar(System.Int32 start, System.Char ch)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()
</code>```

These are only some of the crash reports, there are a couple more but all of them go into the same direction.

what I have tried so far:

Investigated our code and open source library code that could be causing the issue

Faked server responses to return countless varieties of valid/invalid date values

Wrote a test App that parses countless varieties of valid/invalid date values

what I have found out so far:

I cannot reproduce the issue at all

As mentioned above it only appears on Samsung *8 devices

It does not occur on other Android devices

It also does not occur in the iOS or Windows app

It is unlikely to be an issue in our own code as we do not use these constructors (and seldomly handle datetime values manually alltogether)

Has anyone ran into any similar issue or have an idea into which direction I can keep looking? I am completely clueless and would appreciate any sort of hint.

答: After quite some investigation it turns out that the issue is related to the random NullReferenceExceptions accuring within Xamarin apps on Samsung devices when deploying a 32 bit apk to a 64 bit device. Due to another issue in the past we had to disable the 64 bit builds, after resolving that issue and deploying a 64 bit version again we have not received a similar crash report yet.</p>

Body:
We are experiencing DateTime parsing/instantiating related app crashes on Android in a Xamarin based cross platform app. The crashes only occur on Samung devices, mainly S8, S8+ and Note8 with Android 8 and 9. Unfortunately the stacktraces in the crash reports only consist of a couple of lines. Sadly it is not possible to contact the user to get more information because we do not have any information on who it is.

There are different manifestations of the issue, all somewhat connected:

The DateTime constructor is called with invalid parameters

System.ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime.
  Module "System.DateTime", line 0, in DateToTicks
    DateToTicks(System.Int32 year, System.Int32 month, System.Int32 day)
  Module "System.DateTime.", line 0, in ctor
    ctor(System.Int32 year, System.Int32 month, System.Int32 day, System.Int32 hour, System.Int32 minute, System.Int32 second)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()

NullReferenceException in the DateTime constructor

System.NullReferenceException: Object reference not set to an instance of an object
  Module "System.DateTime.", line 0, in ctor
    ctor(System.Int32 year, System.Int32 month, System.Int32 day, System.Int32 hour, System.Int32 minute, System.Int32 second)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()

However, there are also some related crashes that point towards the JSON library

NullReferenceException in Json DateTimeParser ParseZone

System.NullReferenceException: Object reference not set to an instance of an object
  Module "Newtonsoft.Json.Utilities.DateTimeParser", line 0, in ParseZone
    ParseZone(System.Int32 start)
  Module "Newtonsoft.Json.Utilities.DateTimeParser", line 0, in ParseTimeAndZoneAndWhitespace
    ParseTimeAndZoneAndWhitespace(System.Int32 start)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()

IndexOutOfRangeException in Json DateTimeParser Parse2Digit

System.IndexOutOfRangeException: Index was outside the bounds of the array.
  Module "Newtonsoft.Json.Utilities.DateTimeParser", line 0, in Parse2Digit
    Parse2Digit(System.Int32 start, System.Int32& num)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()

NullReferenceException in Json DateTimeParser ParseChar

System.NullReferenceException: Object reference not set to an instance of an object
  Module "Newtonsoft.Json.Utilities.DateTimeParser", line 0, in ParseChar
    ParseChar(System.Int32 start, System.Char ch)
  Module "System.Threading._ThreadPoolWaitCallback", line 0, in PerformWaitCallback
    PerformWaitCallback()

These are only some of the crash reports, there are a couple more but all of them go into the same direction.

what I have tried so far:

Investigated our code and open source library code that could be causing the issue

Faked server responses to return countless varieties of valid/invalid date values

Wrote a test App that parses countless varieties of valid/invalid date values

what I have found out so far:

I cannot reproduce the issue at all

As mentioned above it only appears on Samsung *8 devices

It does not occur on other Android devices

It also does not occur in the iOS or Windows app

It is unlikely to be an issue in our own code as we do not use these constructors (and seldomly handle datetime values manually alltogether)

Has anyone ran into any similar issue or have an idea into which direction I can keep looking? I am completely clueless and would appreciate any sort of hint.


问:
:hover works but rest of the link states don`t (:link & :visited for example)
For unknown to me reason, for a div with "TWO" inside:

:hover state works fine
:link, :visited don`t work

I can't find why?

.menu:link {
  color: teal;
}

.menu:visited {
  color: red;
}

.menu:hover {
  color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <a>
    <div class="menu">ONE</div>
  </a>

    <div class="menu">TWO</div>

</div></code>```

答:
:visited and :link selectors are used with  tag.

a:visited > .menu{
  color: red;
}
a:link > .menu {
  color: teal;
}
a:hover > .menu {
  color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <a>
    <span class="menu">ONE</span>
  </a>

    <span class="menu">TWO</span>

</div></code>```

by the way, I don't think it is a good idea, to use div inside a

Body:
For unknown to me reason, for a div with "TWO" inside:

:hover state works fine
:link, :visited don`t work

I can't find why?

.menu:link {
  color: teal;
}

.menu:visited {
  color: red;
}

.menu:hover {
  color: yellow;
}

ONE

TWO

Body:
:visited and :link selectors are used with <a> tag.

a:visited > .menu{
  color: red;
}
a:link > .menu {
  color: teal;
}
a:hover > .menu {
  color: yellow;
}

<div>
  <a>
    <span class="menu">ONE</span>
  </a>
  <a href="https://stackoverflow.com" target="_blank">
    <span class="menu">TWO</span>
  </a>
</div>

by the way, I don't think it is a good idea, to use div inside a


问:
C++ char* array
When I create something like

```<code>char* t = new char[44];
t = strcpy(s,t);
</code>```

then strlen(t); return some wrong results. how I can change this?

答:
The strcpy function is described thus:

```<code>#include <string.h>
char *strcpy(char *dest, const char *src);
</code>```

The strcpy() function copies the string pointed to by src (including the terminating '\0' character) to the array pointed to by dest.

So, if you are trying to fill in your newly allocated array, you should be doing:

```<code>strcpy(t, s);
</code>```

Not the other way around.

OwnerDisplayName: Александр Брус

Title: C++ char* array

Body:
When I create something like

char* t = new char[44];
t = strcpy(s,t);

then strlen(t); return some wrong results. how I can change this?

Body:
The strcpy function is described thus:

#include <string.h>
char *strcpy(char *dest, const char *src);

The strcpy() function copies the string pointed to by src (including the terminating '\0' character) to the array pointed to by dest.

So, if you are trying to fill in your newly allocated array, you should be doing:

strcpy(t, s);

Not the other way around.


答:
1.Only one submit button in the form needed(at the end of the form before </form>)

```<code><!DOCTYPE html>
    <html>
        <head>
            <script src="script.js"></script>
            <title>Detailed sauce and quantity page</title>
        </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">

                <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">

                <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">

                <br>
                <input type="submit" name="submit" value="Add this sauce to pizza">
            </form>
        </body>
    </html>
</code>```

2.Add name attribute to button.

3.You have to modify PHP code a bit

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Shopping Cart page</title>
    </head>
    <body>
        <h1>Shopping Cart page</h1>
        <?php
            $bbq    = ( !empty($_POST["bbqPizza"]) ) ? $_POST["bbqPizza"] : 0;
            $tomato = ( !empty($_POST["tomatoPizza"]) ) ? $_POST["tomatoPizza"] : 0;
            $salsa  = ( !empty($_POST["salsaPizza"]) ) ? $_POST["salsaPizza"] : 0;
            echo $bbq . " " . $tomato . $salsa . "\n"; die("Please work!");

        ?>
        <a href="OnlinePizzaOrderingPage.html">Add more pizzas to cart</a>
        <a href="Checkoutpage.html">Go to checkout</a>
    </body>
</html>
</code>```

Note:- Always try to check POST data instead of submit button

Title: How to fix no variables echoed in PHP Post Request?

Body:
1.Only one submit button in the form needed(at the end of the form before </form>)

<!DOCTYPE html>
    <html>
        <head>
            <script src="script.js"></script>
            <title>Detailed sauce and quantity page</title>
        </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">

                <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">

                <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">

                <br>
                <input type="submit" name="submit" value="Add this sauce to pizza">
            </form>
        </body>
    </html>

2.Add name attribute to button.

3.You have to modify PHP code a bit

<!DOCTYPE html>
<html>
    <head>
        <title>Shopping Cart page</title>
    </head>
    <body>
        <h1>Shopping Cart page</h1>
        <?php
            $bbq    = ( !empty($_POST["bbqPizza"]) ) ? $_POST["bbqPizza"] : 0;
            $tomato = ( !empty($_POST["tomatoPizza"]) ) ? $_POST["tomatoPizza"] : 0;
            $salsa  = ( !empty($_POST["salsaPizza"]) ) ? $_POST["salsaPizza"] : 0;
            echo $bbq . " " . $tomato . $salsa . "\n"; die("Please work!");

        ?>
        <a href="OnlinePizzaOrderingPage.html">Add more pizzas to cart</a>
        <a href="Checkoutpage.html">Go to checkout</a>
    </body>
</html>

Note:- Always try to check POST data instead of submit button


问:
I can await fs.readdir but I don't know why
https://github.com/SimulatedGREG/electron-vue

I used this template to make electron.

And I am using this library.

https://www.npmjs.com/package/fs-extra

https://nodejs.org/docs/latest-v11.x/api/fs.html

By this document, I can write like this.

```<code>await fs.readdir
</code>```

But the electron template, it is using electron@2.0.4 and which is using node@8.9.3.

So I checked here.

https://nodejs.org/docs/latest-v8.x/api/fs.html

It looks like the function doesn't return promise.

But I actually can await fs functions using fs-extra in electron@2.0.4.

Both develop and build.

Why is this?

result of

```<code>console.log(fs.readdir())
</code>```

Is like below.

It's Promise.

But I don't know why I can do this in electron@2.0.4.

答:
You can use fs module in node v8. the return value will be passed to callback function</p>

```<code>const fs = require('fs');
fs.readdir(dir, function(err, list) {

// do your logic with list array

})
</code>```

Body:
https://github.com/SimulatedGREG/electron-vue

I used this template to make electron.

And I am using this library.

https://www.npmjs.com/package/fs-extra

https://nodejs.org/docs/latest-v11.x/api/fs.html

By this document, I can write like this.

await fs.readdir

But the electron template, it is using electron@2.0.4 and which is using node@8.9.3.

So I checked here.

https://nodejs.org/docs/latest-v8.x/api/fs.html

It looks like the function doesn't return promise.

But I actually can await fs functions using fs-extra in electron@2.0.4.

Both develop and build.

Why is this?

result of

console.log(fs.readdir())

Is like below.

It's Promise.

But I don't know why I can do this in electron@2.0.4.

Body:
You can use fs module in node v8. the return value will be passed to callback function

const fs = require('fs');
fs.readdir(dir, function(err, list) {

// do your logic with list array

})


问:
How to delete from multiple tables in one DELETE statement in a .cfc file?
I have two tables. A device table and a location table. There can only be one device in the device table but there can be multiple devices with multiple locations in the location table.

If a user deletes a device, I need to also delete the locations with the same id from the location table.

Is there a way to delete from multiple tables in a Delete statement (using sql server) from within a cfc page?

I have tried to write a <cfif> when I do my initial delete, to check if there were records deleted and if so, run the next delete statement that deletes the devices from the table.

I have also tried to use this format.

```<code>delete T1, T2
from T1
inner join T2 on T1.device_id = T2.device_id
where T2.device_id = '111';
</code>```

T1 = device table, T2 = Location table

```<code><cfif ARGUMENTS.submitButton eq 'btn_Delete'>
   <cfquery name="DeleteDevice" datasource="#session.dsn#" maxRows=1 >
        DELETE from #session.tq#device
        WHERE device_id = <cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">
    </cfquery>
 </cfif>

<cfif DeleteDevice.RecordCount eq 1>
<cfquery name="DeleteLocation" datasource="#session.dsn#" maxRows=1 >
        DELETE from #session.tq#device_location_xref
        WHERE device_location_xref_recno=<cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">
</cfquery>
</code>```

答:
Can you do something like this</p>

```<code><cfquery>
DECLARE @device_id varchar(20) = <cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">

DELETE
FROM T1
WHERE device_id = @device_id

DELETE
FROM T2
WHERE device_id = @device_id
</cfquery>
</code>```

Body:
I have two tables. A device table and a location table. There can only be one device in the device table but there can be multiple devices with multiple locations in the location table.

If a user deletes a device, I need to also delete the locations with the same id from the location table.

Is there a way to delete from multiple tables in a Delete statement (using sql server) from within a cfc page?

I have tried to write a <cfif> when I do my initial delete, to check if there were records deleted and if so, run the next delete statement that deletes the devices from the table.

I have also tried to use this format.

delete T1, T2
from T1
inner join T2 on T1.device_id = T2.device_id
where T2.device_id = '111';

T1 = device table, T2 = Location table

<cfif ARGUMENTS.submitButton eq 'btn_Delete'>
   <cfquery name="DeleteDevice" datasource="#session.dsn#" maxRows=1 >
        DELETE from #session.tq#device
        WHERE device_id = <cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">
    </cfquery>
 </cfif>

<cfif DeleteDevice.RecordCount eq 1>
<cfquery name="DeleteLocation" datasource="#session.dsn#" maxRows=1 >
        DELETE from #session.tq#device_location_xref
        WHERE device_location_xref_recno=<cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">
</cfquery>

Body:
Can you do something like this

<cfquery>
DECLARE @device_id varchar(20) = <cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">

DELETE
FROM T1
WHERE device_id = @device_id

DELETE
FROM T2
WHERE device_id = @device_id
</cfquery>


问:
How to compute the distance matrix in spark?
I have tried pairing the samples but it costs huge amount of memory as 100 samples leads to 9900 samples which is more costly. What could be the more effective way of computing distance matrix in distributed environment in spark

Here is a snippet of pseudo code what i'm trying

```<code>val input = (sc.textFile("AirPassengers.csv",(numPartitions/2)))
val i = input.map(s => (Vectors.dense(s.split(',').map(_.toDouble))))
val indexed = i.zipWithIndex()                                                                       //Including the index of each sample
val indexedData = indexed.map{case (k,v) => (v,k)}

val pairedSamples = indexedData.cartesian(indexedData)

val filteredSamples = pairedSamples.filter{ case (x,y) =>
(x._1.toInt > y._1.toInt)  //to consider only the upper or lower trainagle
 }
filteredSamples.cache
filteredSamples.count
</code>```

Above code creates the pairs but even if my dataset contains 100 samples, by pairing filteredSamples (above) results in 4950 sample which could be very costly for big data

答:
This can serve as the java version of jtitusj's answer..</p>

```<code>public JavaPairRDD<Tuple2<Long, Long>, Double> getDistanceMatrix(Dataset<Row> ds, String vectorCol) {

    JavaRDD<Vector> rdd = ds.toJavaRDD().map(new Function<Row, Vector>() {

        private static final long serialVersionUID = 1L;

        public Vector call(Row row) throws Exception {
            return row.getAs(vectorCol);
        }

    });

    List<Vector> vectors = rdd.collect();

    long count = ds.count();

    List<Tuple2<Tuple2<Long, Long>, Double>> distanceList = new ArrayList<Tuple2<Tuple2<Long, Long>, Double>>();

    for(long i=0; i < count; i++) {
        for(long j=0; j < count && i > j; j++) {
            Tuple2<Long, Long> indexPair = new Tuple2<Long, Long>(i, j);
            double d = DistanceMeasure.getDistance(vectors.get((int)i), vectors.get((int)j));
            distanceList.add(new Tuple2<Tuple2<Long, Long>, Double>(indexPair, d));
        }
    }

    return distanceList;
}
</code>```

Body:
I have tried pairing the samples but it costs huge amount of memory as 100 samples leads to 9900 samples which is more costly. What could be the more effective way of computing distance matrix in distributed environment in spark

Here is a snippet of pseudo code what i'm trying

val input = (sc.textFile("AirPassengers.csv",(numPartitions/2)))
val i = input.map(s => (Vectors.dense(s.split(',').map(_.toDouble))))
val indexed = i.zipWithIndex()                                                                       //Including the index of each sample
val indexedData = indexed.map{case (k,v) => (v,k)}

val pairedSamples = indexedData.cartesian(indexedData)

val filteredSamples = pairedSamples.filter{ case (x,y) =>
(x._1.toInt > y._1.toInt)  //to consider only the upper or lower trainagle
 }
filteredSamples.cache
filteredSamples.count

Above code creates the pairs but even if my dataset contains 100 samples, by pairing filteredSamples (above) results in 4950 sample which could be very costly for big data

Body:
This can serve as the java version of jtitusj's answer..

public JavaPairRDD<Tuple2<Long, Long>, Double> getDistanceMatrix(Dataset<Row> ds, String vectorCol) {

    JavaRDD<Vector> rdd = ds.toJavaRDD().map(new Function<Row, Vector>() {

        private static final long serialVersionUID = 1L;

        public Vector call(Row row) throws Exception {
            return row.getAs(vectorCol);
        }

    });

    List<Vector> vectors = rdd.collect();

    long count = ds.count();

    List<Tuple2<Tuple2<Long, Long>, Double>> distanceList = new ArrayList<Tuple2<Tuple2<Long, Long>, Double>>();

    for(long i=0; i < count; i++) {
        for(long j=0; j < count && i > j; j++) {
            Tuple2<Long, Long> indexPair = new Tuple2<Long, Long>(i, j);
            double d = DistanceMeasure.getDistance(vectors.get((int)i), vectors.get((int)j));
            distanceList.add(new Tuple2<Tuple2<Long, Long>, Double>(indexPair, d));
        }
    }

    return distanceList;
}


问:
Embed two structs with the same name in a struct
How do you embed two types of the same name in a struct? For instance:

```<code>type datastore {
    *sql.Store
    *file.Store
}
</code>```

Results in duplicate field Store. I know this makes sense, since you wouldn't be able to refer to the embedded field ds.Store but how do you accomplish this anyway?

To clarify, I want to implement an interface with datastore. For that both structs are needed as their methods complement each other to create the interface. What alterantives do I have?

答:
Use a type alias, example:

```<code>type SqlStore = sql.Store // this is a type alias

type datastore struct {
    *SqlStore
    *file.Store
}
</code>```

A type alias doesn’t create a new distinct type different from the type it’s created from. It just introduces an alias name sqlStore, an alternate spelling, for the type denoted by sql.Store.

Body:
How do you embed two types of the same name in a struct? For instance:

type datastore {
    *sql.Store
    *file.Store
}

Results in duplicate field Store. I know this makes sense, since you wouldn't be able to refer to the embedded field ds.Store but how do you accomplish this anyway?

To clarify, I want to implement an interface with datastore. For that both structs are needed as their methods complement each other to create the interface. What alterantives do I have?

Body:
Use a type alias, example:

type SqlStore = sql.Store // this is a type alias

type datastore struct {
    *SqlStore
    *file.Store
}

A type alias doesn’t create a new distinct type different from the type it’s created from. It just introduces an alias name sqlStore, an alternate spelling, for the type denoted by sql.Store.


问:
laravel request not redirect right page
I want to make a filter based on request kelas on database table. It gives me no error just when I click one of the filter, it don't show jadwal page with my filter. It show the main page but the url is right like lps.com/?jadwal-2

I have done make a middleware called SanitizeMiddleware from stackoverflow but still not worked.

This is my route web.php

```<code>Route::get('/', 'HomepageController@index');

Route::resource('pengumuman', 'PengumumanController');
Route::resource('jadwal', 'JadwalController');
Route::resource('rapot', 'RapotController');
</code>```

This is my index() from my JadwalController

```<code>public function index()
{
    if (request()->has('kelas')) {
        $jadwal = jadwal::where('kelas', request('kelas'));
    } else {
        $jadwal = jadwal::all();
    }

    return view('jadwal.index')->with('jadwal',$jadwal);

    //$jadwal = jadwal::all();
    //return view('jadwal.index')->with('jadwal',$jadwal);
}
</code>```

This is my index.blade.php

```<code><div class="container">
    <br>
    <h1>
        <strong>Jadwal Pelajaran</strong>
    </h1>
    <a href="/?kelas=1">jadwwal kelas 1</a>
    <a href="/?kelas-2">jadwal kelas 2</a>
    <a href="/?kelas-3">jadwal kelas 3</a>
    </form>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th scope="col"></th>
                <th scope="col">07.00-08.00</th>
                <th scope="col">08.00-09.00</th>
                <th scope="col">09.00-10.00</th>
                <th scope="col">10.00-11.00</th>
                <th scope="col">10.00-12.00</th>
                <th scope="col">action</th>
            </tr>
        </thead>
        <tbody>
            @if(count($jadwal)>0)
                @foreach($jadwal as $jadwals)
                    <tr>
                        <th scope="row">{{$jadwals->hari}}</th>
                        <td>{{$jadwals->jamke1}}</td>
                        <td>{{$jadwals->jamke2}}</td>
                        <td>{{$jadwals->jamke3}}</td>
                        <td>{{$jadwals->jamke4}}</td>
                        <td>{{$jadwals->jamke4}}</td>
                        <td>
                            <a href="/jadwal/{{$jadwals->id}}/edit" class="btn btn-info">Edit</a>
                        </td>
                    </tr>
                @endforeach
            @else
                <p>tidak ada jadwal</p>
            @endif
        </tbody>
    </table>
</div>
</code>```

And this is the picture of problem:-

this is my jadwal page before filter

this my page after i click the filter using request()

答:
HTML URL talking, lps.com/?jadwal-2 is just calling the home page with a GET parameter called jadwal-2 with no value at all. lps.com/jadwal is good, lps.com/jadwal?kelas=2 is good. forget the dash

Using / in href attribute tell the system to start from the the top level path. Change to relative like :

```<code><a href="?kelas=1">jadwwal kelas 1</a>
<a href="?kelas-2">jadwal kelas 2</a>
<a href="?kelas-3">jadwal kelas 3</a>
</code>```

So being on page lps.com/jadwal will result in url lps.com/jadwal?kelas=1 which is the correct syntax and pattern.

Title: laravel request not redirect right page

Body:
I want to make a filter based on request kelas on database table. It gives me no error just when I click one of the filter, it don't show jadwal page with my filter. It show the main page but the url is right like lps.com/?jadwal-2

I have done make a middleware called SanitizeMiddleware from stackoverflow but still not worked.

This is my route web.php

Route::get('/', 'HomepageController@index');

Route::resource('pengumuman', 'PengumumanController');
Route::resource('jadwal', 'JadwalController');
Route::resource('rapot', 'RapotController');

This is my index() from my JadwalController

public function index()
{
    if (request()->has('kelas')) {
        $jadwal = jadwal::where('kelas', request('kelas'));
    } else {
        $jadwal = jadwal::all();
    }

    return view('jadwal.index')->with('jadwal',$jadwal);

    //$jadwal = jadwal::all();
    //return view('jadwal.index')->with('jadwal',$jadwal);
}

This is my index.blade.php

        Jadwal Pelajaran

    jadwwal kelas 1
    jadwal kelas 2
    jadwal kelas 3
    </form>

                07.00-08.00
                08.00-09.00
                09.00-10.00
                10.00-11.00
                10.00-12.00
                action

            @if(count($jadwal)>0)
                @foreach($jadwal as $jadwals)

                        {{$jadwals->hari}}
                        {{$jadwals->jamke1}}
                        {{$jadwals->jamke2}}
                        {{$jadwals->jamke3}}
                        {{$jadwals->jamke4}}
                        {{$jadwals->jamke4}}

                            id}}/edit" class="btn btn-info">Edit

                @endforeach
            @else

tidak ada jadwal

            @endif

And this is the picture of problem:-

this is my jadwal page before filter

this my page after i click the filter using request()

Body:
HTML URL talking, lps.com/?jadwal-2 is just calling the home page with a GET parameter called jadwal-2 with no value at all. lps.com/jadwal is good, lps.com/jadwal?kelas=2 is good. forget the dash

Using / in href attribute tell the system to start from the the top level path. Change to relative like :

<a href="?kelas=1">jadwwal kelas 1</a>
<a href="?kelas-2">jadwal kelas 2</a>
<a href="?kelas-3">jadwal kelas 3</a>

So being on page lps.com/jadwal will result in url lps.com/jadwal?kelas=1 which is the correct syntax and pattern.


问:
Spread Operator not available in Azure Node Function
I'm writing my first Azure Function in Node. This is in VS Code on my local machine. I'm requiring some js code I'd written for a Chrome extension but it's not compiling. For instance, this spread operator

```<code>if (otherProps) this.props[indx] = {
    ...this.props[indx],
    ...otherProps
};
</code>```

Generates the following error:

```<code>...this.props[indx], ^^^ SyntaxError: Unexpected token ... at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10)
</code>```

node.green shows full compatability for spread at node 8.6, Azure v1 is 8.11, so I don't think it's that.

Have I missed something simple here? Of note, I'm getting all sorts of errors with most of the node packages I tried to require. Spread operators, replace, nodeType all failed.

答: Azure v1 targets node v6, v2 targets 8 & 10, spread operator is not available in v6.</p>

Body:
I'm writing my first Azure Function in Node. This is in VS Code on my local machine. I'm requiring some js code I'd written for a Chrome extension but it's not compiling. For instance, this spread operator

if (otherProps) this.props[indx] = {
    ...this.props[indx],
    ...otherProps
};

Generates the following error:

...this.props[indx], ^^^ SyntaxError: Unexpected token ... at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10)

node.green shows full compatability for spread at node 8.6, Azure v1 is 8.11, so I don't think it's that.

Have I missed something simple here? Of note, I'm getting all sorts of errors with most of the node packages I tried to require. Spread operators, replace, nodeType all failed.


问:
botframeworkv4 - List of available Channel IDs
While exploring the new preview of the botframeworkv4 in C#, I came across a case where I need to do a specific action for a certain channel. In botframeworkv3, I used to access all the channels string names using ChannelIds but I can't find it here.

I know that I can directly write "facebook" for example, but using the provided list prevents any typos and improves readability.

Therefore, what is the equivalent of ChannelIds in botframeworkv4?

答:
ChannelIds has been replaced with Channels in the C# V4 SDK and is available under Microsoft.Bot.Connector.

Checking for a specific channel can be done easily, for example:

```<code>var isEmail = turnContext.Activity.ChannelId == Channels.Email;
</code>```

Use Nicholas R's answer if you need to add custom channels (or example Android, iOS) to the list.

Body:
ChannelIds has been replaced with Channels in the C# V4 SDK and is available under Microsoft.Bot.Connector.

Checking for a specific channel can be done easily, for example:

var isEmail = turnContext.Activity.ChannelId == Channels.Email;

Use Nicholas R's answer if you need to add custom channels (or example Android, iOS) to the list.


问:
Front-end/Back-end design: how to absolutely dissociate the back-end from the front-end?
My question is: (is the above|what is) the right way to create a non intrusive front-end?

I am explaining my problem with a simplified example.

I have a back-end implementing a binary tree:

```<code>// Back-end
struct Node
{
  Label label;
  Node* r, l;
};
</code>```

I would like now to implement the front-end to print the tree graphically. So my idea is to extend the back-end with graphical properties by wrapping it :

```<code>// Front-end
struct Drawable
{
  uint x, y;
};

class Visitor;
template <class T> struct GNode : public Drawable
{
  T* wrapped;
  template <class V> void accept(V& v); // v.visit(*this);
}
</code>```

There is a problem now to create a visitor printing the binary tree:

```<code>struct Visitor
{
    void visit(GNode<Node>& n)
    {
      // print the label and a circle around it: ok.

      if (n.wrapped.l) // l is a Node, not a GNode, I can't use the visitor on it
        // Problem: how to call this visitor on the node's left child?

      // the same with n.wrapped.r
    };
};
</code>```

As explained in comments, the back-end does not use my extended class.

Writing GNode "is-a" Node is not a solution neither since I would have to put the accept() method in the Node class as virtual and override it in GNode but I can't modify the back-end. Then, someone could say too that there is no need to declare accept() in the back-end, downcasting Node* to GNode* would work. Yes it works, but it downcasts...

In my case, I have ~10 kinds of nodes (it is a graph), so I am looking for something elegant, flexible, with as few lines of code as possible (hence the wrapper template idea) :)

Thank you very much.

答:
If your wrapper class (GNode) didn't have to maintain any state across visits (i.e., it only had one field - the wrapped Node object), you could use a pointer or a reference to the wrapped object instead of a copy, and then you would be able to wrap any node at runtime.

But even if you do maintain state (the x,y coordinates), don't you really just infer it from the wrapped object? In that case, wouldn't it be better to separate your visited class from the inferred data? For instance, consider this implementation:

```<code>// This is an adapter pattern, so you might want to call it VisitorAdapter if you
// like naming classes after patterns.
template typename<T>
class VisitorAcceptor
{
private:
    T& wrapped;
public:
    VisitorAcceptor(T& obj)
    {
        wrapped = obj;
    }

    template <typename VisitorT>
    void accept(VisitorT& v)
    {
        v.visit(wrapped);
    }
};

struct GNode
{
    uint x, y;
    shared_ptr<GNode> l,r; // use your favourite smart pointer here

    template <typename VisitorT>
    void accept(VisitorT& v)
}

// You don't have to call a visitor implementation 'Visitor'. It's better to name
// it according to its function, which is, I guess, calculating X,Y coordinates.
{
    shared_ptr<GNode> visit(Node& n)
    {
        shared_ptr<GNode> gnode = new GNode;
        // calculate x,y
        gnode->x = ...
        gnode->y = ...

        if (n.l)
            gnode->l = VisitorAdapter(n.r).accept(*this);
        if (n.r)
            gnode->r = VisitorAdapter(n.l).accept(*this);
    };
};

Now you can have a different visitor for drawing:

struct GNodeDrawer
{
    void visit(GNode& gnode)
    {
        // print the label and a circle around it: ok.

        if (n.r)
            visit(n.l);
        if (n.r)
            visit(n.r);
    };
};
</code>```

Of course, if you don't need all the extensibility the visitor pattern offers, you can throw it away altogether and just walk the the tree recursively with XYCalculator.visit calling itself.

Body:
My question is: (is the above|what is) the right way to create a non intrusive front-end?

I am explaining my problem with a simplified example.

I have a back-end implementing a binary tree:

// Back-end
struct Node
{
  Label label;
  Node* r, l;
};

I would like now to implement the front-end to print the tree graphically. So my idea is to extend the back-end with graphical properties by wrapping it :

// Front-end
struct Drawable
{
  uint x, y;
};

class Visitor;
template <class T> struct GNode : public Drawable
{
  T* wrapped;
  template <class V> void accept(V& v); // v.visit(*this);
}

There is a problem now to create a visitor printing the binary tree:

struct Visitor
{
    void visit(GNode<Node>& n)
    {
      // print the label and a circle around it: ok.

      if (n.wrapped.l) // l is a Node, not a GNode, I can't use the visitor on it
        // Problem: how to call this visitor on the node's left child?

      // the same with n.wrapped.r
    };
};

As explained in comments, the back-end does not use my extended class.

Writing GNode "is-a" Node is not a solution neither since I would have to put the accept() method in the Node class as virtual and override it in GNode but I can't modify the back-end. Then, someone could say too that there is no need to declare accept() in the back-end, downcasting Node* to GNode* would work. Yes it works, but it downcasts...

In my case, I have ~10 kinds of nodes (it is a graph), so I am looking for something elegant, flexible, with as few lines of code as possible (hence the wrapper template idea) :)

Thank you very much.

Body:
If your wrapper class (GNode) didn't have to maintain any state across visits (i.e., it only had one field - the wrapped Node object), you could use a pointer or a reference to the wrapped object instead of a copy, and then you would be able to wrap any node at runtime.

But even if you do maintain state (the x,y coordinates), don't you really just infer it from the wrapped object? In that case, wouldn't it be better to separate your visited class from the inferred data? For instance, consider this implementation:

// This is an adapter pattern, so you might want to call it VisitorAdapter if you
// like naming classes after patterns.
template typename<T>
class VisitorAcceptor
{
private:
    T& wrapped;
public:
    VisitorAcceptor(T& obj)
    {
        wrapped = obj;
    }

    template <typename VisitorT>
    void accept(VisitorT& v)
    {
        v.visit(wrapped);
    }
};

struct GNode
{
    uint x, y;
    shared_ptr<GNode> l,r; // use your favourite smart pointer here

    template <typename VisitorT>
    void accept(VisitorT& v)
}

// You don't have to call a visitor implementation 'Visitor'. It's better to name
// it according to its function, which is, I guess, calculating X,Y coordinates.
{
    shared_ptr<GNode> visit(Node& n)
    {
        shared_ptr<GNode> gnode = new GNode;
        // calculate x,y
        gnode->x = ...
        gnode->y = ...

        if (n.l)
            gnode->l = VisitorAdapter(n.r).accept(*this);
        if (n.r)
            gnode->r = VisitorAdapter(n.l).accept(*this);
    };
};

Now you can have a different visitor for drawing:

struct GNodeDrawer
{
    void visit(GNode& gnode)
    {
        // print the label and a circle around it: ok.

        if (n.r)
            visit(n.l);
        if (n.r)
            visit(n.r);
    };
};

Of course, if you don't need all the extensibility the visitor pattern offers, you can throw it away altogether and just walk the the tree recursively with XYCalculator.visit calling itself.


问:
Does logging a string information fall under magic strings?
I would like to know a base thing.

```<code>_logger.LogInformation("Hi, Am I magic string?");
</code>```

In the above line, does the string fall under magic string?

Any hardcoded validation/action against a response/return is considered a "magic string" to me. (Eg: _config["EmailTo"] should be _config.EmailTo, if(list.contains("error")) should be if(list.contains(errorValue))

Appreciate your thoughts!

答:
Magic exists when the audience expects one thing but sees another.

If there is any system that reads the log file and tries to interpret it and then take some action this string has become a contract/magic because changing it will confuse that system.

A good rule of thumb is to never parse logs unless there are well defined and guarded standards for the log. Parsing strings is not one of them in my opinion and experience. Error numbers are much better/safer.

Body:
I would like to know a base thing.

_logger.LogInformation("Hi, Am I magic string?");

In the above line, does the string fall under magic string?

Any hardcoded validation/action against a response/return is considered a "magic string" to me. (Eg: _config["EmailTo"] should be _config.EmailTo, if(list.contains("error")) should be if(list.contains(errorValue))

Appreciate your thoughts!


问:
Styling different width columns in same row Bootstrap
I've just got back in to learning bootstrap, html and css. So far I have three cards in a row of different widths using the bootstrap grid the horizontal card template. My problem is that I want my layout to be the same in each card, The title and paragraph should be the same distance away in each and the fav / info button the same distance from the title. Also, I managed to get the first two columns close but somehow there is weird extra large spacing between the image and title of the last and largest column. How can I do this?

I've tried to manually adjust the positions of the elements in each card but it's hard to get them consistent, it also made my code a mess with extra ids for very similar things. As for the odd spacing I've tried to find the issue using developer tools on chrome to change the width, padding etc but not sure what is causing this. The columns I have are col-md-3, col-md-4 and col-md-5.

these are my cards

```<code><div class="row">
<div class="col-md-3">

 <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-4">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1517/100633l.jpg" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">Attack on Titan</h5>
        <p class="card-text">Airs Sunday :: 10 eps</p>"
 <div class="col-md-4">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-3">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1068/97169l.jpg" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">The Rising of the Shield Hero</h5>
        <p class="card-text">Airs Wednesday :: 26 eps</p>

                <div class="status"></div>
      </div>
    </div>
  </div>
</div>
  </div>

 <div class="col-md-5">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-3">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1130/99458l.jpg" class="card-img-top" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">Hitori Bocchi no Maru Maru Seikatsu</h5>
        <p class="card-text">Airs Saturday :: 12 eps</p>
                <div class="status"></div>

      </div>
    </div>
  </div>
</code>```

I also added it to my codepen to better see also https://codepen.io/Shiro01/pen/YbRQmQ

I'm trying to get them similar to the cards on this site https://anichart.net/airing

I want to have the column fit the content and don't want the title breaking on to another line. I want the distance of the elements to be as equally spaced as possible so the whole design looks consistent. Thank you.

答:
please try this code:

body {
 padding: 70px;
 font-family: arial, helvetica;
 background-color: #ebebeb;
}

.navbar {
 background-color: #fff;
}

.navbar-brand {
 color: #2980b9;    /* Clips image */
 font-size: 20px;
 font-weight: bold;
}

.nav-link {
 color: #2980b9;
}

.mb-3 {
 max-height: 100px;
}

.md-3 {
 max-width: auto;
}

.card-title {
 font-size: 16px;
 font-weight: bold;
 margin-top: -10px;
 margin-bottom: 2px;
 margin-left: -10px;
}

.card-text {
 margin-top: -4px;
 margin-bottom: 40px;
 margin-left: -10px;
 font-size: 12px;
}

/* Clips image */

.img-container {
 display: inline-block;
 width: 100px;
 height: 100px;
 overflow: hidden;
}

.card-img-top {
 position: relative; top: 50%;
 transform: translateY(-35%);
}

.status {
 background-color: #662481;
 height: 100px;
 width: 10px;
 position: relative;
  top: -96px;
 margin-left: auto;
  z-index: 99;
 padding: 0;
  right: -20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport"content="width=device-width, initial scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" href="assets/font/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="index-css-mini.css">

    <title>AniWatch</title>
</head>
<body>

 <div class="container">
    <nav class="navbar navbar-expand-md fixed-top">
    Brand
    <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse">
        <span class="navbar-toggler-icon"></span>
    </button>
        <div class="collapse navbar-collapse" id="navbarCollapse">
        <div class="navbar-nav">
            Airing
            Finished
        </div>
    </div>
    </nav>
    </div> <!-- nav container -->

<div class="row">
    <div class="col-md-3">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-4">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1517/100633l.jpg" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">Attack on Titan</h5>
        <p class="card-text">Airs Sunday :: 10 eps</p>

                <div class="status"></div>

      </div>
    </div>
  </div>
  </div>
  </div>

 <div class="col-md-4">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-3">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1068/97169l.jpg" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-9">
      <div class="card-body">
        <h5 class="card-title">The Rising of the Shield Hero</h5>
        <p class="card-text">Airs Wednesday :: 26 eps</p>

                <div class="status"></div>
      </div>
    </div>
  </div>
</div>
  </div>

 <div class="col-md-5">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-3">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1130/99458l.jpg" class="card-img-top" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-9">
      <div class="card-body">
        <h5 class="card-title">Hitori Bocchi no Maru Maru Seikatsu</h5>
        <p class="card-text">Airs Saturday :: 12 eps</p>
                <div class="status"></div>

      </div>
    </div>
  </div>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

</body>
</html></code>```

Body:
I've just got back in to learning bootstrap, html and css. So far I have three cards in a row of different widths using the bootstrap grid the horizontal card template. My problem is that I want my layout to be the same in each card, The title and paragraph should be the same distance away in each and the fav / info button the same distance from the title. Also, I managed to get the first two columns close but somehow there is weird extra large spacing between the image and title of the last and largest column. How can I do this?

I've tried to manually adjust the positions of the elements in each card but it's hard to get them consistent, it also made my code a mess with extra ids for very similar things. As for the odd spacing I've tried to find the issue using developer tools on chrome to change the width, padding etc but not sure what is causing this. The columns I have are col-md-3, col-md-4 and col-md-5.

these are my cards

Attack on Titan

Airs Sunday :: 10 eps
"

The Rising of the Shield Hero

Airs Wednesday :: 26 eps

Hitori Bocchi no Maru Maru Seikatsu

Airs Saturday :: 12 eps

I also added it to my codepen to better see also https://codepen.io/Shiro01/pen/YbRQmQ

I'm trying to get them similar to the cards on this site https://anichart.net/airing

I want to have the column fit the content and don't want the title breaking on to another line. I want the distance of the elements to be as equally spaced as possible so the whole design looks consistent. Thank you.

Body:
please try this code:

body {
 padding: 70px;
 font-family: arial, helvetica;
 background-color: #ebebeb;
}

.navbar {
 background-color: #fff;
}

.navbar-brand {
 color: #2980b9;    /* Clips image */
 font-size: 20px;
 font-weight: bold;
}

.nav-link {
 color: #2980b9;
}

.mb-3 {
 max-height: 100px;
}

.md-3 {
 max-width: auto;
}

.card-title {
 font-size: 16px;
 font-weight: bold;
 margin-top: -10px;
 margin-bottom: 2px;
 margin-left: -10px;
}

.card-text {
 margin-top: -4px;
 margin-bottom: 40px;
 margin-left: -10px;
 font-size: 12px;
}

/* Clips image */

.img-container {
 display: inline-block;
 width: 100px;
 height: 100px;
 overflow: hidden;
}

.card-img-top {
 position: relative; top: 50%;
 transform: translateY(-35%);
}

.status {
 background-color: #662481;
 height: 100px;
 width: 10px;
 position: relative;
  top: -96px;
 margin-left: auto;
  z-index: 99;
 padding: 0;
  right: -20px;
}

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport"content="width=device-width, initial scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" href="assets/font/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="index-css-mini.css">

    <title>AniWatch</title>
</head>
<body>

 <div class="container">
    <nav class="navbar navbar-expand-md fixed-top">
    <a href="#" class="navbar-brand">Brand</a>
    <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse">
        <span class="navbar-toggler-icon"></span>
    </button>
        <div class="collapse navbar-collapse" id="navbarCollapse">
        <div class="navbar-nav">
            <a href="#" class="nav-item nav-link active">Airing</a>
            <a href="notwatching.html" class="nav-item nav-link">Finished</a>
        </div>
    </div>
    </nav>
    </div> <!-- nav container -->

<div class="row">
    <div class="col-md-3">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-4">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1517/100633l.jpg" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">Attack on Titan</h5>
        <p class="card-text">Airs Sunday :: 10 eps</p>

                <div class="status"></div>

      </div>
    </div>
  </div>
  </div>
  </div>

 <div class="col-md-4">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-3">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1068/97169l.jpg" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-9">
      <div class="card-body">
        <h5 class="card-title">The Rising of the Shield Hero</h5>
        <p class="card-text">Airs Wednesday :: 26 eps</p>

                <div class="status"></div>
      </div>
    </div>
  </div>
</div>
  </div>

 <div class="col-md-5">

        <div class="card mb-3">
  <div class="row no-gutters">
    <div class="col-md-3">
     <div class="img-container"><img src="https://cdn.myanimelist.net/images/anime/1130/99458l.jpg" class="card-img-top" class="card-img-top" class="card-img" alt="..."></div>
    </div>
    <div class="col-md-9">
      <div class="card-body">
        <h5 class="card-title">Hitori Bocchi no Maru Maru Seikatsu</h5>
        <p class="card-text">Airs Saturday :: 12 eps</p>
                <div class="status"></div>

      </div>
    </div>
  </div>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

</body>
</html>


问:
Perl Net::FTP not lists particular file
I am trying to list the file of remote host using Net::FTP Perl module. Later I want to download it using put command.

Will it possible to list the particular file using ls command

Syntax I am using is:

```<code>$remote_dir = "/home/user/test_dir/";
$ftp->cwd($remote_dir);
$file_name = "test.txt";
print $ftp->ls($file_name);
</code>```

This file is exists in remote server when I tried checking it manually. But listing is not happening.

ftp->ls(); is used for only listing the directory contents or can it be used to list the particular file from a directory as I mentioned above?

答:
ftp->ls(); is used for only listing the directory contents or can it be used to list the particular file from a directory

From the documentation:

ls ( [ DIR ] )

  Get a directory listing of DIR, or the current directory.

Thus, it is clearly documented to list a directory, not a specific regular file.

Title: Perl Net::FTP not lists particular file

Body:
I am trying to list the file of remote host using Net::FTP Perl module. Later I want to download it using put command.

Will it possible to list the particular file using ls command

Syntax I am using is:

$remote_dir = "/home/user/test_dir/";
$ftp->cwd($remote_dir);
$file_name = "test.txt";
print $ftp->ls($file_name);

This file is exists in remote server when I tried checking it manually. But listing is not happening.

ftp->ls(); is used for only listing the directory contents or can it be used to list the particular file from a directory as I mentioned above?


问:
Python Tkinter select whole text with left click
I would like for the user to be able to copy to his clipboard the text from a text widget in tkinter just by using his left mouse button. As in: the user clicks on the text with the mouse left button, the whole text in the text widget is selected (with the blue lines in windows) and it is copied automatically to the clipboard.

i've tried both frame.bind method and clipboard_append but was unsuccesfull

I've tried 2 options:

Option 1 with clipboard, this one works but in the background (the text is copied when a button is clicked and not when a user clicks on the text, also the text is not selected with blue lines like in windows so the user does not know the text was copied, it just copies the text in the background without the user knowledge):

```<code>field_value = self.txt.get("1.0", 'end-1c')  # get field value from event, but remove line return at end
txt_frm.clipboard_clear()  # clear clipboard contents
txt_frm.clipboard_append(field_value)  # append new value to clipbaord
</code>```

Option 2 with binding method to button, this one doesn't work at all:

```<code>def copy_text_to_clipboard(event):
    field_value = event.widget.get("1.0", 'end-1c')
    window.clipboard_clear()  # clear clipboard contents
    window.clipboard_append(field_value)  # append new value to clipbaord

    text_field.bind("<Button-1>", copy_text_to_clipboard)
</code>```

答:
try this method :</p>

```<code>def select_all(event=None):
    text_field.select_range(0, END)
    return "break"

text_field.bind('<Button-1>', select_all)
</code>```

Body:
I would like for the user to be able to copy to his clipboard the text from a text widget in tkinter just by using his left mouse button. As in: the user clicks on the text with the mouse left button, the whole text in the text widget is selected (with the blue lines in windows) and it is copied automatically to the clipboard.

i've tried both frame.bind method and clipboard_append but was unsuccesfull

I've tried 2 options:

Option 1 with clipboard, this one works but in the background (the text is copied when a button is clicked and not when a user clicks on the text, also the text is not selected with blue lines like in windows so the user does not know the text was copied, it just copies the text in the background without the user knowledge):

field_value = self.txt.get("1.0", 'end-1c')  # get field value from event, but remove line return at end
txt_frm.clipboard_clear()  # clear clipboard contents
txt_frm.clipboard_append(field_value)  # append new value to clipbaord

Option 2 with binding method to button, this one doesn't work at all:

def copy_text_to_clipboard(event):
    field_value = event.widget.get("1.0", 'end-1c')
    window.clipboard_clear()  # clear clipboard contents
    window.clipboard_append(field_value)  # append new value to clipbaord

    text_field.bind("<Button-1>", copy_text_to_clipboard)

Body:
try this method :

def select_all(event=None):
    text_field.select_range(0, END)
    return "break"

text_field.bind('<Button-1>', select_all)


问:
Swift 4: validating credit card expiration date
I am writing code to check whether the credit card has expired or not.

Here is what I have

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!) /* line 3 - set to first day of month */
let now = Date()
if (enteredDate! < now) {
    //expired
    // does not work if current month and year
    // is the same as the expiration date,
    // because expiration day is set to the first day of the month on line 3
} else {
    // valid
    print("valid - now: \(now) entered: \(enteredDate)")
}
</code>```

Any ideas on how I can change the initialized date to be the last day of the month instead of the first day?

答:
```<code>if enteredDate.compare(now) == ComparisonResult.orderedDescending
        {
            print("valid")
        }
else{
      print("not valid")
}
</code>```

Body:
I am writing code to check whether the credit card has expired or not.

Here is what I have

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/yyyy"
let enteredDate = dateFormatter.date(from: expiryDate.text!) /* line 3 - set to first day of month */
let now = Date()
if (enteredDate! < now) {
    //expired
    // does not work if current month and year
    // is the same as the expiration date,
    // because expiration day is set to the first day of the month on line 3
} else {
    // valid
    print("valid - now: \(now) entered: \(enteredDate)")
}

Any ideas on how I can change the initialized date to be the last day of the month instead of the first day?


问:
I am getting multiple calls from angular to the Post API in Node
I am trying to write a file from the data from the database but I'm getting multiple calls from the angular causing multiple entries of the same data.How can I stop that? And also it is causing to override write file after some time.

I am not getting what exactly should I do. I have tried subscribing thing in service in angular but it was of no help.
component.ts

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModalRef, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { CountryService } from './country.service';
import { ConfigService } from '../config.service';

@Component({
  selector: 'app-country',
  templateUrl: './country.component.html',
  styleUrls: ['./country.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: []
})
export class CountryComponent implements OnInit {
  public modalRef: NgbModalRef;
  public form: FormGroup;
  public selectedCountry;
  public countries;
  constructor(public fb: FormBuilder, public toastrService: ToastrService,
    public modalService: NgbModal, public configService: ConfigService,
    public countryService: CountryService) {

  }

  ngOnInit() {
    this.form = this.fb.group({
      country: [null, Validators.compose([Validators.required])],
    });
    this.getCountries();
  }

  public getCountries() {
    this.countryService.getCountries((data) => {
      this.countries = data.countries;
    }, (err) => { });
  }

  public selectCountry(country) {
    this.countryService.selectCountry(country, (resp) => {
    }, (err) => { });
  }
}
</code>```

service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { ConfigService } from '../config.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class CountryService {
  private setHeaders() {
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });
    return headers;
  }
  constructor(private configService: ConfigService, public http: HttpClient, public toastrService: ToastrService) { }

  selectCountry(country: any, callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.post(this.configService.url + '/selectedCountry', country, options).subscribe((resp: any) => {
      callback(resp);
    }, err => {
      errCallback(err);
    });
  }

  getCountries(callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.get(this.configService.url + '/countries', options).subscribe((resp: any) => {
         callback(resp.msg);
    }, err => {
      errCallback(err);
    });
  }

}
</code>```

I want the call to be sent only once, not twice

答: Need all your code if you can do a stackblitz, and like Mateusz said its better to handle state with ngrx if you dont want to call twice to backend or a simple approach its something like this https://stackblitz.com/edit/angular-biv6cw.</p>

Body:
I am trying to write a file from the data from the database but I'm getting multiple calls from the angular causing multiple entries of the same data.How can I stop that? And also it is causing to override write file after some time.

I am not getting what exactly should I do. I have tried subscribing thing in service in angular but it was of no help.
component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModalRef, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { CountryService } from './country.service';
import { ConfigService } from '../config.service';

@Component({
  selector: 'app-country',
  templateUrl: './country.component.html',
  styleUrls: ['./country.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: []
})
export class CountryComponent implements OnInit {
  public modalRef: NgbModalRef;
  public form: FormGroup;
  public selectedCountry;
  public countries;
  constructor(public fb: FormBuilder, public toastrService: ToastrService,
    public modalService: NgbModal, public configService: ConfigService,
    public countryService: CountryService) {

  }

  ngOnInit() {
    this.form = this.fb.group({
      country: [null, Validators.compose([Validators.required])],
    });
    this.getCountries();
  }

  public getCountries() {
    this.countryService.getCountries((data) => {
      this.countries = data.countries;
    }, (err) => { });
  }

  public selectCountry(country) {
    this.countryService.selectCountry(country, (resp) => {
    }, (err) => { });
  }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { ConfigService } from '../config.service';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root'
})
export class CountryService {
  private setHeaders() {
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });
    return headers;
  }
  constructor(private configService: ConfigService, public http: HttpClient, public toastrService: ToastrService) { }

  selectCountry(country: any, callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.post(this.configService.url + '/selectedCountry', country, options).subscribe((resp: any) => {
      callback(resp);
    }, err => {
      errCallback(err);
    });
  }

  getCountries(callback, errCallback) {
       const options = {
      headers: this.setHeaders(),
    };
    this.http.get(this.configService.url + '/countries', options).subscribe((resp: any) => {
         callback(resp.msg);
    }, err => {
      errCallback(err);
    });
  }

}

I want the call to be sent only once, not twice


问:
Error when opening shapefile
I am trying to open a shapefile in R, but I am getting the following error message:

```<code>Error in getinfo.shape(filen) : Error opening SHP file
</code>```

I have checked other responses and most problems seem to have been solved by ensuring that the .dbf and .shx files are in the same folder. I have them all in the same folder (along with some other extensions too) but I still get the error message. I work on a mac.
This is my code:

```<code>getinfo.shape("/Users/Suz/Desktop/DWH satellite maps/20100517_Composite.shp")
</code>```

I have tried it without the .shp extension, and with other commands, such as readShapePoints etc. Nothing has worked so far. Please help, I am new to R and making maps, and after extensive Googling and forum-reading I am still stuck.

答:
This is still a problem. I solve it more directly calling the shapefile using file.choose() and manually selecting the file. Hope this helps for anyone.

```<code>library (rgdal)
a = readOGR (file.choose()) #then selecting the shape file manually
</code>```

Title: Error when opening shapefile

Body:
I am trying to open a shapefile in R, but I am getting the following error message:

Error in getinfo.shape(filen) : Error opening SHP file

I have checked other responses and most problems seem to have been solved by ensuring that the .dbf and .shx files are in the same folder. I have them all in the same folder (along with some other extensions too) but I still get the error message. I work on a mac.
This is my code:

getinfo.shape("/Users/Suz/Desktop/DWH satellite maps/20100517_Composite.shp")

I have tried it without the .shp extension, and with other commands, such as readShapePoints etc. Nothing has worked so far. Please help, I am new to R and making maps, and after extensive Googling and forum-reading I am still stuck.

Body:
This is still a problem. I solve it more directly calling the shapefile using file.choose() and manually selecting the file. Hope this helps for anyone.

library (rgdal)
a = readOGR (file.choose()) #then selecting the shape file manually