问:
unexpected code completion when typing div.row
I use bootstrap, and when typing html  I want emmet completion for div.row to be:

```<code><div class= "row">
<div>
</code>```

What I get is:

display:.row;

Here are my settings, trying to stop non emmet expansion. What can I do to get the expansion I want?

```<code>"html.suggest.angular1": false,
"html.suggest.ionic": false,
"html.suggest.html5": false,
"editor.wordBasedSuggestions": false,
"editor.acceptSuggestionOnCommitCharacter": false,
"editor.acceptSuggestionOnEnter": false,
"editor.suggestOnTriggerCharacters": false,
"editor.quickSuggestions": {
    "other": false,
    "comments": false,
    "strings": false
</code>```

答: I had an error in settings json for one project. When i fixed the error emmit is working now. </p>

Body:
I use bootstrap, and when typing html  I want emmet completion for div.row to be:

What I get is:

display:.row;

Here are my settings, trying to stop non emmet expansion. What can I do to get the expansion I want?

"html.suggest.angular1": false,
"html.suggest.ionic": false,
"html.suggest.html5": false,
"editor.wordBasedSuggestions": false,
"editor.acceptSuggestionOnCommitCharacter": false,
"editor.acceptSuggestionOnEnter": false,
"editor.suggestOnTriggerCharacters": false,
"editor.quickSuggestions": {
    "other": false,
    "comments": false,
    "strings": false


来源: stackexchange

问:
check if checkbox is checked before submit form in MVC C# and jQuery
at first I had this MVC View that show a list of specific records from database, this is the code and as you can see there is a checkbox column

```<code> <tbody>
                                    @foreach (var item in Model)
                                    {
                                        <tr>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.numero_documento)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_empresa)
                                            </td>
                                            <td>
                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />
                                            </td>
                                        </tr>
                                    }
                                </tbody>
</code>```

and when press the submit button it makes a validation that at least one checkbox has to be checked, like this

```<code>$("#btn-agrupar").click(function (e) {
    if ($("input[type='checkbox']").is(':checked') === true)
        $("#FormAgrupar").submit();
    else {
        if (e.preventDefault) {
            e.preventDefault();
            $("#mostrarmodal").modal("show");
        }
        else {
            e.returnValue = false;
            $("#mostrarmodal").modal("show");
        }
    }
});
</code>```

and used to work but now I do have to added another checkbox column and use jQuery to send to a specific controller the info in the form, this is the code of the view

```<code><tbody>
                                    @foreach (var item in Model)
                                    {
                                        <tr>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.numero_documento)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.nombre_empresa)
                                            </td>
                                            <td>
                                                <input type="checkbox" name="delete" value="@item.numero_documento" +"a" />
                                            </td>
                                            <td>
                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />
                                            </td>
                                        </tr>
                                    }
                                </tbody>
</code>```

and this is the code of my jQuery, the problem is that now it doesn´t validate if at least one checkbox is checked for none of the checkbox columns, could you help me and tell me the problem?

```<code> $("#btn-agrupar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("RealizarAgrupacion","Home")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

        $("#btn-eliminar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("Index","Contact")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });
</code>```

this is the code of the buttons in my form

```<code><input type="button" value="Cancelar" id="btn-cancelar" class="btn btn-danger" />
                        <input type="button" value="Eliminar Solicitudes" id="btn-eliminar" class="btn btn-danger" />
                        <input type="button" value="Agrupar Solicitudes" id="btn-agrupar" class="btn btn-primary pull-right" />
</code>```

答:
Seems both the checkbox columns don't have any difference. You can specify some html attribute like aria-describedby attribute. For example
For the first Checkbox aria-describedby="Delete" and for the second one aria-describedby="code" like below

```<code><tbody>
    @foreach (var item in Model)
    {
      <tr>
        <td>
            @Html.DisplayFor(modelItem => item.numero_documento)
       </td>
       <td>
          @Html.DisplayFor(modelItem => item.nombre_accion_formativa)
       </td>
       <td>
          @Html.DisplayFor(modelItem => item.nombre_empresa)
       </td>
       <td>
          <input type="checkbox" name="delete" aria-describedby="Delete" value="@item.numero_documento" +"a" />
       </td>
       <td>
          <input type="checkbox" name="code" aria-describedby="Code" value="@item.numero_documento" +"a" />
       </td>
     </tr>
    }
</tbody>
</code>```

And it would be better to check the length of the checkboxes which are checked because you are saying atleast one checkbox can be checked means all are not mandatory to check. In that situation try to change the code as following.

```<code>$("#btn-agrupar").click(function (e) {
            if ($("input[aria-describedby='Delete']").is(':checked').length) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("RealizarAgrupacion","Home")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });
</code>```

If the above code works change the code in the button click code also.

ContentLicense: CC BY-SA 3.0

Body:
at first I had this MVC View that show a list of specific records from database, this is the code and as you can see there is a checkbox column

                                    @foreach (var item in Model)
                                    {

                                                @Html.DisplayFor(modelItem => item.numero_documento)

                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)

                                                @Html.DisplayFor(modelItem => item.nombre_empresa)

                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />

                                    }

and when press the submit button it makes a validation that at least one checkbox has to be checked, like this

$("#btn-agrupar").click(function (e) {
    if ($("input[type='checkbox']").is(':checked') === true)
        $("#FormAgrupar").submit();
    else {
        if (e.preventDefault) {
            e.preventDefault();
            $("#mostrarmodal").modal("show");
        }
        else {
            e.returnValue = false;
            $("#mostrarmodal").modal("show");
        }
    }
});

and used to work but now I do have to added another checkbox column and use jQuery to send to a specific controller the info in the form, this is the code of the view

                                    @foreach (var item in Model)
                                    {

                                                @Html.DisplayFor(modelItem => item.numero_documento)

                                                @Html.DisplayFor(modelItem => item.nombre_accion_formativa)

                                                @Html.DisplayFor(modelItem => item.nombre_empresa)

                                                <input type="checkbox" name="delete" value="@item.numero_documento" +"a" />

                                                <input type="checkbox" name="code" value="@item.numero_documento" +"a" />

                                    }

and this is the code of my jQuery, the problem is that now it doesn´t validate if at least one checkbox is checked for none of the checkbox columns, could you help me and tell me the problem?

 $("#btn-agrupar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("RealizarAgrupacion","Home")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

        $("#btn-eliminar").click(function () {
            if ($("input[type='checkbox']").is(':checked') === true) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("Index","Contact")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

this is the code of the buttons in my form

<input type="button" value="Cancelar" id="btn-cancelar" class="btn btn-danger" />
                        <input type="button" value="Eliminar Solicitudes" id="btn-eliminar" class="btn btn-danger" />
                        <input type="button" value="Agrupar Solicitudes" id="btn-agrupar" class="btn btn-primary pull-right" />

Body:
Seems both the checkbox columns don't have any difference. You can specify some html attribute like aria-describedby attribute. For example
For the first Checkbox aria-describedby="Delete" and for the second one aria-describedby="code" like below

<tbody>
    @foreach (var item in Model)
    {
      <tr>
        <td>
            @Html.DisplayFor(modelItem => item.numero_documento)
       </td>
       <td>
          @Html.DisplayFor(modelItem => item.nombre_accion_formativa)
       </td>
       <td>
          @Html.DisplayFor(modelItem => item.nombre_empresa)
       </td>
       <td>
          <input type="checkbox" name="delete" aria-describedby="Delete" value="@item.numero_documento" +"a" />
       </td>
       <td>
          <input type="checkbox" name="code" aria-describedby="Code" value="@item.numero_documento" +"a" />
       </td>
     </tr>
    }
</tbody>

And it would be better to check the length of the checkboxes which are checked because you are saying atleast one checkbox can be checked means all are not mandatory to check. In that situation try to change the code as following.

$("#btn-agrupar").click(function (e) {
            if ($("input[aria-describedby='Delete']").is(':checked').length) {
                var form = $("#FormAgrupar");
                form.attr("action", "@Url.Action("RealizarAgrupacion","Home")");
                form.submit();
            }
            else {
                if (e.preventDefault) {
                    e.preventDefault();
                    $("#mostrarmodal").modal("show");
                }
                else {
                    e.returnValue = false;
                    $("#mostrarmodal").modal("show");
                }
            }
        });

If the above code works change the code in the button click code also.


问:
How to find the Gaussian Weighted-Average and Standard deviation of a structural element
I'm trying to implement an Intensity Normalization algorithm that is described by this formula:

x' = (x - gaussian_weighted_average) / std_deviation

The paper I'm following describes that I have to find the gaussian weighted average and the standard deviation corresponding to each pixel "x" neighbors using a 7x7 kernel.

PS: x' is the new pixel value.

So, my question is: how can I compute a gaussian weighted average and the standard deviation for each pixel in image using a 7x7 kernel?

Does OpenCV provide any method to solve this?

```<code>import cv2
img = cv2.imread("b.png", 0)
widht = img.shape[0]
height = img.shape[1]
for i in range (widht):
    for j in range (height):
        new_image = np.zeros((height,width,1), np.uint8)
        new_image[i][j] = img[i][j] - ...
</code>```

答:
The original implementation (C++) of the author can be found here: see GenerateIntensityNormalizedDatabase().

This has been re-implemented by another student in python. The python implementation is:

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

def StdDev(img, meanPoint, point, kSize):
    kSizeX, kSizeY = kSize / 2, kSize / 2

    ystart = point[1] - kSizeY if 0 < point[1] - kSizeY < img.shape[0] else 0
    yend = point[1] + kSizeY + 1 if 0 < point[1] + kSizeY + 1 < img.shape[0] else img.shape[0] - 1

    xstart = point[0] - kSizeX if 0 < point[0] - kSizeX < img.shape[1] else 0
    xend = point[0] + kSizeX + 1 if 0 < point[0] + kSizeX + 1 < img.shape[1] else img.shape[1] - 1

    patch = (img[ystart:yend, xstart:xend] - meanPoint) ** 2
    total = np.sum(patch)
    n = patch.size

    return 1 if total == 0 or n == 0 else np.sqrt(total / float(n))

def IntensityNormalization(img, kSize):
    blur = cv2.GaussianBlur(img, (kSize, kSize), 0, 0).astype(np.float64)
    newImg = np.ones(img.shape, dtype=np.float64) * 127

    for x in range(img.shape[1]):
        for y in range(img.shape[0]):
            original = img[y, x]
            gauss = blur[y, x]
            desvio = StdDev(img, gauss, [x, y], kSize)

            novoPixel = 127
            if desvio > 0:
                novoPixel = (original - gauss) / float(desvio)

            newVal = np.clip((novoPixel * 127 / float(2.0)) + 127, 0, 255)
            newImg[y, x] = newVal
    return newImg
</code>```

To use the intensity normalization, you could do this:

```<code>kSize = 7
img = cv2.imread('{IMG_FILENAME}', cv2.IMREAD_GRAYSCALE).astype(np.float64)
out = IntensityNormalization(img, kSize)
</code>```

To visualize the resulting image, don't forget to convert out back to np.uint8 (why?). I'd recommend you to use the original implementation in C++ if you want to reproduce his results.

Disclaimer: I'm from the same lab of the author of this paper.

Body:
I'm trying to implement an Intensity Normalization algorithm that is described by this formula:

x' = (x - gaussian_weighted_average) / std_deviation

The paper I'm following describes that I have to find the gaussian weighted average and the standard deviation corresponding to each pixel "x" neighbors using a 7x7 kernel.

PS: x' is the new pixel value.

So, my question is: how can I compute a gaussian weighted average and the standard deviation for each pixel in image using a 7x7 kernel?

Does OpenCV provide any method to solve this?

import cv2
img = cv2.imread("b.png", 0)
widht = img.shape[0]
height = img.shape[1]
for i in range (widht):
    for j in range (height):
        new_image = np.zeros((height,width,1), np.uint8)
        new_image[i][j] = img[i][j] - ...

Body:
The original implementation (C++) of the author can be found here: see GenerateIntensityNormalizedDatabase().

This has been re-implemented by another student in python. The python implementation is:

import cv2
import numpy as np

def StdDev(img, meanPoint, point, kSize):
    kSizeX, kSizeY = kSize / 2, kSize / 2

    ystart = point[1] - kSizeY if 0 < point[1] - kSizeY < img.shape[0] else 0
    yend = point[1] + kSizeY + 1 if 0 < point[1] + kSizeY + 1 < img.shape[0] else img.shape[0] - 1

    xstart = point[0] - kSizeX if 0 < point[0] - kSizeX < img.shape[1] else 0
    xend = point[0] + kSizeX + 1 if 0 < point[0] + kSizeX + 1 < img.shape[1] else img.shape[1] - 1

    patch = (img[ystart:yend, xstart:xend] - meanPoint) ** 2
    total = np.sum(patch)
    n = patch.size

    return 1 if total == 0 or n == 0 else np.sqrt(total / float(n))

def IntensityNormalization(img, kSize):
    blur = cv2.GaussianBlur(img, (kSize, kSize), 0, 0).astype(np.float64)
    newImg = np.ones(img.shape, dtype=np.float64) * 127

    for x in range(img.shape[1]):
        for y in range(img.shape[0]):
            original = img[y, x]
            gauss = blur[y, x]
            desvio = StdDev(img, gauss, [x, y], kSize)

            novoPixel = 127
            if desvio > 0:
                novoPixel = (original - gauss) / float(desvio)

            newVal = np.clip((novoPixel * 127 / float(2.0)) + 127, 0, 255)
            newImg[y, x] = newVal
    return newImg

To use the intensity normalization, you could do this:

kSize = 7
img = cv2.imread('{IMG_FILENAME}', cv2.IMREAD_GRAYSCALE).astype(np.float64)
out = IntensityNormalization(img, kSize)

To visualize the resulting image, don't forget to convert out back to np.uint8 (why?). I'd recommend you to use the original implementation in C++ if you want to reproduce his results.

Disclaimer: I'm from the same lab of the author of this paper.


问:
Creating a dataframe from a scraped character vector
I am trying to create a dataframe that has the columns: First name, Last name, Party, State, Member ID. Here is my code

```<code>library('rvest')

candidate_url <- 'https://www.congress.gov/help/field-values/member-bioguide-ids'
candidate_page <- read_html(candidate_url)
candidate_nodes <- html_nodes(candidate_page, 'table')
candidate_list <- html_text(candidate_nodes)
</code>```

My main issue is getting the member IDs. An example ID is A000009. When I use the gsub function I lose the leading A in this example. The A is from this candidate's last name (Abercrombie), but I do not know how to add the A back into the member ID. Of course if there's a better way I am open to any suggestions.

答:
Give this a try. I have updated this to include separating out the different fields.</p>

```<code>library('rvest')
library('dplyr')
library('tidyr')

candidate_url <- 'https://www.congress.gov/help/field-values/member-bioguide-ids'
candidate_page <- read_html(candidate_url)
candidate_nodes <- html_nodes(candidate_page, 'table')
df.candidates <- as.data.frame(html_table(candidate_nodes, header = TRUE, fill = TRUE), stringsAsFactors = FALSE)
df.candidates <- df.candidates[!is.na(df.candidates$Member),]

df.candidates <- df.candidates %>%
                 mutate(Party.State = gsub("[\\(\\)]", "", regmatches(Member, gregexpr("\\(.*?\\)", Member))[[1]])) %>%
                 separate(Party.State, into = c("Party","State"), sep = " - ") %>%
                 mutate(Full.name = trimws(regmatches(df.candidates$Member, regexpr("^[^\\(]+", df.candidates$Member)))) %>%
                 separate(Full.name, into = c("Last.Name","First.Name","Suffix"), sep = ",", fill = "right") %>%
                 select(First.Name, Last.Name, Suffix, Party, State, Member.ID)
</code>```

Body:
I am trying to create a dataframe that has the columns: First name, Last name, Party, State, Member ID. Here is my code

library('rvest')

candidate_url <- 'https://www.congress.gov/help/field-values/member-bioguide-ids'
candidate_page <- read_html(candidate_url)
candidate_nodes <- html_nodes(candidate_page, 'table')
candidate_list <- html_text(candidate_nodes)

My main issue is getting the member IDs. An example ID is A000009. When I use the gsub function I lose the leading A in this example. The A is from this candidate's last name (Abercrombie), but I do not know how to add the A back into the member ID. Of course if there's a better way I am open to any suggestions.

Body:
Give this a try. I have updated this to include separating out the different fields.

library('rvest')
library('dplyr')
library('tidyr')

candidate_url <- 'https://www.congress.gov/help/field-values/member-bioguide-ids'
candidate_page <- read_html(candidate_url)
candidate_nodes <- html_nodes(candidate_page, 'table')
df.candidates <- as.data.frame(html_table(candidate_nodes, header = TRUE, fill = TRUE), stringsAsFactors = FALSE)
df.candidates <- df.candidates[!is.na(df.candidates$Member),]

df.candidates <- df.candidates %>%
                 mutate(Party.State = gsub("[\\(\\)]", "", regmatches(Member, gregexpr("\\(.*?\\)", Member))[[1]])) %>%
                 separate(Party.State, into = c("Party","State"), sep = " - ") %>%
                 mutate(Full.name = trimws(regmatches(df.candidates$Member, regexpr("^[^\\(]+", df.candidates$Member)))) %>%
                 separate(Full.name, into = c("Last.Name","First.Name","Suffix"), sep = ",", fill = "right") %>%
                 select(First.Name, Last.Name, Suffix, Party, State, Member.ID)


问:
Structuring Cucumber JVM step definitions in different java files
I am working on an automation project based on Appium-cucumber-Java, which will be growing over time.

Currently, I have Step definitions Given,When, Then in one file for iOS & another file for Android.
Both of these, files extend from a common basetest class.
I initialize required Page Objects using new keyword in both of these files.

Now, I would like to modularise it little bit & create a CommonStepDefs file. But I am starting to get nullpointer exception.

Can you please suggest with any method similar to this or sample example to build this

Thanks in advance.

```<code>public class AndroidTestsStepDefs_usingFactory extends BaseTestClass {

AndroidChooseCountryPage androidChooseCountryPage;
AndroidCountrySelectionPage androidCountrySelectionPage;
OrderPrints orderPrints;
AndroidHomePage androidHomePage;
TourPage tourPage;

public AndroidTestsStepDefs_usingFactory() throws IOException, AWTException {
}

@Given("^the app has been installed$")
public void the_app_has_been_installed() throws Throwable {
    initializeDriver("android");
    super.setCoreAppType("Android");
}
</code>```

答:
You are interested in sharing state between your step definitions files.

The idiomatic to share state in Java is to create a common object that is shared between all steps using dependency injection.

If your project uses a dependency injection framework, use the same for sharing state between the step definition classes. Cucumber-JVM supports many different dependency injection frameworks. Yours is probably supported.

If you don't use a dependency injection, I suggest using PicoContainer.

I have written two blog post on the topic. Sharing state using

PicoContainer:
http://www.thinkcode.se/blog/2017/04/01/sharing-state-between-steps-in-cucumberjvm-using-picocontainer

Spring:
http://www.thinkcode.se/blog/2017/06/24/sharing-state-between-steps-in-cucumberjvm-using-spring

Body:
I am working on an automation project based on Appium-cucumber-Java, which will be growing over time.

Currently, I have Step definitions Given,When, Then in one file for iOS & another file for Android.
Both of these, files extend from a common basetest class.
I initialize required Page Objects using new keyword in both of these files.

Now, I would like to modularise it little bit & create a CommonStepDefs file. But I am starting to get nullpointer exception.

Can you please suggest with any method similar to this or sample example to build this

Thanks in advance.

public class AndroidTestsStepDefs_usingFactory extends BaseTestClass {

AndroidChooseCountryPage androidChooseCountryPage;
AndroidCountrySelectionPage androidCountrySelectionPage;
OrderPrints orderPrints;
AndroidHomePage androidHomePage;
TourPage tourPage;

public AndroidTestsStepDefs_usingFactory() throws IOException, AWTException {
}

@Given("^the app has been installed$")
public void the_app_has_been_installed() throws Throwable {
    initializeDriver("android");
    super.setCoreAppType("Android");
}


问:
How to move head to left in ParticleHead.js
I want to move particle head to left in particlehead.Js . Please help me.
This is the github repository: https://github.com/vs811/RightCust
This is the live preview: http://cdn.rawgit.com/vs811/RightCust/vs811-patch-5/indexnew.html

ParticleHead is on third slide

答:
Did you give particlehead.js a look? I found these two variables about 20 lines in.

```<code>var windowHalfX = site.Width / 2;
var windowHalfY = site.Height / 2;
</code>```

Try changing these to move the head where you want it to go.
If that doesn't work, take a look at the style.css file and modify the particle head class shown here:

```<code>.particlehead {
    background: #000000;
}
</code>```

Body:
Did you give particlehead.js a look? I found these two variables about 20 lines in.

var windowHalfX = site.Width / 2;
var windowHalfY = site.Height / 2;

Try changing these to move the head where you want it to go.
If that doesn't work, take a look at the style.css file and modify the particle head class shown here:

.particlehead {
    background: #000000;
}


问:
The name 'Scripts' does not exists in the current context in MVC
In my mvc application, In the _Layout.cshtml has code below...

```<code><head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
</code>```

But the problem is it says The name 'Scripts' does not exists in the current context.

I have already added the assembly to the reference and to the Bundle config as using System.Web.Optimization;

This happens for @styles also..
What should I do?

答:
Please Follow My Step will Clear this

First

Install Microsoft.AspNet.Web.Optimisation

Check that the App_Start Folder contains a BundleConfig.cs File.

Add <namespaces>
        <add namespace="System.Web.Optimization"/>
      </namespaces>
in Views/web.config File

Add BundleConfig.RegisterBundles(BundleTable.Bundles); in Global.asax.cs

Rebuild and Run it

Body:
In my mvc application, In the _Layout.cshtml has code below...

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

But the problem is it says The name 'Scripts' does not exists in the current context.

I have already added the assembly to the reference and to the Bundle config as using System.Web.Optimization;

This happens for @styles also..
What should I do?


问:
jQuery.post() data not "posting"
I am working on a project that requires posting JSON data to a specific URL. I am trying to use the jQuery.post() method to do this. I have two problems I can't seem to figure out.

The first problem:

```<code>jQuery.post("http://cowbell.grooveshark.com/more.php?getCommunicationToken", dataString, function(data){ alert(data) } );
</code>```

Using a packet sniffer I discovered that the variable dataString was not being posted. Really no content was being posted at all.

The second problem is that the more.php script was returning the the content below in a packet:

```<code>could not parse, no method specified!
</code>```

This isn't a problem at the moment; however, the success function in my jQuery.post() alerted with an empty data variable.

Here are my references:

http://api.jquery.com/jQuery.post/

http://nettech.wikia.com/wiki/Grooveshark_Internal_API

Thanks for any help anyone has!

答: Does the domain you are posting to have a web service that it can expose to you? That will help you in posting the data correctly...</p>

ContentLicense: CC BY-SA 2.5

Title: jQuery.post() data not "posting"

Body:
I am working on a project that requires posting JSON data to a specific URL. I am trying to use the jQuery.post() method to do this. I have two problems I can't seem to figure out.

The first problem:

jQuery.post("http://cowbell.grooveshark.com/more.php?getCommunicationToken", dataString, function(data){ alert(data) } );

Using a packet sniffer I discovered that the variable dataString was not being posted. Really no content was being posted at all.

The second problem is that the more.php script was returning the the content below in a packet:

could not parse, no method specified!

This isn't a problem at the moment; however, the success function in my jQuery.post() alerted with an empty data variable.

Here are my references:

http://api.jquery.com/jQuery.post/

http://nettech.wikia.com/wiki/Grooveshark_Internal_API

Thanks for any help anyone has!


问:
React Native access strings.xml from inside javascript code
Is there a way to access the current values from android/app/src/main/res/values/strings.xml from inside Javascript code? I want to place different endpoint URLs for each build, but I'm failing even to detect the type of build inside react-native code without having to resort to the __DEV__ variable (which can be turned off from the dev menu)

答: The only way this might be possible would be building a bridge using native modules, https://facebook.github.io/react-native/docs/native-modules-android.html. Essential you can pass strings in JS to the native modules and have native function handle which string to grab and pass back to JS.</p>


问:
AttributeError: Unknown property cmap
I have the following 2 errors:

```<code>AttributeError: Unknown property cmap
</code>```

and

```<code>Cannot find reference 'coolwarm' in 'cm.py'
</code>```

I have run:

```<code>import matplotlib.pyplot as plt
import matplotlib
import matplotlib.cm as cm
</code>```

Code I get the error with is

```<code>fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

ax1.plot(result['tme'], result['spread'], ".", markersize=1,
c=result['bdaterange'], cmap=cm.coolwarm)
</code>```

答:
Colormap coolwarm is added to matplotlib since 1.1.0 (commit).

Update your matplotlib after it then you'll get it working.

```<code>pip install --upgrade matplotlib
</code>```

Title: AttributeError: Unknown property cmap

Body:
I have the following 2 errors:

AttributeError: Unknown property cmap

and

Cannot find reference 'coolwarm' in 'cm.py'

I have run:

import matplotlib.pyplot as plt
import matplotlib
import matplotlib.cm as cm

Code I get the error with is

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

ax1.plot(result['tme'], result['spread'], ".", markersize=1,
c=result['bdaterange'], cmap=cm.coolwarm)

Body:
Colormap coolwarm is added to matplotlib since 1.1.0 (commit).

Update your matplotlib after it then you'll get it working.

pip install --upgrade matplotlib


问:
Why does the TextMate title bar not show the file path when opened with the "mate" command?
When I open a file in TextMate using the mate command the title bar does not allow me to right click to see the path of the file while files opened within the TextMate app do show the full path.  Is there something about the behavior of the mate command that prevents this functionality or is this a bug?

答:
Go to folder "/Applications/TextMate.app/Contents/Resources" or where your TextMate.app installation folder. Close textmate app before modifying the file.

Modify the file Default.tmProperties as below. I have provided the diff here:

diff Default.tmProperties

 ../textmateBin/TextMate.app/Contents/Resources/Default.tmProperties
10c10

    < windowTitleProject = '${projectDirectory:+ — ${projectDirectory}}'

windowTitleProject = '${projectDirectory:+ — ${projectDirectory/^.*///}}'

Restart your textmate app and it should display your folder path :)


问:
Line contains invalid enclosed character data or delimiter at position
I was trying to load the data from the csv file into the Oracle sql developer, when inserting the data I encountered the error which says:

Line contains invalid enclosed character data or delimiter at position

I am not sure how to tackle this problem!

For Example:

```<code>    INSERT INTO PROJECT_LIST (Project_Number, Name, Manager, Projects_M,
Project_Type, In_progress, at_deck, Start_Date, release_date, For_work, nbr,
List, Expenses) VALUES ('5770','"Program Cardinal
(Agile)','','','','','',to_date('', 'YYYY-MM-DD'),'','','','','');
</code>```

The Error shown were:

--Insert failed for row  4

--Line contains invalid enclosed character data or delimiter at position 79.

--Row 4

答: I fixed it by using the concatenate function in my CSV file first and then uploaded it on sql, which worked. </p>

Body:
I was trying to load the data from the csv file into the Oracle sql developer, when inserting the data I encountered the error which says:

Line contains invalid enclosed character data or delimiter at position

I am not sure how to tackle this problem!

For Example:

    INSERT INTO PROJECT_LIST (Project_Number, Name, Manager, Projects_M,
Project_Type, In_progress, at_deck, Start_Date, release_date, For_work, nbr,
List, Expenses) VALUES ('5770','"Program Cardinal
(Agile)','','','','','',to_date('', 'YYYY-MM-DD'),'','','','','');

The Error shown were:

--Insert failed for row  4

--Line contains invalid enclosed character data or delimiter at position 79.

--Row 4


问:
Use json in typescript with ionic
I'm using typescript and I'm trying to declare a variable with the data from my json file. I already made some interfaces using js2ts.com. But I don't know how to call the json file in my typescript file.</p>

答:
If it's just a json file/structure, you're going to need to make an AJAX call to it like it was a server resource. If it's an object within a module/library, you can import the object. I'm assuming this is a web app, since you mentioned ionic. If it were a NodeJS app, you could load the resource using the fs module.

Some flavor of the following should work:

```<code>$http({
    method: 'GET',
    url: '/PATH_TO_JSON'
}).then(function success(response) {
    // Success handling
}, function failure(response) {
   // Error handling
 });
</code>```

If you are attempting to access the file when it is on the device, look into the Cordova File API.

Title: Use json in typescript with ionic

Body:
If it's just a json file/structure, you're going to need to make an AJAX call to it like it was a server resource. If it's an object within a module/library, you can import the object. I'm assuming this is a web app, since you mentioned ionic. If it were a NodeJS app, you could load the resource using the fs module.

Some flavor of the following should work:

$http({
    method: 'GET',
    url: '/PATH_TO_JSON'
}).then(function success(response) {
    // Success handling
}, function failure(response) {
   // Error handling
 });

If you are attempting to access the file when it is on the device, look into the Cordova File API.


问:
Generic Static Class as Service Locator
I am applying the Service Locator pattern as described in Game Programming Patterns, and am wondering about a possible generic implementation. The following code does work, but I am confused about using a class that is both generic and static.

The idea of the following C# code is to provide a "global" service to other parts of the application, exposing only an interface rather than the full implementation. Each service registered using this method will only have one instance in the application, but I want to be able to easily swap in/out different implementations of the provided interfaces.

My question is: when I use the following class to provide different services throughout my application, how does C# know that I am referring to different services of different types? Intuitively, I would almost think that the static variable, _service, would be overridden with each new service.

```<code>public static class ServiceLocator<T>
{
    static T _service;

    public static T GetService()
    {
        return _service;
    }

    public static void Provide(T service)
    {
        _service = service;
    }
}
</code>```

Here's some usage:

```<code>// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocator<ICamera>.Provide(_camera);

// Elsewhere, usage:
ICamera camera = ServiceLocator<ICamera>.GetService();

// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocator<IMap>.Provide(CurrentMap);

// Elsewhere, using this different service:
IMap map = ServiceLocator<IMap>.GetService();
</code>```

答:
C# creates a separate closed type for every combination of generic parameters for open type.

Since every combination of generic parameters creates a separate class, calling a static constructor and creating own members for each of them.
You can think of them like of different classes.

```<code>public static class GenericCounter<T>
{
    public static int Count { get; set; } = 0;
}

GenericCounter<int>.Count++;
GenericCounter<int>.Count++;
GenericCounter<string>.Count++;
Console.WriteLine(GenericCounter<double>.Count); // 0
Console.WriteLine(GenericCounter<int>.Count); // 2
Console.WriteLine(GenericCounter<string>.Count); // 1
</code>```

This code outputs:

```<code>0
2
1
</code>```

For example, in your case, behavior will be the same as if you created two separate classes:

```<code>public static class ServiceLocatorOfIMap
{
    static IMap _service;

    public static IMap GetService()
    {
        return _service;
    }

    public static void Provide(IMap service)
    {
        _service = service;
    }
}

public static class ServiceLocatorOfICamera
{
    static ICamera _service;

    public static ICamera GetService()
    {
        return _service;
    }

    public static void Provide(ICamera service)
    {
        _service = service;
    }
}
</code>```

and used it like this:

```<code>// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocatorForICamera.Provide(_camera);

// Elsewhere, usage:
ICamera camera = ServiceLocatorForICamera.GetService();

// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocatorForIMap.Provide(CurrentMap);

// Elsewhere, using this different service:
IMap map = ServiceLocatorForIMap.GetService();
</code>```

In general, it is similar to what C# does when it meets static generic classes.

Title: Generic Static Class as Service Locator

Body:
I am applying the Service Locator pattern as described in Game Programming Patterns, and am wondering about a possible generic implementation. The following code does work, but I am confused about using a class that is both generic and static.

The idea of the following C# code is to provide a "global" service to other parts of the application, exposing only an interface rather than the full implementation. Each service registered using this method will only have one instance in the application, but I want to be able to easily swap in/out different implementations of the provided interfaces.

My question is: when I use the following class to provide different services throughout my application, how does C# know that I am referring to different services of different types? Intuitively, I would almost think that the static variable, _service, would be overridden with each new service.

public static class ServiceLocator<T>
{
    static T _service;

    public static T GetService()
    {
        return _service;
    }

    public static void Provide(T service)
    {
        _service = service;
    }
}

Here's some usage:

// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocator<ICamera>.Provide(_camera);

// Elsewhere, usage:
ICamera camera = ServiceLocator<ICamera>.GetService();

// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocator<IMap>.Provide(CurrentMap);

// Elsewhere, using this different service:
IMap map = ServiceLocator<IMap>.GetService();

Body:
C# creates a separate closed type for every combination of generic parameters for open type.

Since every combination of generic parameters creates a separate class, calling a static constructor and creating own members for each of them.
You can think of them like of different classes.

public static class GenericCounter<T>
{
    public static int Count { get; set; } = 0;
}

GenericCounter<int>.Count++;
GenericCounter<int>.Count++;
GenericCounter<string>.Count++;
Console.WriteLine(GenericCounter<double>.Count); // 0
Console.WriteLine(GenericCounter<int>.Count); // 2
Console.WriteLine(GenericCounter<string>.Count); // 1

This code outputs:

0
2
1

For example, in your case, behavior will be the same as if you created two separate classes:

public static class ServiceLocatorOfIMap
{
    static IMap _service;

    public static IMap GetService()
    {
        return _service;
    }

    public static void Provide(IMap service)
    {
        _service = service;
    }
}

public static class ServiceLocatorOfICamera
{
    static ICamera _service;

    public static ICamera GetService()
    {
        return _service;
    }

    public static void Provide(ICamera service)
    {
        _service = service;
    }
}

and used it like this:

// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocatorForICamera.Provide(_camera);

// Elsewhere, usage:
ICamera camera = ServiceLocatorForICamera.GetService();

// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocatorForIMap.Provide(CurrentMap);

// Elsewhere, using this different service:
IMap map = ServiceLocatorForIMap.GetService();

In general, it is similar to what C# does when it meets static generic classes.


问:
Is there any way to change char* value at any index?
As I know, if we declare char* in our program then it gives memory from read-only area, so we are not able to change a char at any position in the array.

```<code>char *ch = "sitaram";
ch[2] = 'y';
</code>```

The above code will not run properly, as we are changing read-only memory.

One approach is we can declare our char array as

```<code>char ch[] = "sitaram";
</code>```

and then we can change a value at an index.

Is there any way where I can change a char value at any index in a char*?

答:
Using char arrays:

```<code>char text[] = "sitaram";
text[3] = 'o';
char * p = &text[0];
p[4] = 'x';
cout << text;
</code>```

Body:
As I know, if we declare char* in our program then it gives memory from read-only area, so we are not able to change a char at any position in the array.

char *ch = "sitaram";
ch[2] = 'y';

The above code will not run properly, as we are changing read-only memory.

One approach is we can declare our char array as

char ch[] = "sitaram";

and then we can change a value at an index.

Is there any way where I can change a char value at any index in a char*?

Body:
Using char arrays:

char text[] = "sitaram";
text[3] = 'o';
char * p = &text[0];
p[4] = 'x';
cout << text;


问:
boost multiindex: lower_bound with value_type as argument
I'd like to use lower_bound with the value_type of a Boost MultiIndex Container. So far, I only managed to make this work by explicitly extracting the members:

```<code>#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
#include <string>

struct name {
    std::string firstname;
    std::string lastname;
    name(const std::string & firstname, const std::string & lastname) :
        firstname(firstname), lastname(lastname) {}
};

typedef boost::multi_index::multi_index_container<
    name,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_unique<
            boost::multi_index::composite_key<
                name,
                boost::multi_index::member<name, std::string, &name::lastname>,
                boost::multi_index::member<name, std::string, &name::firstname>
            >,
            boost::multi_index::composite_key_compare<
                std::less<std::string>,
                std::less<std::string>
            >
        >
    >
> NameIndex;

int main(void) {
    NameIndex nameindex;
    nameindex.insert(name("Alfred", "Ammer"));
    nameindex.insert(name("Martin", "Mauser"));
    // In my real code, I get this object passed.
    name lookupname("Hans", "Hoffer");

    // Does not compile
    //auto it = nameindex.get<0>().lower_bound(lookupname);

    // compiles, but I have to take explicitly list the members - in the right order
    auto it = nameindex.get<0>().lower_bound(std::make_tuple(lookupname.lastname, lookupname.firstname));
}
</code>```

How can I avoid extracting the members?

答:
Write</p>

```<code>auto it = nameindex.get<0>().lower_bound(
    nameindex.get<0>().key_extractor()(lookupname));
</code>```

Body:
I'd like to use lower_bound with the value_type of a Boost MultiIndex Container. So far, I only managed to make this work by explicitly extracting the members:

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
#include <string>

struct name {
    std::string firstname;
    std::string lastname;
    name(const std::string & firstname, const std::string & lastname) :
        firstname(firstname), lastname(lastname) {}
};

typedef boost::multi_index::multi_index_container<
    name,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_unique<
            boost::multi_index::composite_key<
                name,
                boost::multi_index::member<name, std::string, &name::lastname>,
                boost::multi_index::member<name, std::string, &name::firstname>
            >,
            boost::multi_index::composite_key_compare<
                std::less<std::string>,
                std::less<std::string>
            >
        >
    >
> NameIndex;

int main(void) {
    NameIndex nameindex;
    nameindex.insert(name("Alfred", "Ammer"));
    nameindex.insert(name("Martin", "Mauser"));
    // In my real code, I get this object passed.
    name lookupname("Hans", "Hoffer");

    // Does not compile
    //auto it = nameindex.get<0>().lower_bound(lookupname);

    // compiles, but I have to take explicitly list the members - in the right order
    auto it = nameindex.get<0>().lower_bound(std::make_tuple(lookupname.lastname, lookupname.firstname));
}

How can I avoid extracting the members?

Body:
Write

auto it = nameindex.get<0>().lower_bound(
    nameindex.get<0>().key_extractor()(lookupname));


问:
What is the best way to communicate between client socket and server socket which suppors multiple types of action?
In short:

The main problem is, for an online game, server should support multiple types of action which client wants to do, such like: "Sign in game." , "Create a game room." , "Launch a game.", "send a chat message.", "Get a room list." ...

But if I'm going to use Socket, I'm wondering what is the best way to distinguish out the type of the action from each message received or sended between server and client.

This is what the deployment of my online game looks like:

For supporting multiple types of action, my first idea:

If I choose to use JSON, it might look like:

```<code>{
    "action":"signIn",
    "data":{
        "id":"00001",
        "name":"waterball"
    }
}
</code>```

and then the Server side can distinguish out the action by parsing the JSON property.

But a problem occurs, I will have lots of "if-else" descriptions like:

```<code>if ( action.equals("signIn") )
    ....
else if ( action.equals("createRoom") )
    ....
else if ( action.equals("launchGame") )
    ....
</code>```

And the program can be very unscalable and unmaintainable.

So please share your idea about what is the better way to support multiple types of action between Server/Client socket.

Thanks.

答:
I believe it is fine to use JSON is your messaging, however, in handling multiple types of actions, you might be interested in using the command design pattern.

https://www.tutorialspoint.com/design_pattern/command_pattern.htm

Body:
In short:

The main problem is, for an online game, server should support multiple types of action which client wants to do, such like: "Sign in game." , "Create a game room." , "Launch a game.", "send a chat message.", "Get a room list." ...

But if I'm going to use Socket, I'm wondering what is the best way to distinguish out the type of the action from each message received or sended between server and client.

This is what the deployment of my online game looks like:

For supporting multiple types of action, my first idea:

If I choose to use JSON, it might look like:

{
    "action":"signIn",
    "data":{
        "id":"00001",
        "name":"waterball"
    }
}

and then the Server side can distinguish out the action by parsing the JSON property.

But a problem occurs, I will have lots of "if-else" descriptions like:

if ( action.equals("signIn") )
    ....
else if ( action.equals("createRoom") )
    ....
else if ( action.equals("launchGame") )
    ....

And the program can be very unscalable and unmaintainable.

So please share your idea about what is the better way to support multiple types of action between Server/Client socket.

Thanks.


问:
Issues with integrating spring security saml 2.0 with adfs 2.0 as idp
I am trying to integrate spring security saml 2.0 with adfs 2.0 as idp. But i am getting error saying- "Response doesn't have any valid assertion which would pass subject validation ".
Please find below saml tracer output.

```<code>`<samlp:Response ID="_7a5cd6ab-f2eb-4b24-b827-01b9852ca41d"
             Version="2.0"
             IssueInstant="2017-07-04T07:09:13.497Z"
             Destination="https://example.com/saml/SSO"
             Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
             InResponseTo="a4h23ag43aca1gh951g2c322ce22102"
             xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://example.com/adfs/services/trust</Issuer>
<samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
<EncryptedAssertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
    <xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
                        xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
        <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
        <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <e:EncryptedKey xmlns:e="http://www.w3.org/2001/04/xmlenc#">
                <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p">
                    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                </e:EncryptionMethod>
                <KeyInfo>
                    <ds:X509Data xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                        <ds:X509IssuerSerial>
                            <ds:X509IssuerName>CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US</ds:X509IssuerName>
                            <ds:X509SerialNumber>352932712240095357742.......</ds:X509SerialNumber>
                        </ds:X509IssuerSerial>
                    </ds:X509Data>
                </KeyInfo>
                <e:CipherData>
                    <e:CipherValue>oLddsOeYU6cozK4XsUdiCUM55C30nV3VZaaEv/M28hjj4zq3J0ylOBAzwiSa .....</e:CipherValue>
                </e:CipherData>
            </e:EncryptedKey>
        </KeyInfo>
        <xenc:CipherData>
            <xenc:CipherValue>NUwiN6Xq2ibLA8NIlzZP5YK2W1hdGU9YeGjfvpqWiXTBGviKh/4uL6Fk8DF1 .....</xenc:CipherValue>
        </xenc:CipherData>
    </xenc:EncryptedData>
</EncryptedAssertion>
</code>```

 `

答:
I do not think ADFS 2.0 supports the SAML-P protocol. There are mainly three federated sign-in protocols used by different identity providers (such as octa, adfs) and those are: WS-Federation, SAML-P and OpenID Connect/OAuth2. People often confuse protocol with token format. WS-Federation and SAML-P protocol uses both SAML format on the tokens thus people tend to mix the two protocols.

WS-Federation is a microsoft protocol used on ADFS. Newer versions of ADFS also supports SAML-P and OpenID Connect protocol. Also see ADFS Deep-Dive: Comparing WS-Fed, SAML, and OAuth

Body:
I am trying to integrate spring security saml 2.0 with adfs 2.0 as idp. But i am getting error saying- "Response doesn't have any valid assertion which would pass subject validation ".
Please find below saml tracer output.

`<samlp:Response ID="_7a5cd6ab-f2eb-4b24-b827-01b9852ca41d"
             Version="2.0"
             IssueInstant="2017-07-04T07:09:13.497Z"
             Destination="https://example.com/saml/SSO"
             Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
             InResponseTo="a4h23ag43aca1gh951g2c322ce22102"
             xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://example.com/adfs/services/trust</Issuer>
<samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
<EncryptedAssertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
    <xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
                        xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
        <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
        <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <e:EncryptedKey xmlns:e="http://www.w3.org/2001/04/xmlenc#">
                <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p">
                    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                </e:EncryptionMethod>
                <KeyInfo>
                    <ds:X509Data xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                        <ds:X509IssuerSerial>
                            <ds:X509IssuerName>CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US</ds:X509IssuerName>
                            <ds:X509SerialNumber>352932712240095357742.......</ds:X509SerialNumber>
                        </ds:X509IssuerSerial>
                    </ds:X509Data>
                </KeyInfo>
                <e:CipherData>
                    <e:CipherValue>oLddsOeYU6cozK4XsUdiCUM55C30nV3VZaaEv/M28hjj4zq3J0ylOBAzwiSa .....</e:CipherValue>
                </e:CipherData>
            </e:EncryptedKey>
        </KeyInfo>
        <xenc:CipherData>
            <xenc:CipherValue>NUwiN6Xq2ibLA8NIlzZP5YK2W1hdGU9YeGjfvpqWiXTBGviKh/4uL6Fk8DF1 .....</xenc:CipherValue>
        </xenc:CipherData>
    </xenc:EncryptedData>
</EncryptedAssertion>

 `


答:
But a problem occurs, I will have lots of "if-else" descriptions like:

You can define an Processing interface with a process() method that accepts a JSON object (for example : javax.json.JsonObject).

Each action implements this interface.

In this way you can use a Map<String, Action> that stores the Action subclass associated to each String action.

For example to initialize the map:

```<code>Map<String, Action> actionsByName = new HashMap<>();
actionsByName.put("signIn", new SignAction());
actionsByName.put("createRoom", new CreateRoomAction());
</code>```

To handle the user action :

```<code>   String actionName = ..;
   Action action = actionsByName.get(actionName);
   action.process(jsonObject);
</code>```

Title: What is the best way to communicate between client socket and server socket which suppors multiple types of action?

Body:
But a problem occurs, I will have lots of "if-else" descriptions like:

You can define an Processing interface with a process() method that accepts a JSON object (for example : javax.json.JsonObject).

Each action implements this interface.

In this way you can use a Map<String, Action> that stores the Action subclass associated to each String action.

For example to initialize the map:

Map<String, Action> actionsByName = new HashMap<>();
actionsByName.put("signIn", new SignAction());
actionsByName.put("createRoom", new CreateRoomAction());

To handle the user action :

   String actionName = ..;
   Action action = actionsByName.get(actionName);
   action.process(jsonObject);


问:
SyntaxError: name 'cows' is assigned to before global declaration in Python3.6
I am trying to edit the global variables cows and bulls inside a loop but getting this error "SyntaxError: name 'cows' is assigned to before global declaration"

```<code>import random

random_no = random.sample(range(0, 10), 4)
cows = 0
bulls = 0
#random_num = ','.join(map(str, random_no))
print(random_no)
user_input = input("Guess the no: ")
for index, num in enumerate(random_no):
    global cows, bulls
    print(index, num)
    if user_input[index] == num:
        cows += 1
    elif user_input[index] in random_no:
        bulls += 1

print(f'{cows} cows and {bulls} bulls')
</code>```

答:
Python has no block scoping, only functions and classes introduce a new scope.

Because you have no function here, there is no need to use a global statement, cows and bulls are already globals.

You have other issues too:

input() returns a string, always.

Indexing works on strings (you get individual characters), are you sure you wanted that?

user_input[index] == num is always going to be false; '1' == 1 tests if two different types of objects are equal; they are not.

user_input[index] in random_no is also always going to be false, your random_no list contains only integers, no strings.

If the user is to enter one random number, convert the input() to an integer, and don't bother with enumerate():

```<code>user_input = int(input("Guess the no: "))
for num in random_no:
    if user_input == num:
        cows += 1
    elif user_input in random_no:
        bulls += 1
</code>```

Body:
I am trying to edit the global variables cows and bulls inside a loop but getting this error "SyntaxError: name 'cows' is assigned to before global declaration"

import random

random_no = random.sample(range(0, 10), 4)
cows = 0
bulls = 0
#random_num = ','.join(map(str, random_no))
print(random_no)
user_input = input("Guess the no: ")
for index, num in enumerate(random_no):
    global cows, bulls
    print(index, num)
    if user_input[index] == num:
        cows += 1
    elif user_input[index] in random_no:
        bulls += 1

print(f'{cows} cows and {bulls} bulls')

Body:
Python has no block scoping, only functions and classes introduce a new scope.

Because you have no function here, there is no need to use a global statement, cows and bulls are already globals.

You have other issues too:

input() returns a string, always.

Indexing works on strings (you get individual characters), are you sure you wanted that?

user_input[index] == num is always going to be false; '1' == 1 tests if two different types of objects are equal; they are not.

user_input[index] in random_no is also always going to be false, your random_no list contains only integers, no strings.

If the user is to enter one random number, convert the input() to an integer, and don't bother with enumerate():

user_input = int(input("Guess the no: "))
for num in random_no:
    if user_input == num:
        cows += 1
    elif user_input in random_no:
        bulls += 1


答:
Since you've got an HTML table, use html_table to extract it to a data.frame. You'll need fill = TRUE, because the table has extra empty rows inserted between each entry, which you can easily drop afterwards with tidyr::drop_na.

library(tidyverse)
library(rvest)

page <- 'https://www.congress.gov/help/field-values/member-bioguide-ids' %>%
    read_html()

members <- page %>%
    html_node('table') %>%
    html_table(fill = TRUE) %>%
    set_names('member', 'bioguide') %>%
    drop_na(member) %>%    # remove empty rows inserted in the table
    tbl_df()    # for printing

members
#> # A tibble: 2,243 x 2
#>                                             member bioguide
#>  *                                           <chr>    <chr>
#>  1       Abdnor, James (Republican - South Dakota)  A000009
#>  2         Abercrombie, Neil (Democratic - Hawaii)  A000014
#>  3     Abourezk, James (Democratic - South Dakota)  A000017
#>  4     Abraham, Ralph Lee (Republican - Louisiana)  A000374
#>  5        Abraham, Spencer (Republican - Michigan)  A000355
#>  6         Abzug, Bella S. (Democratic - New York)  A000018
#>  7 Acevedo-Vila, Anibal (Democratic - Puerto Rico)  A000359
#>  8       Ackerman, Gary L. (Democratic - New York)  A000022
#>  9    Adams, Alma S. (Democratic - North Carolina)  A000370
#> 10          Adams, Brock (Democratic - Washington)  A000031
#> # ... with 2,233 more rows
```

The member column could be further extracted, if you like.

There are also many other useful sources for this data, some of which correlate it with other useful variables. This one is well-structured and updated regularly.

Title: Creating a dataframe from a scraped character vector

Body:
I am trying to create a dataframe that has the columns: First name, Last name, Party, State, Member ID. Here is my code

library('rvest')

candidate_url <- 'https://www.congress.gov/help/field-values/member-bioguide-ids'
candidate_page <- read_html(candidate_url)
candidate_nodes <- html_nodes(candidate_page, 'table')
candidate_list <- html_text(candidate_nodes)

My main issue is getting the member IDs. An example ID is A000009. When I use the gsub function I lose the leading A in this example. The A is from this candidate's last name (Abercrombie), but I do not know how to add the A back into the member ID. Of course if there's a better way I am open to any suggestions.

Body:
Since you've got an HTML table, use html_table to extract it to a data.frame. You'll need fill = TRUE, because the table has extra empty rows inserted between each entry, which you can easily drop afterwards with tidyr::drop_na.

library(tidyverse)
library(rvest)

page <- 'https://www.congress.gov/help/field-values/member-bioguide-ids' %>%
    read_html()

members <- page %>%
    html_node('table') %>%
    html_table(fill = TRUE) %>%
    set_names('member', 'bioguide') %>%
    drop_na(member) %>%    # remove empty rows inserted in the table
    tbl_df()    # for printing

members
#> # A tibble: 2,243 x 2
#>                                             member bioguide
#>  *                                           <chr>    <chr>
#>  1       Abdnor, James (Republican - South Dakota)  A000009
#>  2         Abercrombie, Neil (Democratic - Hawaii)  A000014
#>  3     Abourezk, James (Democratic - South Dakota)  A000017
#>  4     Abraham, Ralph Lee (Republican - Louisiana)  A000374
#>  5        Abraham, Spencer (Republican - Michigan)  A000355
#>  6         Abzug, Bella S. (Democratic - New York)  A000018
#>  7 Acevedo-Vila, Anibal (Democratic - Puerto Rico)  A000359
#>  8       Ackerman, Gary L. (Democratic - New York)  A000022
#>  9    Adams, Alma S. (Democratic - North Carolina)  A000370
#> 10          Adams, Brock (Democratic - Washington)  A000031
#> # ... with 2,233 more rows

The member column could be further extracted, if you like.

There are also many other useful sources for this data, some of which correlate it with other useful variables. This one is well-structured and updated regularly.


问:
Need help identifying type of UTF Encoding
I'm having a hard time trying to figure out the type of unicode that i need to convert to pass data for post request. Mostly would be chinese characters.

Example String:

的事故事务院治党派驻地是不是

Expected Unicode: %u7684%u4E8B%u6545%u4E8B%u52A1%u9662%u6CBB%u515A%u6D3E%u9A7B%u5730%u662F%u4E0D%u662F

Tried to encode to UTF16-BE:
%76%84%4E%8B%65%45%4E%8B%52%A1%5C%40%5C%40%95%7F%67%1F%8D%27%7B%49%5F%85%62%08%59%1A

Encoded text in UTF-16: %FF%FE%84%76%8B%4E%45%65%8B%4E%A1%52%62%96%BB%6C%5A%51%3E%6D%7B%9A%30%57%2F%66%0D%4E%2F%66

Encoded text in UTF-8: %E7%9A%84%E4%BA%8B%E6%95%85%E4%BA%8B%E5%8A%A1%E9%99%A2%E6%B2%BB%E5%85%9A%E6%B4%BE%E9%A9%BB%E5%9C%B0%E6%98%AF%E4%B8%8D%E6%98%AF

As you can see, UTF16-BE is the closest, but it only takes 2 bytes and there should be an additional %u in front of every character as shown in the expected unicode.

I've been using URLEncoder method to get the encoded text, with the standard charset encodings but it doesn't seem to return the expected unicode.

Code:

```<code>String text = "的事故事务院治党派驻地是不是";
URLEncoder.encode(text, "UTF-16BE");
</code>```

答:
As Kayaman said in a comment: Your expectation is wrong.

That is because %uNNNN is not a valid URL encoding of Unicode text. As Wikipedia says it:

There exists a non-standard encoding for Unicode characters: %uxxxx, where xxxx is a UTF-16 code unit represented as four hexadecimal digits. This behavior is not specified by any RFC and has been rejected by the W3C.

So unless your server is expected non-standard input, your expectation is wrong.

Instead, use UTF-8. As Wikipedia says it:

The generic URI syntax mandates that new URI schemes that provide for the representation of character data in a URI must, in effect, represent characters from the unreserved set without translation, and should convert all other characters to bytes according to UTF-8, and then percent-encode those values. This requirement was introduced in January 2005 with the publication of RFC 3986. URI schemes introduced before this date are not affected.

That is however for sending data in a URL, e.g. as part of a GET.

For sending text data as part of a application/x-www-form-urlencoded encoded POST, see the HTML5 documentation:

If the form element has an accept-charset attribute, let the selected character encoding be the result of picking an encoding for the form.

Otherwise, if the form element has no accept-charset attribute, but the document's character encoding is an ASCII-compatible character encoding, then that is the selected character encoding.

Otherwise, let the selected character encoding be UTF-8.

Since most web pages ("the document") are presented in UTF-8 these days, that would likely mean UTF-8.

Body:
I'm having a hard time trying to figure out the type of unicode that i need to convert to pass data for post request. Mostly would be chinese characters.

Example String:

的事故事务院治党派驻地是不是

Expected Unicode: %u7684%u4E8B%u6545%u4E8B%u52A1%u9662%u6CBB%u515A%u6D3E%u9A7B%u5730%u662F%u4E0D%u662F

Tried to encode to UTF16-BE:
%76%84%4E%8B%65%45%4E%8B%52%A1%5C%40%5C%40%95%7F%67%1F%8D%27%7B%49%5F%85%62%08%59%1A

Encoded text in UTF-16: %FF%FE%84%76%8B%4E%45%65%8B%4E%A1%52%62%96%BB%6C%5A%51%3E%6D%7B%9A%30%57%2F%66%0D%4E%2F%66

Encoded text in UTF-8: %E7%9A%84%E4%BA%8B%E6%95%85%E4%BA%8B%E5%8A%A1%E9%99%A2%E6%B2%BB%E5%85%9A%E6%B4%BE%E9%A9%BB%E5%9C%B0%E6%98%AF%E4%B8%8D%E6%98%AF

As you can see, UTF16-BE is the closest, but it only takes 2 bytes and there should be an additional %u in front of every character as shown in the expected unicode.

I've been using URLEncoder method to get the encoded text, with the standard charset encodings but it doesn't seem to return the expected unicode.

Code:

String text = "的事故事务院治党派驻地是不是";
URLEncoder.encode(text, "UTF-16BE");


问:
null in console after submit button in router.post
This here is my form where i'm trying to redirect the page to home after hitting the submit button! res.redirect('/home') is not working so I have tried to do that with console.log("testing"); and for some reason that is not working as well! What am I missing?

答:
1)Consider using form's onsubmit method instead of button's onclick. Just because it's made for that purpose. 2)There are alot of code but redirect is nowhere to be found. 3)There is no reason to redirect on client on submitting the form. Just none. You should submit it to the server, receive the data, and then redirect, if you want.

```<code>router.get('/home', function(req, res) {
    //do something
});

router.post('/contact/send', function(req, res){
    console.log("testingggg");
    res.redirect('/home');
});
</code>```

Also, dont name your API '/contact/send', just '/contact' is enough.

Body:
1)Consider using form's onsubmit method instead of button's onclick. Just because it's made for that purpose. 2)There are alot of code but redirect is nowhere to be found. 3)There is no reason to redirect on client on submitting the form. Just none. You should submit it to the server, receive the data, and then redirect, if you want.

router.get('/home', function(req, res) {
    //do something
});

router.post('/contact/send', function(req, res){
    console.log("testingggg");
    res.redirect('/home');
});

Also, dont name your API '/contact/send', just '/contact' is enough.


问:
Convert function PHP to C#
I am stuck in a convertion of PHP function to C#!

Someone can tell me what I am doing bad?

Original code (PHP):

```<code>function delete_all_between($beginning, $end, $string)
{
    $beginningPos = strpos($string, $beginning);
    $endPos = strpos($string, $end);
    if ($beginningPos === false || $endPos === false) {
        return $string;
    }

    $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

    return str_replace($textToDelete, '', $string);
}
</code>```

My code C#:

```<code>string delete_all_between(string beginning, string end, string html)
{
    int beginningPos = html.IndexOf(beginning);
    int endPos = html.IndexOf(end);
    if (beginningPos == -1 || endPos == -1)
    {
        return html;
    }
}
</code>```

I hope someone can help me, I am really stuck!

答:
Use Substring and Replace to mask out and replace the unwanted string. Also, I would add a check to make sure that endPos > beginningPos:

```<code>string delete_all_between(string beginningstring, string endstring, string html)
{
    int beginningPos = html.IndexOf(beginningstring);
    int endPos = html.IndexOf(endstring);
    if (beginningPos != -1 && endPos != -1 && endPos > beginningPos)
    {
        string textToDelete = html.Substring(beginningPos, (endPos - beginningPos) + endstring.Length); //mask out
        string newHtml = html.Replace(textToDelete, ""); //replace mask with empty string
        return newHtml; //return result
    }
    else return html;
}
</code>```

Test with input

```<code>delete_all_between("hello", "bye", "Some text hello remove this byethat I wrote")
</code>```

Yields the result:

Some text that I wrote

Title: Convert function PHP to C#

Body:
I am stuck in a convertion of PHP function to C#!

Someone can tell me what I am doing bad?

Original code (PHP):

function delete_all_between($beginning, $end, $string)
{
    $beginningPos = strpos($string, $beginning);
    $endPos = strpos($string, $end);
    if ($beginningPos === false || $endPos === false) {
        return $string;
    }

    $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

    return str_replace($textToDelete, '', $string);
}

My code C#:

string delete_all_between(string beginning, string end, string html)
{
    int beginningPos = html.IndexOf(beginning);
    int endPos = html.IndexOf(end);
    if (beginningPos == -1 || endPos == -1)
    {
        return html;
    }
}

I hope someone can help me, I am really stuck!

Body:
Use Substring and Replace to mask out and replace the unwanted string. Also, I would add a check to make sure that endPos > beginningPos:

string delete_all_between(string beginningstring, string endstring, string html)
{
    int beginningPos = html.IndexOf(beginningstring);
    int endPos = html.IndexOf(endstring);
    if (beginningPos != -1 && endPos != -1 && endPos > beginningPos)
    {
        string textToDelete = html.Substring(beginningPos, (endPos - beginningPos) + endstring.Length); //mask out
        string newHtml = html.Replace(textToDelete, ""); //replace mask with empty string
        return newHtml; //return result
    }
    else return html;
}

Test with input

delete_all_between("hello", "bye", "Some text hello remove this byethat I wrote")

Yields the result:

Some text that I wrote


问:
The type 'UserControl' does not support direct content
I have an Outlook 2013 and 2016 VSTO Add-in project and am trying to add a WPF user control to a custom task pane as described here.

The problem I have is when I add the User Control (WPF) it generates me a WPF control with a grid, but automatically throws an error of "The type 'UserControl' does not support direct content".

WPF generated:

```<code><UserControl x:Class="TestNamespace.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:TestNamespace"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>

</Grid>
</UserControl>
</code>```

I know in the past I have had to add the WPF project type guid to the .proj file to get some things to work, but adding this made no difference (in fact it would not even load when in a certain order).

Original:

```<code><ProjectTypeGuids>{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</code>```

Crashes:

```<code><ProjectTypeGuids>{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</code>```

Doesn't crash, but doesn't fix the error:

```<code><ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</code>```

Can anyone point me in the right direction?

UPDATE

I tried creating a new class library project straight out of the box, added a WPF user control, then added the reference to System.Xaml and I have the same issue.

答: Just remove System.Xaml, then add it again.

Body:
I have an Outlook 2013 and 2016 VSTO Add-in project and am trying to add a WPF user control to a custom task pane as described here.

The problem I have is when I add the User Control (WPF) it generates me a WPF control with a grid, but automatically throws an error of "The type 'UserControl' does not support direct content".

WPF generated:

<UserControl x:Class="TestNamespace.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:TestNamespace"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>

</Grid>
</UserControl>

I know in the past I have had to add the WPF project type guid to the .proj file to get some things to work, but adding this made no difference (in fact it would not even load when in a certain order).

Original:

<ProjectTypeGuids>{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Crashes:

<ProjectTypeGuids>{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Doesn't crash, but doesn't fix the error:

<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Can anyone point me in the right direction?

UPDATE

I tried creating a new class library project straight out of the box, added a WPF user control, then added the reference to System.Xaml and I have the same issue.


问:
How do I call $resource service from controller in angularJs
This is get service function where I am calling the API

```<code>    .factory('Report', function($resource, API_URL) {
       return $resource(API_URL  +
       'security/:userId/1498780800000/listOfDeliveries', {

      userId : '@userId',
      expected : '@expected',
      arg1 : '@arg1'
    }, {
      update: {
        method: 'PUT'
      }
    });
  })
</code>```

In the app.js I have this below controller

```<code>    .controller('ReportsController', function($scope, $rootScope,
     ProfileData, $state, $timeout, Report) {

})
</code>```

答:
First of all, you need to check how angular factory & service work.

Your factory return a $resource, so read the doc about $resource

A resource "class" object with methods for the default set of resource
  actions optionally extended with custom actions. The default set
  contains these actions:

```<code>{
   'get':    {method:'GET'},
   'save':   {method:'POST'},
   'query':  {method:'GET', isArray:true},
   'remove': {method:'DELETE'},
   'delete': {method:'DELETE'}
};
</code>```

So, you can use theses methods: Report.get(), Report.save(), Report.query(), Report.remove(), Report.delete()

In addition there are custom method you defined: Report.update()

And you can pass userId as params so:

Report.get({userId: 1234}); will call a GET request to: API_URL+'security/1234/1498780800000/listOfDeliveries

(expected and args1 are not in url so I dont think you need them)

What's returning Report.get() ?

Class actions return empty instance (with additional properties below). Instance actions return promise of the action

So Report.get(...) is returning a promise, you will get data by:

```<code>Report.get(...).then(function(data) {
  $scope.requestData = data;
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is get service function where I am calling the API

    .factory('Report', function($resource, API_URL) {
       return $resource(API_URL  +
       'security/:userId/1498780800000/listOfDeliveries', {

      userId : '@userId',
      expected : '@expected',
      arg1 : '@arg1'
    }, {
      update: {
        method: 'PUT'
      }
    });
  })

In the app.js I have this below controller

    .controller('ReportsController', function($scope, $rootScope,
     ProfileData, $state, $timeout, Report) {

})

Body:
First of all, you need to check how angular factory & service work.

Your factory return a $resource, so read the doc about $resource

A resource "class" object with methods for the default set of resource
  actions optionally extended with custom actions. The default set
  contains these actions:

{
   'get':    {method:'GET'},
   'save':   {method:'POST'},
   'query':  {method:'GET', isArray:true},
   'remove': {method:'DELETE'},
   'delete': {method:'DELETE'}
};

So, you can use theses methods: Report.get(), Report.save(), Report.query(), Report.remove(), Report.delete()

In addition there are custom method you defined: Report.update()

And you can pass userId as params so:

Report.get({userId: 1234}); will call a GET request to: API_URL+'security/1234/1498780800000/listOfDeliveries

(expected and args1 are not in url so I dont think you need them)

What's returning Report.get() ?

Class actions return empty instance (with additional properties below). Instance actions return promise of the action

So Report.get(...) is returning a promise, you will get data by:

Report.get(...).then(function(data) {
  $scope.requestData = data;
});


问:
CSS: How do I stop hover effects from pushing my text?
I hope you understood the question, you can see an example here:

http://jsfiddle.net/nFbJY/

When you scroll over any of the links they move :(

Any advice on how to solve this issue?

HTML:

```<code><div class="links">
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="pricing.html">Pricing</a></li>
<li><a href="faq.html">FAQ</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</code>```

CSS:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left; margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC;          border-radius: 5px; -moz-border-radius: 5px;}
a:hover { border: 1px solid blue; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}
```

答:
Try to hover the li element instead of a

a:hover { border: 1px solid blue; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}

li:hover { background-color:yellow; }
```

Body:
I hope you understood the question, you can see an example here:

http://jsfiddle.net/nFbJY/

When you scroll over any of the links they move :(

Any advice on how to solve this issue?

HTML:

Home

Pricing

FAQ

About

Contact

CSS:

div.links {float: left; padding-top:15px;}
ul {list-style:none;}
li {float: left; margin: 0 .15em; padding: 3px 10px 3px 10px; border: 1px solid #CCC;          border-radius: 5px; -moz-border-radius: 5px;}
a:hover { border: 1px solid blue; border-radius: 5px; -moz-border-radius: 5px; padding: 3px 10px 3px 10px; background-color:yellow;}


问:
mod_expires.c cause session problems
I active mod_expires.c with this configuration :

```<code> ## EXPIRES CACHING ##
 <IfModule mod_expires.c>
 ExpiresActive On
 ExpiresByType image/jpg "access plus 1 month"
 ExpiresByType image/jpeg "access plus 1 month"
 ExpiresByType image/gif "access plus 1 month"
 ExpiresByType image/png "access plus 1 month"
 ExpiresByType text/css "access plus 1 year"
 ExpiresByType appliction/x-javascript "access plus 1 year"
 ExpiresByType text/javascript "access plus 1 year"
 ExpiresByType application/javascript "access plus 1 year"
 ExpiresByType application/pdf "access plus 1 week"
 ExpiresByType application/x-shockwave-flash "access plus 1 month"
 ExpiresByType image/x-icon "access plus 1 year"
 ExpiresDefault "access plus 1 day"
 </IfModule>
 ## EXPIRES CACHING ##
</code>```

It works very well, everything is catched fine. However, since its active some customer told me they got another account from another customer when they log in. I can't reproduce the bug in my pc login works perfectly fine.

anyone get a clue ? Thanks

答:
Try this at the end of your .htaccess: </p>

```<code><filesMatch "\.(php)$">
  ExpiresActive Off
</filesMatch>
</code>```

Title: mod_expires.c cause session problems

Body:
I active mod_expires.c with this configuration :

 ## EXPIRES CACHING ##
 <IfModule mod_expires.c>
 ExpiresActive On
 ExpiresByType image/jpg "access plus 1 month"
 ExpiresByType image/jpeg "access plus 1 month"
 ExpiresByType image/gif "access plus 1 month"
 ExpiresByType image/png "access plus 1 month"
 ExpiresByType text/css "access plus 1 year"
 ExpiresByType appliction/x-javascript "access plus 1 year"
 ExpiresByType text/javascript "access plus 1 year"
 ExpiresByType application/javascript "access plus 1 year"
 ExpiresByType application/pdf "access plus 1 week"
 ExpiresByType application/x-shockwave-flash "access plus 1 month"
 ExpiresByType image/x-icon "access plus 1 year"
 ExpiresDefault "access plus 1 day"
 </IfModule>
 ## EXPIRES CACHING ##

It works very well, everything is catched fine. However, since its active some customer told me they got another account from another customer when they log in. I can't reproduce the bug in my pc login works perfectly fine.

anyone get a clue ? Thanks

Body:
Try this at the end of your .htaccess:

<filesMatch "\.(php)$">
  ExpiresActive Off
</filesMatch>


问:
sed & protobuf: need to delete dots
I need to delete dots using sed, but not all dots.

```<code>- repeated .CBroadcast_GetBroadcastChatUserNames_Response.PersonaName persona_names = 1
+ repeated CBroadcast_GetBroadcastChatUserNames_Response.PersonaName persona_names = 1
</code>```

Here the dot after repeated, (repeated also can beoptional | required | extend) should be deleted

```<code>- rpc NotifyBroadcastViewerState (.CBroadcast_BroadcastViewerState_Notification) returns (.NoResponse)
+ rpc NotifyBroadcastViewerState (CBroadcast_BroadcastViewerState_Notification) returns (NoResponse)
</code>```

And here delete dot after (

It should work on multiple files with different content.

Full code can be found here

答:
A perhaps simpler solution (works with both GNU sed and BSD/macOS sed):

```<code>sed -E 's/([[:space:][:punct:]])\./\1/g' file
</code>```

In case a . can also appear as the first character on a line, use the following varation:

sed -E 's/(^|[[:space:][:punct:]])\./\1/g' file

The assumption is that any . preceded by:

a whitespace character (character class [:space:])

as in:  .

or a punctuation character (character class [:punct:])

as in: (.

should be removed, by replacing the matched sequence with just the character preceding the ., captured via subexpression (...) in the regular expression, and referenced in the replacement string with \1 (the first capture group).

If you invert the logic, you can try the simpler:

```<code>sed -E 's/([^[:alnum:]])\./\1/g' file
</code>```

In case a . can also appear as the first character on a line:

sed -E 's/(^|[^[:alnum:]])\./\1/g' file

This replaces all periods that are not (^) preceded by an alphanumeric character (a letter or digit).

Title: sed & protobuf: need to delete dots

Body:
I need to delete dots using sed, but not all dots.

- repeated .CBroadcast_GetBroadcastChatUserNames_Response.PersonaName persona_names = 1
+ repeated CBroadcast_GetBroadcastChatUserNames_Response.PersonaName persona_names = 1

Here the dot after repeated, (repeated also can beoptional | required | extend) should be deleted

- rpc NotifyBroadcastViewerState (.CBroadcast_BroadcastViewerState_Notification) returns (.NoResponse)
+ rpc NotifyBroadcastViewerState (CBroadcast_BroadcastViewerState_Notification) returns (NoResponse)

And here delete dot after (

It should work on multiple files with different content.

Full code can be found here

Body:
A perhaps simpler solution (works with both GNU sed and BSD/macOS sed):

sed -E 's/([[:space:][:punct:]])\./\1/g' file

In case a . can also appear as the first character on a line, use the following varation:

sed -E 's/(^|[[:space:][:punct:]])\./\1/g' file

The assumption is that any . preceded by:

a whitespace character (character class [:space:])

as in:  .

or a punctuation character (character class [:punct:])

as in: (.

should be removed, by replacing the matched sequence with just the character preceding the ., captured via subexpression (...) in the regular expression, and referenced in the replacement string with \1 (the first capture group).

If you invert the logic, you can try the simpler:

sed -E 's/([^[:alnum:]])\./\1/g' file

In case a . can also appear as the first character on a line:

sed -E 's/(^|[^[:alnum:]])\./\1/g' file

This replaces all periods that are not (^) preceded by an alphanumeric character (a letter or digit).


问:
Creating and returning Observable from Angular 2 Service
This is more of a "best practices" question. There are three players: a Component, a Service and a Model. The Component is calling the Service to get data from a database. The Service is using:

this.people = http.get('api/people.json').map(res => res.json());
```

<p>to return an <code>Observable</code>.</p>

<p>The <code>Component</code> could just subscribe to the <code>Observable</code>:</p>

<pre class="lang-js prettyprint-override"><code>    peopleService.people
        .subscribe(people => this.people = people);
      }
</code>```

However, what I really want is for the Service to return an Array of Model objects that was created from the data that the Service retrieved from the database. I realized that the Component could just create this array in the subscribe method, but I think it would be cleaner if the service do that and make it available to the Component.

How can the Service create a new Observable, containing that array, and return that?

答:
In the service.ts file -

a. import 'of' from observable/of

 b. create a json list

 c. return json object using Observable.of()

    Ex. -

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class ClientListService {
    private clientList;

    constructor() {
        this.clientList = [
            {name: 'abc', address: 'Railpar'},
            {name: 'def', address: 'Railpar 2'},
            {name: 'ghi', address: 'Panagarh'},
            {name: 'jkl', address: 'Panagarh 2'},
        ];
    }

    getClientList () {
        return Observable.of(this.clientList);
    }
};
</code>```

In the component where we are calling the get function of the service -

```<code>this.clientListService.getClientList().subscribe(res => this.clientList = res);
</code>```

Body:
This is more of a "best practices" question. There are three players: a Component, a Service and a Model. The Component is calling the Service to get data from a database. The Service is using:

this.people = http.get('api/people.json').map(res => res.json());

to return an Observable.

The Component could just subscribe to the Observable:

    peopleService.people
        .subscribe(people => this.people = people);
      }

However, what I really want is for the Service to return an Array of Model objects that was created from the data that the Service retrieved from the database. I realized that the Component could just create this array in the subscribe method, but I think it would be cleaner if the service do that and make it available to the Component.

How can the Service create a new Observable, containing that array, and return that?

Body:
In the service.ts file -

a. import 'of' from observable/of

 b. create a json list

 c. return json object using Observable.of()

    Ex. -

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class ClientListService {
    private clientList;

    constructor() {
        this.clientList = [
            {name: 'abc', address: 'Railpar'},
            {name: 'def', address: 'Railpar 2'},
            {name: 'ghi', address: 'Panagarh'},
            {name: 'jkl', address: 'Panagarh 2'},
        ];
    }

    getClientList () {
        return Observable.of(this.clientList);
    }
};

In the component where we are calling the get function of the service -

this.clientListService.getClientList().subscribe(res => this.clientList = res);


问:
res.download(NodeJS) not triggering a download on the browser
I've been struggling with this for a while and can't seem to find an answer, I'm developing a website with a budgeting option, I'm sending an object from the client to the server, and that server is using PDFKit to create a PDF version of the budget, once it's created I want to actually send back that PDF to the client and trigger a download, this is what I've done

Client-side code:

```<code>let data = {
  nombre: this.state.name,
  email: this.state.email,
  telefono: this.state.phone,
  carrito: this.props.budget.cart,
  subTotal: this.props.budget.subTotal,
  IVA: this.props.budget.tax,
  total: this.props.budget.subTotal + this.props.budget.tax
}
  axios({
    method: 'post',
    url: 'http://localhost:1337/api/budget',
    data: data
  })
    .then((response) => {
      console.log('This is the response', response);
      window.open('/download')
    })
    .catch((error) => {
      alert(error);
    })
</code>```

So that data goes to my server-side code perfectly and it looks like this

```<code>const pdf = require('pdfkit');
const fs = require('fs');
const path = require('path');

exports.makePDFBudget = (req, res) => {
  let myDoc = new pdf;
  myDoc.pipe(fs.createWriteStream(`PDFkit/budget.pdf`));
  myDoc.font('Times-Roman')
       .fontSize(12)
       .text(`${req.body.name} ${req.body.phone} ${req.body.email} ${req.body.cart} ${req.body.subTotal} ${req.body.total} ${req.body.tax}`);
  myDoc.end()
}
</code>```

That's creating my PDF, what I want now is that once it's created and the response is sent back to the client, the client opens a new window with the URL "/download" which is set to download that PDF, but that's not happening for some reason, it opens up the new window but the download never starts and it throws absolutely no error I'm my Node console or browser console
this is how I send my file to the client

```<code>const fs = require('fs');
const path = require('path');

exports.downloadPDFBudget = (req, res) => {
  res.download(__dirname + 'budget.pdf', 'budget.pdf');
}
</code>```

And this is how my server index looks like

```<code>const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const api = express.Router();
const { makePDFBudget } = require('./PDFkit/makePDFBudget.js');
const { downloadPDFBudget } = require('./PDFkit/downloadPDFBudget.js')

app.use(express.static(__dirname + '/../public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));

api.route('/budget')
  .post(makePDFBudget)

api.route('/download')
  .get(downloadPDFBudget)

app.use('/api', api);

const port = 1337;

app.listen(port);

console.log('Listening on port ', port);

module.exports = app;
</code>```

答: I just solved it, the port in which I was running my client obviously was different from the one I was running my server, so I had to open a window to my server's port to trigger the download, I realized this because I threw a console log on the function that was supposed to do the res.download it wasn't showing up. Thanks!</p>

Body:
I've been struggling with this for a while and can't seem to find an answer, I'm developing a website with a budgeting option, I'm sending an object from the client to the server, and that server is using PDFKit to create a PDF version of the budget, once it's created I want to actually send back that PDF to the client and trigger a download, this is what I've done

Client-side code:

let data = {
  nombre: this.state.name,
  email: this.state.email,
  telefono: this.state.phone,
  carrito: this.props.budget.cart,
  subTotal: this.props.budget.subTotal,
  IVA: this.props.budget.tax,
  total: this.props.budget.subTotal + this.props.budget.tax
}
  axios({
    method: 'post',
    url: 'http://localhost:1337/api/budget',
    data: data
  })
    .then((response) => {
      console.log('This is the response', response);
      window.open('/download')
    })
    .catch((error) => {
      alert(error);
    })

So that data goes to my server-side code perfectly and it looks like this

const pdf = require('pdfkit');
const fs = require('fs');
const path = require('path');

exports.makePDFBudget = (req, res) => {
  let myDoc = new pdf;
  myDoc.pipe(fs.createWriteStream(`PDFkit/budget.pdf`));
  myDoc.font('Times-Roman')
       .fontSize(12)
       .text(`${req.body.name} ${req.body.phone} ${req.body.email} ${req.body.cart} ${req.body.subTotal} ${req.body.total} ${req.body.tax}`);
  myDoc.end()
}

That's creating my PDF, what I want now is that once it's created and the response is sent back to the client, the client opens a new window with the URL "/download" which is set to download that PDF, but that's not happening for some reason, it opens up the new window but the download never starts and it throws absolutely no error I'm my Node console or browser console
this is how I send my file to the client

const fs = require('fs');
const path = require('path');

exports.downloadPDFBudget = (req, res) => {
  res.download(__dirname + 'budget.pdf', 'budget.pdf');
}

And this is how my server index looks like

const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const api = express.Router();
const { makePDFBudget } = require('./PDFkit/makePDFBudget.js');
const { downloadPDFBudget } = require('./PDFkit/downloadPDFBudget.js')

app.use(express.static(__dirname + '/../public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));

api.route('/budget')
  .post(makePDFBudget)

api.route('/download')
  .get(downloadPDFBudget)

app.use('/api', api);

const port = 1337;

app.listen(port);

console.log('Listening on port ', port);

module.exports = app;