问:
Convert from .gql to json or csv
How to convert gql file (grakn) to json or csv?
I read the documentation provided by grakn.ai and there are only detailed explanation of how to convert different file formats to gql provided.

Here: https://grakn.ai/pages/documentation/migration/migration-overview.html

is explained how to do it:

Exporting Data from Grakn
It is also possible to export data from Grakn using the migration shell script. Usage is as follows:

```<code>    usage: graql migrate export -data -schema [-help] [-no] [-batch <arg>] [-uri <arg>] [-keyspace <arg>]
     -data                 export data
     -schema               export schema
     -h,--help             print usage message
     -k,--keyspace <arg>   keyspace to use
     -n,--no               dry run- write to standard out
     -u,--uri <arg>        uri to engine endpoint
     -r, --retry           Number of times to retry sending tasks if engine is not available
     -d,--debug            Migration immediatly stops if any transaction fails
</code>```

Exporting data or the schema from Grakn, into Graql, will always redirect to standard out.

But I'm afraid, I don't understand how to use it.

答:
I am afraid you can't export from Grakn into other data formats. The export function is exclusively designed to export your data and schema into a graql file so you can more easily transfer it to another running instance of Grakn.

Something similar to getting a SQL dump from a SQL database.

You can export your schema with the following command:

```<code>graql migrate export -schema -keyspace mykeyspace
</code>```

and your data with this

```<code>graql migrate export -data -keyspace mykeyspace
</code>```

where mykeyspace is the name of your keyspace

Title: Convert from .gql to json or csv

Body:
How to convert gql file (grakn) to json or csv?
I read the documentation provided by grakn.ai and there are only detailed explanation of how to convert different file formats to gql provided.

Here: https://grakn.ai/pages/documentation/migration/migration-overview.html

is explained how to do it:

Exporting Data from Grakn
It is also possible to export data from Grakn using the migration shell script. Usage is as follows:

    usage: graql migrate export -data -schema [-help] [-no] [-batch <arg>] [-uri <arg>] [-keyspace <arg>]
     -data                 export data
     -schema               export schema
     -h,--help             print usage message
     -k,--keyspace <arg>   keyspace to use
     -n,--no               dry run- write to standard out
     -u,--uri <arg>        uri to engine endpoint
     -r, --retry           Number of times to retry sending tasks if engine is not available
     -d,--debug            Migration immediatly stops if any transaction fails

Exporting data or the schema from Grakn, into Graql, will always redirect to standard out.

But I'm afraid, I don't understand how to use it.

Body:
I am afraid you can't export from Grakn into other data formats. The export function is exclusively designed to export your data and schema into a graql file so you can more easily transfer it to another running instance of Grakn.

Something similar to getting a SQL dump from a SQL database.

You can export your schema with the following command:

graql migrate export -schema -keyspace mykeyspace

and your data with this

graql migrate export -data -keyspace mykeyspace

where mykeyspace is the name of your keyspace


来源: stackexchange

问:
How to have 2 rect overlap in d3 to make progress bar?
I am trying to make a progress bar using d3, I am able to make the bar chart

But I want to have the range overlap under the bar like this

Here is my d3 code

```<code>var my_values = [
    { name: 'London', cost: 8674000},
    { name: 'New York', cost: 8406000},
    { name: 'Sydney', cost: 4293000},
    { name: 'Paris', cost: 2244000},
    { name: 'Beijing', cost: 11510000}
];

d3.selectAll('rect')
.data(my_values)
.attr('height', 5)
.attr('width', function(d) {
    var scaleFactor = 0.00004;
    return d.cost * scaleFactor;
})
.attr('y', function(d, i) {
  return i * 20;
})
</code>```

Is there a way to make the range of the bar show under each rect so that the user can eye ball what is the relative percentage base on the position of the bar?

Edit:

I want to know how to create just the bar, here is the bar with text omitted

答:
First of all: use a scale to create your bars based on your data. Using a proper scale the issue here is easy to solve:

Create the background bars using the maximum of the scale's domain:

```<code>.attr("width", function(d) {
    return scale(scale.domain()[1])
})
</code>```

Then, over that elements, create the real bars, using the data:

```<code>.attr("width", function(d) {
    return scale(d.cost)
})
</code>```

For creating the overlap give the real bars the same x, y and height attributes of the background bars. But they have to be painted after the background: in an SVG, whoever is painted later remains on top.

Here is a demo:

var my_values = [{
  name: 'London',
  cost: 8674000
}, {
  name: 'New York',
  cost: 8406000
}, {
  name: 'Sydney',
  cost: 4293000
}, {
  name: 'Paris',
  cost: 2244000
}, {
  name: 'Beijing',
  cost: 11510000
}];

var svg = d3.select("svg");

var scale = d3.scaleLinear()
  .domain([0, 12000000])
  .range([0, 480]);

var background = svg.selectAll(null)
  .data(my_values)
  .enter()
  .append("rect")
  .attr("x", 10)
  .attr("y", function(d, i) {
    return 10 + i * 20
  })
  .attr("height", 10)
  .attr("width", function(d) {
    return scale(scale.domain()[1])
  })
  .attr("rx", 5)
  .attr("ry", 5)
  .style("fill", "#ddd");

var bars = svg.selectAll(null)
  .data(my_values)
  .enter()
  .append("rect")
  .attr("x", 10)
  .attr("y", function(d, i) {
    return 10 + i * 20
  })
  .attr("height", 10)
  .attr("width", function(d) {
    return scale(d.cost)
  })
  .attr("rx", 5)
  .attr("ry", 5)
  .style("fill", "#666");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="200"></svg></code>```

PS: If you want to remove the round corners in the right hand side of the bars you have some options: creating paths instead of bars or creating small bars on top of the real ones to cover the round corners, for instance. The problem is that, in an SVG rect, you cannot choose what corner will be round: rx and ry apply to all corners.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a progress bar using d3, I am able to make the bar chart

But I want to have the range overlap under the bar like this

Here is my d3 code

var my_values = [
    { name: 'London', cost: 8674000},
    { name: 'New York', cost: 8406000},
    { name: 'Sydney', cost: 4293000},
    { name: 'Paris', cost: 2244000},
    { name: 'Beijing', cost: 11510000}
];

d3.selectAll('rect')
.data(my_values)
.attr('height', 5)
.attr('width', function(d) {
    var scaleFactor = 0.00004;
    return d.cost * scaleFactor;
})
.attr('y', function(d, i) {
  return i * 20;
})

Is there a way to make the range of the bar show under each rect so that the user can eye ball what is the relative percentage base on the position of the bar?

Edit:

I want to know how to create just the bar, here is the bar with text omitted

Body:
First of all: use a scale to create your bars based on your data. Using a proper scale the issue here is easy to solve:

Create the background bars using the maximum of the scale's domain:

.attr("width", function(d) {
    return scale(scale.domain()[1])
})

Then, over that elements, create the real bars, using the data:

.attr("width", function(d) {
    return scale(d.cost)
})

For creating the overlap give the real bars the same x, y and height attributes of the background bars. But they have to be painted after the background: in an SVG, whoever is painted later remains on top.

Here is a demo:

var my_values = [{
  name: 'London',
  cost: 8674000
}, {
  name: 'New York',
  cost: 8406000
}, {
  name: 'Sydney',
  cost: 4293000
}, {
  name: 'Paris',
  cost: 2244000
}, {
  name: 'Beijing',
  cost: 11510000
}];

var svg = d3.select("svg");

var scale = d3.scaleLinear()
  .domain([0, 12000000])
  .range([0, 480]);

var background = svg.selectAll(null)
  .data(my_values)
  .enter()
  .append("rect")
  .attr("x", 10)
  .attr("y", function(d, i) {
    return 10 + i * 20
  })
  .attr("height", 10)
  .attr("width", function(d) {
    return scale(scale.domain()[1])
  })
  .attr("rx", 5)
  .attr("ry", 5)
  .style("fill", "#ddd");

var bars = svg.selectAll(null)
  .data(my_values)
  .enter()
  .append("rect")
  .attr("x", 10)
  .attr("y", function(d, i) {
    return 10 + i * 20
  })
  .attr("height", 10)
  .attr("width", function(d) {
    return scale(d.cost)
  })
  .attr("rx", 5)
  .attr("ry", 5)
  .style("fill", "#666");

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="200"></svg>

PS: If you want to remove the round corners in the right hand side of the bars you have some options: creating paths instead of bars or creating small bars on top of the real ones to cover the round corners, for instance. The problem is that, in an SVG rect, you cannot choose what corner will be round: rx and ry apply to all corners.


问:
How to programatically create a Facebook application via JS SDK or Open Graph API? (createApplication)
I know there are currently two methods that can be used to do this, documented (poorly) on Facebook's Developer site:

The old (depreciated) JavaScript SDK FB.Connect.createApplication

A new FBJS method Facebook.createApplication (only for use on Canvas pages)

The problem is that I not using a Canvas app that runs FBJS, and I am not using the OLD JS SKD. I am trying to do this on a regular old PHP website that uses the current JavaScript SDK and the PHP SDK.

I am doing the usual Open Graph API calls and such with the current SDK, so I understand the basics, I'm just not sure how to proceed to use the OLD SDK, or if (fingers crossed) I even really have to?

So, is there a way to make new Facebook Apps with the current JS SDK? Or with a server side PHP SDK call to the Graph?

And if not, how do I call the old SDK to do this?

Thanks

UPDATE: You still can't do this, but there is an official bug in the Facebook tracker about it: http://developers.facebook.com/bugs/295627350461318

答:
There isn't outside of the OLD SDK as you indicated. It's been removed (what Facebook calls "deprecated"). I put in a feature request recently for them to add it back into the API:

Me:

The Facebook Developer tool is
considerably lacking in features. We'd
like to be able to create a third
party application that adds layers of
functionality to the developer
application, but we'd need to be able
to create and administer applications
via the Graph API.

The Graph API supports querying for
information on existing applications.
To create, administer or delete
applications developers must go to the
Developer Application.

Them:

------- Comment #1 From Jeff Bowen 2010-12-07 16:59:12 (-) [reply]

------- Thanks for the request. We’ll track this on our wishlist

ContentLicense: CC BY-SA 2.5


问:
Arrays and C syntax
I have some code that isn't compiling, and I have been wracking my brain to fix it, I'm just a beginner programmer, and I feel like I have my fundamentals down, but for some reason I am getting errors like I forgot to put a semicolon and stuff, not sure why, or where that is, so if someone would be willing to proofread my work it would be greatly appreciated.

The errors appear to be occurring at the end of each statement in the main program, and error codes indicate I am forgetting a semicolon but I think I have them all so I don't quite understand my error.

```<code>    #include <stdio.h>
    #include <stdlib.h>

    void printArrayValues(int array[], int num);

    void fillWithIndex(int array[], int num);

    int main(int argc, char * argv[])
    {
        int arr1[] = { 23, 21, 20, 27 };
        int arr2[] = { 5, 7, 9, 11, 13 };

            // Print the values in the first array, fill that array with
            // its indexes, and then print the values of the array
            // again.

            printArrayValues(arr1[], 4);
            fillWithIndex(arr1[], 4);
            printArrayValues(arr1[], 4);

            // Do similarly for the second array.

            printArrayValues(arr2[], 5);
            fillWithIndex(arr2[], 5);
            printArrayValues(arr2[], 5);

            return 0;
    }

    void printArrayValues(int array[], int num)

    {
        int i = 0;

        while (i < num)
        {
            printf("%d\n", array[i]);
            i++;
        }

        return;
    }

    void fillWithIndex(int array[], int num)
    {
        int i = 0;

        while (i < num)
        {
            array[i] = i;
            i++;
        }

        return;
    }
</code>```

答:
1.While you are calling the function from main() don't use [] to array.
2.As you are not getting values in command line then use only int main()

i.e.

```<code>int main()
    {
        int arr1[] = { 23, 21, 20, 27 };
        int arr2[] = { 5, 7, 9, 11, 13 };

            // Print the values in the first array, fill that array with
            // its indexes, and then print the values of the array
            // again.

            printArrayValues(arr1, 4);
            fillWithIndex(arr1, 4);
            printArrayValues(arr1, 4);

            // Do similarly for the second array.

            printArrayValues(arr2, 5);
            fillWithIndex(arr2, 5);
            printArrayValues(arr2, 5);

            return 0;
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Arrays and C syntax

Body:
I have some code that isn't compiling, and I have been wracking my brain to fix it, I'm just a beginner programmer, and I feel like I have my fundamentals down, but for some reason I am getting errors like I forgot to put a semicolon and stuff, not sure why, or where that is, so if someone would be willing to proofread my work it would be greatly appreciated.

The errors appear to be occurring at the end of each statement in the main program, and error codes indicate I am forgetting a semicolon but I think I have them all so I don't quite understand my error.

    #include <stdio.h>
    #include <stdlib.h>

    void printArrayValues(int array[], int num);

    void fillWithIndex(int array[], int num);

    int main(int argc, char * argv[])
    {
        int arr1[] = { 23, 21, 20, 27 };
        int arr2[] = { 5, 7, 9, 11, 13 };

            // Print the values in the first array, fill that array with
            // its indexes, and then print the values of the array
            // again.

            printArrayValues(arr1[], 4);
            fillWithIndex(arr1[], 4);
            printArrayValues(arr1[], 4);

            // Do similarly for the second array.

            printArrayValues(arr2[], 5);
            fillWithIndex(arr2[], 5);
            printArrayValues(arr2[], 5);

            return 0;
    }

    void printArrayValues(int array[], int num)

    {
        int i = 0;

        while (i < num)
        {
            printf("%d\n", array[i]);
            i++;
        }

        return;
    }

    void fillWithIndex(int array[], int num)
    {
        int i = 0;

        while (i < num)
        {
            array[i] = i;
            i++;
        }

        return;
    }

Body:
1.While you are calling the function from main() don't use [] to array.
2.As you are not getting values in command line then use only int main()

i.e.

int main()
    {
        int arr1[] = { 23, 21, 20, 27 };
        int arr2[] = { 5, 7, 9, 11, 13 };

            // Print the values in the first array, fill that array with
            // its indexes, and then print the values of the array
            // again.

            printArrayValues(arr1, 4);
            fillWithIndex(arr1, 4);
            printArrayValues(arr1, 4);

            // Do similarly for the second array.

            printArrayValues(arr2, 5);
            fillWithIndex(arr2, 5);
            printArrayValues(arr2, 5);

            return 0;
    }


问:
Pandas: replace records based on conditional test in column
I have unique records in a dataframe, with no duplicates, as determined by combination of values across several columns:

```<code>import pandas as pd
d = {'Alpha' : ['C', 'B', 'C','D', 'A', 'A'], 'Beta' : ['G', 'F', 'G', 'H', 'A', 'A'],'Year': ['Base', 88, 94, 22, 'Base', 66], 'Zulu' : [1, 2, -3, 4, 5, -3]}
df = pd.DataFrame(d)
</code>```

This gets us:

```<code>  Alpha Beta  Year  Zulu
0     C    G  Base     1
1     B    F    88     2
2     C    G    94    -3
3     D    H    22     4
4     A    A  Base     5
5     A    A    66    -4
</code>```

Index 0 is a near match with index 2, & index 4 is a near match with index 5, except that the 'Year' value for index 0 & index 4 is Base, and 'Zulu' value for index 2 & 5 are negative. I want to replace the negative 'Zulu' values in 2 & 5 with their corresponding Zulu values in index 0 & 4, without disrupting other rows. The output df would look like this:

```<code>  Alpha Beta  Year  Zulu
0     C    G  Base     1
1     B    F    88     2
2     C    G    94     1
3     D    H    22     4
4     A    A  Base     5
5     A    A    66     5
</code>```

I can easily start with a filter & deep copy to avoid slicing issues, & then a backup of original data:

```<code>df_sub = df[df.Zulu < 0].copy(deep=True)
df_sub['Zulu_backup'] = df_sub.Zulu
</code>```

I can then use df_sub to merge with the original:

```<code>df_result = pd.merge(df_sub, df, how='right')
</code>```

Resulting in:

```<code>Alpha Beta  Year    Zulu     Zulu_backup
0     C    G    94    -3         -3.0
1     A    A    66    -3         -3.0
2     C    G  Base     1          NaN
3     B    F    88     2          NaN
4     D    H    22     4          NaN
5     A    A  Base     5          NaN
</code>```

But I don't know where to go from here without messing up the dataframe's other rows. I have a rather convoluted script. I am guessing I could create a series and map it to the dataframe, but I'm at a loss as to how to do so. Iterating through this is not an option as I have millions of rows. Would appreciate any assistance.

答:
One way would be to convert the negative values in Zulu to nan and then fillna</p>

```<code>df.loc[df['Zulu'] < 0, 'Zulu'] = np.nan
df['Zulu'] = df.groupby(['Alpha', 'Beta']).Zulu.apply(lambda x: x.ffill().bfill()).astype(int)

    Alpha   Beta    Year    Zulu
0   C       G       Base    1
1   B       F       88      2
2   C       G       94      1
3   D       H       22      4
4   A       A       Base    5
5   A       A       66      5
</code>```

Body:
I have unique records in a dataframe, with no duplicates, as determined by combination of values across several columns:

import pandas as pd
d = {'Alpha' : ['C', 'B', 'C','D', 'A', 'A'], 'Beta' : ['G', 'F', 'G', 'H', 'A', 'A'],'Year': ['Base', 88, 94, 22, 'Base', 66], 'Zulu' : [1, 2, -3, 4, 5, -3]}
df = pd.DataFrame(d)

This gets us:

  Alpha Beta  Year  Zulu
0     C    G  Base     1
1     B    F    88     2
2     C    G    94    -3
3     D    H    22     4
4     A    A  Base     5
5     A    A    66    -4

Index 0 is a near match with index 2, & index 4 is a near match with index 5, except that the 'Year' value for index 0 & index 4 is Base, and 'Zulu' value for index 2 & 5 are negative. I want to replace the negative 'Zulu' values in 2 & 5 with their corresponding Zulu values in index 0 & 4, without disrupting other rows. The output df would look like this:

  Alpha Beta  Year  Zulu
0     C    G  Base     1
1     B    F    88     2
2     C    G    94     1
3     D    H    22     4
4     A    A  Base     5
5     A    A    66     5

I can easily start with a filter & deep copy to avoid slicing issues, & then a backup of original data:

df_sub = df[df.Zulu < 0].copy(deep=True)
df_sub['Zulu_backup'] = df_sub.Zulu

I can then use df_sub to merge with the original:

df_result = pd.merge(df_sub, df, how='right')

Resulting in:

Alpha Beta  Year    Zulu     Zulu_backup
0     C    G    94    -3         -3.0
1     A    A    66    -3         -3.0
2     C    G  Base     1          NaN
3     B    F    88     2          NaN
4     D    H    22     4          NaN
5     A    A  Base     5          NaN

But I don't know where to go from here without messing up the dataframe's other rows. I have a rather convoluted script. I am guessing I could create a series and map it to the dataframe, but I'm at a loss as to how to do so. Iterating through this is not an option as I have millions of rows. Would appreciate any assistance.

Body:
One way would be to convert the negative values in Zulu to nan and then fillna

df.loc[df['Zulu'] < 0, 'Zulu'] = np.nan
df['Zulu'] = df.groupby(['Alpha', 'Beta']).Zulu.apply(lambda x: x.ffill().bfill()).astype(int)

    Alpha   Beta    Year    Zulu
0   C       G       Base    1
1   B       F       88      2
2   C       G       94      1
3   D       H       22      4
4   A       A       Base    5
5   A       A       66      5


问:
Error: java.lang.NoClassDefFoundError: com.fasterxml.jackson.databind.Module
I am getting the below error when I am running the application.

```<code>java.lang.NoClassDefFoundError: com.fasterxml.jackson.databind.Module
at java.lang.J9VMInternals.verifyImpl(Native Method)
at java.lang.J9VMInternals.verify(J9VMInternals.java:94)
</code>```

Even I put the below jar files in my class path and still there is no luck on running the application.
Jars that I put:
jackson-databind-2.7.4.jar
jackson-dataformat-yaml-2.7.4.jar
jackson-jarxrs-base-2.7.4.jar
jackson-jaxrs-json-provider.jar
jackson-module-jaxb-annotations.jar

Can anyone help me?

Thank you in advance.

答: You don't say which release of MyEclipse you're using but you probably need to ensure that those jars are also added to the Deployment Assembly. Search for Deployment Assembly in the Preferences (the location changed in MyEclipse 2017). That preferences page has the option of adding missing jars from your build path. Instead of altering the build path, in future, alter the deployment assembly and this will update the build path.</p>

Body:
I am getting the below error when I am running the application.

java.lang.NoClassDefFoundError: com.fasterxml.jackson.databind.Module
at java.lang.J9VMInternals.verifyImpl(Native Method)
at java.lang.J9VMInternals.verify(J9VMInternals.java:94)

Even I put the below jar files in my class path and still there is no luck on running the application.
Jars that I put:
jackson-databind-2.7.4.jar
jackson-dataformat-yaml-2.7.4.jar
jackson-jarxrs-base-2.7.4.jar
jackson-jaxrs-json-provider.jar
jackson-module-jaxb-annotations.jar

Can anyone help me?

Thank you in advance.


问:
Python Plot 3d Vectors
Supppse that I wanted to take the following three [x,y,z] coordinates:

[0.799319 -3.477045e-01  0.490093]

[0.852512  9.113778e-16 -0.522708]

[0.296422  9.376042e-01  0.181748]

And plot them as vectors where the vector's start at the origin [0,0,0]. How can I go about doing this? I've been trying to use matplotlib's quiver, but I keep geting the following value error:

```<code>ValueError: need at least one array to concatenate
</code>```

Here's my code (document_matrix_projections are the three coordinates above represented as a matrix):

```<code>D1, D2, D3 = zip(*document_matrix_projections)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(D1)
plt.show()
</code>```

答:
The quiver() function needs locations of the arrows as X,Y,Z and U,V,W as the components of the arrow. So the following script can plot your data:

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

p0 = [0.799319, -3.477045e-01, 0.490093]
p1 = [0.852512, 9.113778e-16, -0.522708]
p2 = [0.296422, 9.376042e-01, 0.181748]

origin = [0,0,0]
X, Y, Z = zip(origin,origin,origin)
U, V, W = zip(p0,p1,p2)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(X,Y,Z,U,V,W,arrow_length_ratio=0.01)
plt.show()
</code>```

But the results are not pretty. If you would like to use Mayavi, the following works:

```<code>import numpy as np
import mayavi.mlab as m

p0 = [0.799319, -3.477045e-01, 0.490093]
p1 = [0.852512, 9.113778e-16, -0.522708]
p2 = [0.296422, 9.376042e-01, 0.181748]

origin = [0,0,0]
X, Y, Z = zip(origin,origin,origin)
U, V, W = zip(p0,p1,p2)

m.quiver3d(X,Y,Z,U,V,W)
</code>```

Title: Python Plot 3d Vectors

Body:
Supppse that I wanted to take the following three [x,y,z] coordinates:

[0.799319 -3.477045e-01  0.490093]

[0.852512  9.113778e-16 -0.522708]

[0.296422  9.376042e-01  0.181748]

And plot them as vectors where the vector's start at the origin [0,0,0]. How can I go about doing this? I've been trying to use matplotlib's quiver, but I keep geting the following value error:

ValueError: need at least one array to concatenate

Here's my code (document_matrix_projections are the three coordinates above represented as a matrix):

D1, D2, D3 = zip(*document_matrix_projections)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(D1)
plt.show()

Body:
The quiver() function needs locations of the arrows as X,Y,Z and U,V,W as the components of the arrow. So the following script can plot your data:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

p0 = [0.799319, -3.477045e-01, 0.490093]
p1 = [0.852512, 9.113778e-16, -0.522708]
p2 = [0.296422, 9.376042e-01, 0.181748]

origin = [0,0,0]
X, Y, Z = zip(origin,origin,origin)
U, V, W = zip(p0,p1,p2)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(X,Y,Z,U,V,W,arrow_length_ratio=0.01)
plt.show()

But the results are not pretty. If you would like to use Mayavi, the following works:

import numpy as np
import mayavi.mlab as m

p0 = [0.799319, -3.477045e-01, 0.490093]
p1 = [0.852512, 9.113778e-16, -0.522708]
p2 = [0.296422, 9.376042e-01, 0.181748]

origin = [0,0,0]
X, Y, Z = zip(origin,origin,origin)
U, V, W = zip(p0,p1,p2)

m.quiver3d(X,Y,Z,U,V,W)


问:
Product Method Overloading
so I was working on this problem on CodeHS, then I was stuck for so long so decided to ask here.

The exercise is to overload the product method to allow for multiplying together other types of values:

two doubles

an int and a double

a double and an int

three ints

three doubles

```<code>public class Product extends ConsoleProgram
{
    public void run()
    {
        int intValue = 5;
        double doubleValue = 2.5;

        int product1 = product(intValue, intValue);
        System.out.println(product1);

        // Use method overloading to define methods
        // for each of the following method calls

        double product2 = product(doubleValue, doubleValue);
        System.out.println(product2);

        int product3 = product(intValue, intValue, intValue);
        System.out.println(product3);

        double product4 = product(intValue, doubleValue);
        System.out.println(product4);

        double product5 = product(doubleValue, intValue);
        System.out.println(product5);

        double product6 = product(doubleValue, doubleValue, doubleValue);
        System.out.println(product6);
    }

    public int product(int one, int two)
    {
        return one * two;
    }
}
</code>```

Thank you

答:
be aware that overloading means, the name of the method and the return type remains the same as the original/ initial method.

then you need to define/ implement those methods>

2 doubles would be:

```<code>public int product(double one, double two)
{
    return (int)(one * two);
}
</code>```

an int and a double would be

```<code>public int product(int one, double two)
{
    return (int)(one * two);
}
</code>```

etc

Title: Product Method Overloading

Body:
so I was working on this problem on CodeHS, then I was stuck for so long so decided to ask here.

The exercise is to overload the product method to allow for multiplying together other types of values:

two doubles

an int and a double

a double and an int

three ints

three doubles

public class Product extends ConsoleProgram
{
    public void run()
    {
        int intValue = 5;
        double doubleValue = 2.5;

        int product1 = product(intValue, intValue);
        System.out.println(product1);

        // Use method overloading to define methods
        // for each of the following method calls

        double product2 = product(doubleValue, doubleValue);
        System.out.println(product2);

        int product3 = product(intValue, intValue, intValue);
        System.out.println(product3);

        double product4 = product(intValue, doubleValue);
        System.out.println(product4);

        double product5 = product(doubleValue, intValue);
        System.out.println(product5);

        double product6 = product(doubleValue, doubleValue, doubleValue);
        System.out.println(product6);
    }

    public int product(int one, int two)
    {
        return one * two;
    }
}

Thank you

Body:
be aware that overloading means, the name of the method and the return type remains the same as the original/ initial method.

then you need to define/ implement those methods>

2 doubles would be:

public int product(double one, double two)
{
    return (int)(one * two);
}

an int and a double would be

public int product(int one, double two)
{
    return (int)(one * two);
}

etc


问:
How to remove an item from an array in Vue.js
I am new to vue.js (2) and I am currently working on a simple event app. I've managed to add events but now I would like to delete events based on clicking on a button.

HTML

```<code>    <div class="list-group">

        <div class="list-group-item" v-for="event in events">
            <h4 class="list-group-item-heading">
                {{ event.name }}
            </h4>

            <h5>
                {{ event.date }}
            </h5>

            <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

            <button class="btn btn-xs btn-danger" @click="deleteEvent(event)">Delete</button>
        </div>

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

JS(Vue)

```<code>new Vue ({
    el: '#app',

    data: {
        events: [
            {
                id: 1,
                name: 'Event 1',
                description: 'Just some lorem ipsum',
                date: '2015-09-10'
            },
            {
                id: 2,
                name: 'Event 2',
                description: 'Just another lorem ipsum',
                date: '2015-10-02'
            }
        ],

        event: { name: '', description: '', date: '' }
    },

    ready: function() {

    },

    methods: {

        deleteEvent: function(event) {
                this.events.splice(this.event);
        },

        // Adds an event to the existing events array
        addEvent: function() {
            if(this.event.name) {
                this.events.push(this.event);
                this.event = { name: '', description: '', date: '' };
            }
        }

    } // end of methods

});
</code>```

I've tried to pass the event to the function and than delete that one with the slice function, I thought it was that code for deleting some data from the array. What is the best en cleanest way to delete data from the array with a simpleb button and onclick event?

答:
It is even funnier when you are doing it with inputs, because they should be bound. If you are interested in how to do it in Vue2 with options to insert and delete, please see an example:

please have a look an js fiddle

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: 'def' });
    },
    deleteFind: function (index) {
      console.log(index);
      console.log(this.finds);
      this.finds.splice(index, 1);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>
<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value">
    <button @click="deleteFind(index)">
      delete
    </button>
  </div>

  <button @click="addFind">
    New Find
  </button>

  ```{{ $data }}```
</div></code>```

Body:
I am new to vue.js (2) and I am currently working on a simple event app. I've managed to add events but now I would like to delete events based on clicking on a button.

HTML

                {{ event.name }}

                {{ event.date }}

{{ event.description }}

            <button class="btn btn-xs btn-danger" @click="deleteEvent(event)">Delete</button>

JS(Vue)

new Vue ({
    el: '#app',

    data: {
        events: [
            {
                id: 1,
                name: 'Event 1',
                description: 'Just some lorem ipsum',
                date: '2015-09-10'
            },
            {
                id: 2,
                name: 'Event 2',
                description: 'Just another lorem ipsum',
                date: '2015-10-02'
            }
        ],

        event: { name: '', description: '', date: '' }
    },

    ready: function() {

    },

    methods: {

        deleteEvent: function(event) {
                this.events.splice(this.event);
        },

        // Adds an event to the existing events array
        addEvent: function() {
            if(this.event.name) {
                this.events.push(this.event);
                this.event = { name: '', description: '', date: '' };
            }
        }

    } // end of methods

});

I've tried to pass the event to the function and than delete that one with the slice function, I thought it was that code for deleting some data from the array. What is the best en cleanest way to delete data from the array with a simpleb button and onclick event?

Body:
It is even funnier when you are doing it with inputs, because they should be bound. If you are interested in how to do it in Vue2 with options to insert and delete, please see an example:

please have a look an js fiddle

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: 'def' });
    },
    deleteFind: function (index) {
      console.log(index);
      console.log(this.finds);
      this.finds.splice(index, 1);
    }
  }
});

<script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>
<div id="app">
  <h1>Finds</h1>
  <div v-for="(find, index) in finds">
    <input v-model="find.value">
    <button @click="deleteFind(index)">
      delete
    </button>
  </div>

  <button @click="addFind">
    New Find
  </button>

  <pre>{{ $data }}</pre>
</div>


问:
ICS file when imported in outlook shows wrong end date when no start & end time is specified
I have generated ICS file through PHP & JS .

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:https://www.google.com/
CALSCALE:GREGORIAN
TZ:+00
BEGIN:VEVENT
UID:https://www.google.com/
DTSTAMP:20180308T140833Z
DTSTART;VALUE=DATE:20180308
DTEND;VALUE=DATE:20180312
SUMMARY:"Hamlet"
X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML><HTML><BODY>Show Times:<br/>March 8-11, 2018 @ 7:30 pm<br/> March 12, 2018 @ 2:00 pm<br/>Often dubbed the “Greatest Play Ever Written” and written by the most produced playwright each year, William Shakespeare, the titular Hamlet.<br/><a href=https://www.whittierevents.com/events/hamlet/>https://www.whittierevents.com/events/hamlet/</a></BODY></HTML>
LOCATION:6760 Painter Ave, Whittier, CA 90601
END:VEVENT
END:VCALENDAR
</code>```

When I import this file in outlook, end date is shown as 11th March though it is 12th March.
How can I fix this?

答: According to the spec, the end of an allday event is the beginning of the next day.  So a 1 day event in the ics file will have 2 dates - the DTEND will be the day after the DTSTART.  So in our case, to make it look like it ends on the 12th in applications, the .ics file must say 13th.  See also Exclusive/Inclusive DTEND according to RFC5545 and Fullcalendar in event with time part, how to do it right?</p>

Body:
I have generated ICS file through PHP & JS .

BEGIN:VCALENDAR
VERSION:2.0
PRODID:https://www.google.com/
CALSCALE:GREGORIAN
TZ:+00
BEGIN:VEVENT
UID:https://www.google.com/
DTSTAMP:20180308T140833Z
DTSTART;VALUE=DATE:20180308
DTEND;VALUE=DATE:20180312
SUMMARY:"Hamlet"
X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML>Show Times:
March 8-11, 2018 @ 7:30 pm
 March 12, 2018 @ 2:00 pm
Often dubbed the “Greatest Play Ever Written” and written by the most produced playwright each year, William Shakespeare, the titular Hamlet.
https://www.whittierevents.com/events/hamlet/
LOCATION:6760 Painter Ave, Whittier, CA 90601
END:VEVENT
END:VCALENDAR

When I import this file in outlook, end date is shown as 11th March though it is 12th March.
How can I fix this?


问:
Call PHP function in ajax, Synchronous XMLHttpRequest deprecarted
Completely new to php/ajax. Every tutorial seems to be outdated in one way or another. Spent about 30 hours already trying to come up with a simple insert/retrieve script. Please help! Once i see the code working its alot easier for me to fiddle with it understand the documentation.

Im getting the following error.

```<code>[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
</code>```

My index.php relevant data, the error is on the xmlhttp.open line.

```<code>disp_data();
function disp_data(){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "update.php?status=disp",false);
</code>```

This is my update.php relevant code. On the tutorial, it is supposed to load my data upon refresh, but its blank. I'm not sure why the tutorial sets it to false, when the documentation ive read at w3schools seems I should make it true, but neither work.

```<code>$status = $_GET["status"];

if ($status == "disp") {
  $link = mysqli_connect("localhost", "root", "");
  mysqli_select_db($link, "checkbox");
</code>```

      $res = mysqli_query($link, "SELECT * FROM table1");

my full index.php

```<code><div id ="disp_data"></div>

<script src="jquery-3.2.1.min.js"></script>
<script type ="text/javascript">

(function() {
  var newXHR = null;

  function sendXHR(type, url, data, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
    newXHR.send(data);

    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response); // Callback function to process the response.
      }
    };
  }

  sendXHR("GET", "update.php?status=disp", null, function(response) {
    document.getElementById("disp_data").innerHTML=newXHR.responseText;
  });

})();

</script>

</body>
</code>```

my full update.php file

```<code>$status = $_GET["status"];
if($status=="disp")
{
$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"checkbox");
$res = mysqli_query($link,"SELECT * FROM table1");

echo "<table>";
while($row = mysqli_fetch_array($res))
{
echo "<tr>";
echo "<td>";   echo $row["id"]; echo "</td>";
echo "<td>";  echo $row["name"];  echo "</td>";
echo "<td>";  echo $row["city"];  echo "</td>";

echo "</tr>";
}
echo "</table>";
}
</code>```

答:
You should use true in the async parameter.

Something like this: xmlhttp.open("GET", "update.php?status=disp", true);.

See XMLHttpRequest.open().

You could use this helper function to make XMLHttpRequest.

Works in all browsers, incluiding IE6.

```<code>var newXHR = null;

function sendXHR(type, url, data, callback) {
  newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
  newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
  newXHR.send(data);
  newXHR.onreadystatechange = function() {
    if (this.status === 200 && this.readyState === 4) {
      callback(this.response); // Callback function to process the response.
    }
  };
}
</code>```

Usage:

```<code>sendXHR("GET", "update.php?status=disp", null, function(response) {
  console.log(response);
});
</code>```

You could retrieve data by using this demo:

(function() {

  var newXHR = null;

  function sendXHR(type, url, data, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
    newXHR.send(data);
    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response); // Callback function to process the response.
      }
    };
  }

  // Example 1: Get data.
  var btnRequest = document.getElementById("btnRequest");
  btnRequest.onclick = function() {
    sendXHR("GET", "https://gist.githubusercontent.com/dannyjhonston/22851f9c21733973b2705b0b65443f90/raw/30cf99ceeb470a7ab6d2ffb51a78f1bb57f41ca3/data.txt", null, function(response) {
      document.getElementById("myDiv").innerHTML = response; // response contains the data from the server.
    });
  };

  // Example 2. Cancel a long request.
  var btnCancelRequest = document.getElementById("btnCancelRequest");
  btnCancelRequest.onclick = function() {
    newXHR.abort(); // You can use the newXHR variable to abort a XMLHttpRequest that is taking long time to response, with the .abort() method.
  };

})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myDiv {
  border: solid 1px #ccc;
  border-radius: 5px;
  margin: 20px;
  padding: 5px;
}</code>```

<button id="btnRequest" type="button">Request data</button>
<button id="btnCancelRequest" type="button">Cancel request</button>

The new content will print here.
```
</div>
</div>
</p>

<hr>

<p>It's good to know this:</p>

<blockquote>
  <p><strong><code>XMLHttpRequest.response</code></strong> property returns the response's
  body. It can be of the type <code>ArrayBuffer</code>, <code>Blob</code>, <code>Document</code>,
  <code>JavaScript</code> object, or a <code>DOMString</code>, depending of the value of
  <code>XMLHttpRequest.responseType</code> property. Value of response is null if
  the request is not complete or was not successful. However, if the
  value of <code>responseType</code> was set to <code>"text"</code> or the empty string,
  response can contain the partial text response while the request is
  still in the loading state.</p>

  <p><strong><code>XMLHttpRequest.responseText</code></strong> property returns a <code>DOMString</code>
  that contains the response to the request as text, or <code>null</code> if the
  request was unsuccessful or has not yet been sent. The <code>responseText</code>
  property will have the partial response as it arrives even before the
  request is complete. If <code>responseType</code> is set to anything other than
  the empty <code>string</code> or <code>"text"</code>, accessing <code>responseText</code> will throw
  <code>InvalidStateError</code> exception.</p>
</blockquote>

<hr>

<p>Your php code must be like this:</p>

```$status = $_GET["status"];
if($status=="disp")
{
    $link = mysqli_connect("localhost", "root", "");
    mysqli_select_db($link,"checkbox");
    $res = mysqli_query($link,"SELECT * FROM table1");

    $html = "
"; // Declare a variable to concat the html content.
    while($row = mysqli_fetch_array($res))
    {
        $html += "
";
        $html += $row["id"];
        $html += "	";
        $html += $row["name"];
        $html += "	";
        $html += $row["city"];
        $html += "
";
    }
    $html += "
";
    echo $html; // Prints the $html variable.
}
```

<p>In you html code you need to remove:</p>

```
```

It's not necessary if you gonna use native javascript.

Body:
Completely new to php/ajax. Every tutorial seems to be outdated in one way or another. Spent about 30 hours already trying to come up with a simple insert/retrieve script. Please help! Once i see the code working its alot easier for me to fiddle with it understand the documentation.

Im getting the following error.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

My index.php relevant data, the error is on the xmlhttp.open line.

disp_data();
function disp_data(){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "update.php?status=disp",false);

This is my update.php relevant code. On the tutorial, it is supposed to load my data upon refresh, but its blank. I'm not sure why the tutorial sets it to false, when the documentation ive read at w3schools seems I should make it true, but neither work.

$status = $_GET["status"];

if ($status == "disp") {
  $link = mysqli_connect("localhost", "root", "");
  mysqli_select_db($link, "checkbox");

      $res = mysqli_query($link, "SELECT * FROM table1");

my full index.php

my full update.php file

$status = $_GET["status"];
if($status=="disp")
{
$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"checkbox");
$res = mysqli_query($link,"SELECT * FROM table1");

echo "
";
while($row = mysqli_fetch_array($res))
{
echo "
";
echo "";   echo $row["id"]; echo "	";
echo "";  echo $row["name"];  echo "	";
echo "";  echo $row["city"];  echo "	";

echo "
";
}
echo "
";
}

Body:
You should use true in the async parameter.

Something like this: xmlhttp.open("GET", "update.php?status=disp", true);.

See XMLHttpRequest.open().

You could use this helper function to make XMLHttpRequest.

Works in all browsers, incluiding IE6.

var newXHR = null;

function sendXHR(type, url, data, callback) {
  newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
  newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
  newXHR.send(data);
  newXHR.onreadystatechange = function() {
    if (this.status === 200 && this.readyState === 4) {
      callback(this.response); // Callback function to process the response.
    }
  };
}

Usage:

sendXHR("GET", "update.php?status=disp", null, function(response) {
  console.log(response);
});

You could retrieve data by using this demo:

(function() {

  var newXHR = null;

  function sendXHR(type, url, data, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
    newXHR.send(data);
    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response); // Callback function to process the response.
      }
    };
  }

  // Example 1: Get data.
  var btnRequest = document.getElementById("btnRequest");
  btnRequest.onclick = function() {
    sendXHR("GET", "https://gist.githubusercontent.com/dannyjhonston/22851f9c21733973b2705b0b65443f90/raw/30cf99ceeb470a7ab6d2ffb51a78f1bb57f41ca3/data.txt", null, function(response) {
      document.getElementById("myDiv").innerHTML = response; // response contains the data from the server.
    });
  };

  // Example 2. Cancel a long request.
  var btnCancelRequest = document.getElementById("btnCancelRequest");
  btnCancelRequest.onclick = function() {
    newXHR.abort(); // You can use the newXHR variable to abort a XMLHttpRequest that is taking long time to response, with the .abort() method.
  };

})();

#myDiv {
  border: solid 1px #ccc;
  border-radius: 5px;
  margin: 20px;
  padding: 5px;
}

<button id="btnRequest" type="button">Request data</button>
<button id="btnCancelRequest" type="button">Cancel request</button>
<div id="myDiv">The new content will print here.</div>

It's good to know this:

XMLHttpRequest.response property returns the response's
  body. It can be of the type ArrayBuffer, Blob, Document,
  JavaScript object, or a DOMString, depending of the value of
  XMLHttpRequest.responseType property. Value of response is null if
  the request is not complete or was not successful. However, if the
  value of responseType was set to "text" or the empty string,
  response can contain the partial text response while the request is
  still in the loading state.

XMLHttpRequest.responseText property returns a DOMString
  that contains the response to the request as text, or null if the
  request was unsuccessful or has not yet been sent. The responseText
  property will have the partial response as it arrives even before the
  request is complete. If responseType is set to anything other than
  the empty string or "text", accessing responseText will throw
  InvalidStateError exception.

Your php code must be like this:

$status = $_GET["status"];
if($status=="disp")
{
    $link = mysqli_connect("localhost", "root", "");
    mysqli_select_db($link,"checkbox");
    $res = mysqli_query($link,"SELECT * FROM table1");

    $html = "<table>"; // Declare a variable to concat the html content.
    while($row = mysqli_fetch_array($res))
    {
        $html += "<tr><td>";
        $html += $row["id"];
        $html += "</td><td>";
        $html += $row["name"];
        $html += "</td><td>";
        $html += $row["city"];
        $html += "</td></tr>";
    }
    $html += "</table>";
    echo $html; // Prints the $html variable.
}

In you html code you need to remove:

<script src="jquery-3.2.1.min.js"></script>

It's not necessary if you gonna use native javascript.


问:
getting "Response code 404 mapped as failure" by consuming web api from Mulesoft
I'm trying to consume to the open source api getting the response code 404 mapped as failure.

```<code><http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>
<http:request-config name="HTTP_Request_Configuration" protocol="HTTPS" host="api.taxjar.com" port="443" basePath="v2/taxes" doc:name="HTTP Request Configuration"/>
<flow name="postTaxCollectionFlow">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/taxcollection" allowedMethods="POST" doc:name="HTTP"/>
    <dw:transform-message doc:name="Transform Message" metadata:id="2789cbd2-5ca6-46c2-856f-67ba2bdfa6dd">
        <dw:input-payload mimeType="application/json"/>
        <dw:set-payload>
            <![CDATA[%dw 1.0
            %output application/json
            ---
            payload
            ]]></dw:set-payload>
    </dw:transform-message>
    <http:request config-ref="HTTP_Request_Configuration" path="https://api.taxjar.com/v2/taxes" method="POST" doc:name="Web Service">
        <http:request-builder>
            <http:query-param paramName="Authorization" value="Token token="8dbc821e651fe0672c4032e65209b37c""/>
            <http:query-param paramName="Content-Type" value="application/json"/>
        </http:request-builder>
    </http:request>
    <byte-array-to-object-transformer doc:name="Byte Array to Object"/>
    <json:object-to-json-transformer doc:name="Object to JSON"/>
    <logger message="#[payload]" level="INFO" doc:name="Logger"/>
</flow>
</code>```

and error message is

Response code 404 mapped as failure.
Payload               : org.glassfish.grizzly.utils.BufferInputStream@12c30f42
Element               : /postTaxCollectionFlow/processors/1 @ taxcollection_apisero:taxcollection_apisero.xml:23 (Web Service)
Element XML           :
                        http:request-builder

please help me out to configure it

答:
Check the path in the Webservice component,
Since you have already specified the host and port need not give the path as complete. Please change the path and check response.</p>

Body:
I'm trying to consume to the open source api getting the response code 404 mapped as failure.

<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>
<http:request-config name="HTTP_Request_Configuration" protocol="HTTPS" host="api.taxjar.com" port="443" basePath="v2/taxes" doc:name="HTTP Request Configuration"/>
<flow name="postTaxCollectionFlow">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/taxcollection" allowedMethods="POST" doc:name="HTTP"/>
    <dw:transform-message doc:name="Transform Message" metadata:id="2789cbd2-5ca6-46c2-856f-67ba2bdfa6dd">
        <dw:input-payload mimeType="application/json"/>
        <dw:set-payload>
            <![CDATA[%dw 1.0
            %output application/json
            ---
            payload
            ]]></dw:set-payload>
    </dw:transform-message>
    <http:request config-ref="HTTP_Request_Configuration" path="https://api.taxjar.com/v2/taxes" method="POST" doc:name="Web Service">
        <http:request-builder>
            <http:query-param paramName="Authorization" value="Token token="8dbc821e651fe0672c4032e65209b37c""/>
            <http:query-param paramName="Content-Type" value="application/json"/>
        </http:request-builder>
    </http:request>
    <byte-array-to-object-transformer doc:name="Byte Array to Object"/>
    <json:object-to-json-transformer doc:name="Object to JSON"/>
    <logger message="#[payload]" level="INFO" doc:name="Logger"/>
</flow>

and error message is

Response code 404 mapped as failure.
Payload               : org.glassfish.grizzly.utils.BufferInputStream@12c30f42
Element               : /postTaxCollectionFlow/processors/1 @ taxcollection_apisero:taxcollection_apisero.xml:23 (Web Service)
Element XML           :
                        http:request-builder

please help me out to configure it


问:
Fancybox Pop-up Login - Page only opens in modal box
I'm trying to create a log-in page using Fancybox.  Everyhing works fine, except when I redirect the user to the logged-in page, it keeps opening up in the modal dialog box.

How can I reference the parent?

parent.opener.location.href is not working.

Thanks

答:
It seems the following worked:</p>

```<code>parent.document.location.href
</code>```

Body:
It seems the following worked:

parent.document.location.href


问:
Load balancing sockets on a horizontally scaling WebSocket server?
Every few months when thinking through a personal project that involves sockets I find myself having the question of "How would you properly load balance sockets on a dynamic horizontally scaling WebSocket server?"

I understand the theory behind horizontally scaling the WebSockets and using pub/sub models to get data to the right server that holds the socket connection for a specific user. I think I understand ways to effectively identify the server with the fewest current socket connections that I would want to route a new socket connection too. What I don't understand is how to effectively route new socket connections to the server you've picked with low socket count.

I don't imagine this answer would be tied to a specific server implementation, but rather could be applied to most servers. I could easily see myself implementing this with vert.x, node.js, or even perfect.

答:
First off, you need to define the bounds of the problem you're asking about.  If you're truly talking about dynamic horizontal scaling where you spin up and down servers based on total load, then that's an even more involved problem than just figuring out where to route the latest incoming new socket connection.

To solve that problem, you have to have a way of "moving" a socket from one host to another so you can clear connections from a host that you want to spin down (I'm assuming here that true dynamic scaling goes both up and down).  The usual way I've seen that done is by engaging a cooperating client where you tell the client to reconnect and when it reconnects it is load balanced onto a different server so you can clear off the one you wanted to spin down.  If your client has auto-reconnect logic already (like socket.io does), you can just have the server close the connection and the client will automatically re-connect.

As for load balancing the incoming client connections, you have to decide what load metric you want to use.  Ultimately, you need a score for each server process that tells you how "busy" you think it is so you can put new connections on the least busy server.  A rudimentary score would just be number of current connections.  If you have large numbers of connections per server process (tens of thousands) and there's no particular reason in your app that some might be lots more busy than others, then the law of large numbers probably averages out the load so you could get away with just how many connections each server has.  If the use of connections is not that fair or even, then you may have to also factor in some sort of time moving average of the CPU load along with the total number of connections.

If you're going to load balance across multiple physical servers, then you will need a load balancer or proxy service that everyone connects to initially and that proxy can look at the metrics for all currently running servers in the pool and assign the connection to the one with the most lowest current score.  That can either be done with a proxy scheme or (more scalable) via a redirect so the proxy gets out of the way after the initial assignment.

You could then also have a process that regularly examines your load score (however you decided to calculate it) on all the servers in the cluster and decides when to spin a new server up or when to spin one down or when things are too far out of balance on a given server and that server needs to be told to kick several connections off, forcing them to rebalance.

What I don't understand is how to effectively route new socket connections to the server you've picked with low socket count.

As described above, you either use a proxy scheme or a redirect scheme.  At a slightly higher cost at connection time, I favor the redirect scheme because it's more scalable when running and creates fewer points of failure for an existing connection.  All clients connect to your incoming connection gateway server which is responsible for knowing the current load score for each of the servers in the farm and based on that, it assigns an incoming connection to the host with the lowest score and this new connection is then redirected to reconnect to one of the specific servers in your farm.

I have also seen load balancing done purely by a custom DNS implementation.  Client requests IP address for farm.somedomain.com and that custom DNS server gives them the IP address of the host it wants them assigned to.  Each client that looks up the IP address for farm.somedomain.com may get a different IP address.  You spin hosts up or down by adding or removing them from the custom DNS server and it is that custom DNS server that has to contain the logic for knowing the load balancing logic and the current load scores of all the running hosts.


问:
Authenticate PostgreSQL user and password without database
How do I verify the postgresql user and password are valid without the existence of a database?

I'm creating an automated installation that will create a database and run sql scripts to create tables.  The install needs to authenticate the user and password before running the scripts.  The automated install calls Windows batch files.  First I set the password, set PGPASSWORD=mypassword.

After setting the password, what command can authenticate the user and password and return an error code or message?

Other database programs (like IBM and db2) have an attach command which lets the user attach to the server or instance, without specifying a db name. I cannot find the equivalent for PostgreSQL.

How do I login to PostgreSQL on the command line without specifying a database name?

答:
Simply use this command in your terminal:</p>

```<code>psql postgres
</code>```

Body:
Simply use this command in your terminal:

psql postgres


问:
Find all possible combinations from multiple arrays
I'm trying to write an algorithm, and due to my lack of experience writing complex algorithms, I'm struggling a bit here. So, in this scenario I have n number of character arrays, each array containing m characters. I need to generate every possible combination of characters between the arrays.

Example, I have the following arrays:

```<code>arr1 = [2, 3]
arr2 = ['y', 1]
arr3 = [1]
arr4 = [2, 'u', 4]
</code>```

With the above arrays all of the possible combinations are:

```<code>2y12
2y1u
2y14
2112
211u
2114
3y12
3y1u
3y14
3112
311u
3114
</code>```

There can be any number n arrays, and any number of characters in each array. So this algorithm needs to scale. I was thinking that a recursive solution might be possible, I just can't wrap my head around how that would work. This problem is very similar to the post Generating all Possible Combinations, except I still don't see how to make the solution dynamic in order to handle any number of arrays with any number of elements within said arrays.

My solution will end up being written in C#, but you can help my with any other language or pseudo code.

答:
```<code>void Dodge(List<List<T>> domains)
{
    Fuski(domains, new List<T>());
}

void Fuski(List<List<T>> domains, List<T> vector)
{
    if (domains.Count == vector.Count)
    {
        Console.WriteLine(string.Join("", vector));
        return;
    }
    foreach (var value in domains[vector.Count])
    {
        var newVector = vector.ToList();
        newVector.Add(value);
        Fuski(domains, newVector);
    }
}
</code>```

Body:
I'm trying to write an algorithm, and due to my lack of experience writing complex algorithms, I'm struggling a bit here. So, in this scenario I have n number of character arrays, each array containing m characters. I need to generate every possible combination of characters between the arrays.

Example, I have the following arrays:

arr1 = [2, 3]
arr2 = ['y', 1]
arr3 = [1]
arr4 = [2, 'u', 4]

With the above arrays all of the possible combinations are:

2y12
2y1u
2y14
2112
211u
2114
3y12
3y1u
3y14
3112
311u
3114

There can be any number n arrays, and any number of characters in each array. So this algorithm needs to scale. I was thinking that a recursive solution might be possible, I just can't wrap my head around how that would work. This problem is very similar to the post Generating all Possible Combinations, except I still don't see how to make the solution dynamic in order to handle any number of arrays with any number of elements within said arrays.

My solution will end up being written in C#, but you can help my with any other language or pseudo code.


问:
Is it possible to check if elements of a tensor are out of boundaries?
Is it possible to check if elements of a tensor are out of boundaries using torch.cuda.FloatTensor on PyTorch, GPU approach?

Example (check limits):

```<code>for i in range(pop):
    if (x[i]>xmax):
        x[i]=xmax
    elif (x[i]<xmin):
        x[i]=xmin
</code>```

I tried the following, but did not speed up:

```<code>idxmax    = (x > xmax) # elements that are bigger that upper limit
idxmim    = (x < min)  # elements that are smaller that upper limit
x[idxmax] = xmax
x[idxmin] = xmin
</code>```

If not, is it possible to do this check limits part, using only the CPU? How?

答:
You can get a CPU copy of tensor x, do your operations and then push the tensor to GPU memory again.

```<code>x = x.cpu()  # get the CPU copy
# do your operations
x = x.cuda() # move the object back to cuda memory
</code>```

Body:
Is it possible to check if elements of a tensor are out of boundaries using torch.cuda.FloatTensor on PyTorch, GPU approach?

Example (check limits):

for i in range(pop):
    if (x[i]>xmax):
        x[i]=xmax
    elif (x[i]<xmin):
        x[i]=xmin

I tried the following, but did not speed up:

idxmax    = (x > xmax) # elements that are bigger that upper limit
idxmim    = (x < min)  # elements that are smaller that upper limit
x[idxmax] = xmax
x[idxmin] = xmin

If not, is it possible to do this check limits part, using only the CPU? How?

Body:
You can get a CPU copy of tensor x, do your operations and then push the tensor to GPU memory again.

x = x.cpu()  # get the CPU copy
# do your operations
x = x.cuda() # move the object back to cuda memory


问:
HTML/CSS Blink Animation Website
I'm trying to create a flashing effect for an image and I've come across that you can use "Blink" Animations. But I'm clueless on how to set a time limit e.g. Flash on and Off in 4 seconds.

I have used Keyframe (blink) with opacity on different percentage.

Is there any chance you guys could help me it would be much appreciated.

Here is my code that I have tried.

```

答:
First thing to note here is: The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent

IE8 and earlier use filter:alpha(opacity=x). The x can take a value from 0 - 100. A lower value makes the element more transparent.
I have made the changes to your code and you can find the snippet below.

Hope it works!

javascript jquery html css
shareeditflag```

Title: HTML/CSS Blink Animation Website

Body:
First thing to note here is: The opacity property can take a value from 0.0 - 1.0. The lower value, the more transparent

IE8 and earlier use filter:alpha(opacity=x). The x can take a value from 0 - 100. A lower value makes the element more transparent.
I have made the changes to your code and you can find the snippet below.

Hope it works!

<html>
<head>
<style>
/* Firefox old*/
@-moz-keyframes blink {
    from, 50%, to {
    opacity: 1;
  }

  25%, 75% {
    opacity: 0;
  }
}

@-webkit-keyframes blink {
    from, 50%, to {
    opacity: 1;
  }

  25%, 75% {
    opacity: 0;
  }
}
/* IE */
@-ms-keyframes blink {
    from, 50%, to {
    opacity: 1;
  }

  25%, 75% {
    opacity: 0;
  }
}
/* Opera and prob css3 final iteration */
@keyframes blink {
    from, 50%, to {
    opacity: 1;
  }

  25%, 75% {
    opacity: 0;
  }
}
.blink-image {
    -moz-animation: blink normal 4s infinite ease-in-out; /* Firefox */
    -webkit-animation: blink normal 4s infinite ease-in-out; /* Webkit */
    -ms-animation: blink normal 4s infinite ease-in-out; /* IE */
    animation: blink normal 4s infinite ease-in-out; /* Opera and prob css3 final iteration */
}
</style>
</head>
<body>
<p align="center">
<img class="blink-image" src="http://keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" width="390" />
</body>
</html>
javascript jquery html css
shareeditflag


问:
selecting a ng-select with jquery
The first control on my page needs to have input focus when the page initially loads, unfortunately, in my case, that control is an ng-select.

So, somewhere in my ang2 template:

```<code><ng-select id="mySelect" class="form-control" [options]="_myOptions" [(ngModel)]="model.SelectId" *ngIf=initDone' name=" mySelect" style="z-index: 10">
</ng-select>
</code>```

In my ngAfterViewInit, I have:

```<code>$("#mySelect > div").focus();
$("#mySelect > div").select();
</code>```

(Also tried dropping the div)

Alas, this is not working.

Note:
This is NOT a duplicate of "What is the easiest way to put a default focus on an element in AngularJS". That question is referring to an input control, so basic jquery focus/select works. This is specifically referring to an ng-select (which render as a bunch children div's).

答:
This code worked for me, try this

```<code><ng-select #myInput id="mySelect" class="form-control" [options]="_myOptions" [(ngModel)]="model.SelectId" *ngIf=initDone' name=" mySelect" style="z-index: 10">
</ng-select>
</code>```

and in your component.ts, use viewchild and renderer to get the element. AfterViewInit helps to focus it after the html is rendered. (got issue on OnInit(), that why)

```<code>import {ViewChild, Component, AfterViewInit, ElementRef, Renderer} from 'angular2/core';

export class App {
  @ViewChild('myInput') selectFocus:ElementRef;

  constructor(private _renderer : Renderer) {

  }

  public ngAfterViewInit() {
    this._renderer.invokeElementMethod(this.selectFocus.nativeElement, 'focus', []);
  }
}
</code>```

Title: selecting a ng-select with jquery

Body:
The first control on my page needs to have input focus when the page initially loads, unfortunately, in my case, that control is an ng-select.

So, somewhere in my ang2 template:

<ng-select id="mySelect" class="form-control" [options]="_myOptions" [(ngModel)]="model.SelectId" *ngIf=initDone' name=" mySelect" style="z-index: 10">
</ng-select>

In my ngAfterViewInit, I have:

$("#mySelect > div").focus();
$("#mySelect > div").select();

(Also tried dropping the div)

Alas, this is not working.

Note:
This is NOT a duplicate of "What is the easiest way to put a default focus on an element in AngularJS". That question is referring to an input control, so basic jquery focus/select works. This is specifically referring to an ng-select (which render as a bunch children div's).

Body:
This code worked for me, try this

<ng-select #myInput id="mySelect" class="form-control" [options]="_myOptions" [(ngModel)]="model.SelectId" *ngIf=initDone' name=" mySelect" style="z-index: 10">
</ng-select>

and in your component.ts, use viewchild and renderer to get the element. AfterViewInit helps to focus it after the html is rendered. (got issue on OnInit(), that why)

import {ViewChild, Component, AfterViewInit, ElementRef, Renderer} from 'angular2/core';

export class App {
  @ViewChild('myInput') selectFocus:ElementRef;

  constructor(private _renderer : Renderer) {

  }

  public ngAfterViewInit() {
    this._renderer.invokeElementMethod(this.selectFocus.nativeElement, 'focus', []);
  }
}


答:
Array decays to pointer to its first element. First argument of both of your functions expects an argument of type int *. In your function calls you should pass the first argument like this

```<code>printArrayValues(arr1, 4);
fillWithIndex(arr1, 4);
printArrayValues(arr1, 4);

// Do similarly for the second array.

printArrayValues(arr2, 5);
fillWithIndex(arr2, 5);
printArrayValues(arr2, 5);
</code>```

Note that, you do not need subscript operator in your function call. Empty subscript operator is only valid when it is used as a parameter in function declaration/definition or when declared with an initializer list.

Title: Arrays and C syntax

Body:
I have some code that isn't compiling, and I have been wracking my brain to fix it, I'm just a beginner programmer, and I feel like I have my fundamentals down, but for some reason I am getting errors like I forgot to put a semicolon and stuff, not sure why, or where that is, so if someone would be willing to proofread my work it would be greatly appreciated.

The errors appear to be occurring at the end of each statement in the main program, and error codes indicate I am forgetting a semicolon but I think I have them all so I don't quite understand my error.

    #include <stdio.h>
    #include <stdlib.h>

    void printArrayValues(int array[], int num);

    void fillWithIndex(int array[], int num);

    int main(int argc, char * argv[])
    {
        int arr1[] = { 23, 21, 20, 27 };
        int arr2[] = { 5, 7, 9, 11, 13 };

            // Print the values in the first array, fill that array with
            // its indexes, and then print the values of the array
            // again.

            printArrayValues(arr1[], 4);
            fillWithIndex(arr1[], 4);
            printArrayValues(arr1[], 4);

            // Do similarly for the second array.

            printArrayValues(arr2[], 5);
            fillWithIndex(arr2[], 5);
            printArrayValues(arr2[], 5);

            return 0;
    }

    void printArrayValues(int array[], int num)

    {
        int i = 0;

        while (i < num)
        {
            printf("%d\n", array[i]);
            i++;
        }

        return;
    }

    void fillWithIndex(int array[], int num)
    {
        int i = 0;

        while (i < num)
        {
            array[i] = i;
            i++;
        }

        return;
    }

Body:
Array decays to pointer to its first element. First argument of both of your functions expects an argument of type int *. In your function calls you should pass the first argument like this

printArrayValues(arr1, 4);
fillWithIndex(arr1, 4);
printArrayValues(arr1, 4);

// Do similarly for the second array.

printArrayValues(arr2, 5);
fillWithIndex(arr2, 5);
printArrayValues(arr2, 5);

Note that, you do not need subscript operator in your function call. Empty subscript operator is only valid when it is used as a parameter in function declaration/definition or when declared with an initializer list.


问:
Trying to write a JSON to a file using JSON Spirit in C++
I am trying to write to a JSON to a file using JSON Spirit.

I am using the code similar to the examples given on the website to do this as follows:

```<code>json_spirit::Object emotion_json;
emotion_obj.push_back(json_spirit::Pair("Dominant emotion", "Joy"));

ofstream os("emotion_json.json");
json_spirit::write(emotion_obj, os);
os.close();
</code>```

I keep getting the error:

```<code>undefined reference to 'json_spirit::write(json_spirit::Value_impl<json_spirit::Config_vector<std::string> > const&, std::ostream&, int, unsigned int)'
</code>```

I tried different variations witin JSON Spirit to output the JSON to a file, but none of them seem to be working for me despite having the headers:

```<code>#include <json_spirit.h>
#include <json_spirit_writer_template.h>
#include <json_spirit_writer.h>
</code>```

Any idea what might be going on? Also, if there is a better, light-weight library to create JSON structures in C++, I am all ears. Thanks!

答:
Turn on the linking option:

```<code>-ljson_spirit
</code>```

If compiler cannot find json_spirit, use

```<code>-L /path/to/the/parent/folder/of/libjson_spirit.a
</code>```

before json_spirit and after the name of .cpp file.

If you cannot find any libjson_spirit.a, you should build the library.

Go to the folder json_spirit in the source code where you see file CMakeLists.txt.

In the command line type:

```<code>cmake .
make
</code>```

Then libjson_spirit.a will be created.

Body:
I am trying to write to a JSON to a file using JSON Spirit.

I am using the code similar to the examples given on the website to do this as follows:

json_spirit::Object emotion_json;
emotion_obj.push_back(json_spirit::Pair("Dominant emotion", "Joy"));

ofstream os("emotion_json.json");
json_spirit::write(emotion_obj, os);
os.close();

I keep getting the error:

undefined reference to 'json_spirit::write(json_spirit::Value_impl<json_spirit::Config_vector<std::string> > const&, std::ostream&, int, unsigned int)'

I tried different variations witin JSON Spirit to output the JSON to a file, but none of them seem to be working for me despite having the headers:

#include <json_spirit.h>
#include <json_spirit_writer_template.h>
#include <json_spirit_writer.h>

Any idea what might be going on? Also, if there is a better, light-weight library to create JSON structures in C++, I am all ears. Thanks!

Body:
Turn on the linking option:

-ljson_spirit

If compiler cannot find json_spirit, use

-L /path/to/the/parent/folder/of/libjson_spirit.a

before json_spirit and after the name of .cpp file.

If you cannot find any libjson_spirit.a, you should build the library.

Go to the folder json_spirit in the source code where you see file CMakeLists.txt.

In the command line type:

cmake .
make

Then libjson_spirit.a will be created.


问:
Test a controller in .Net Core always returns false?
I write the following XUnit test to test a .Net Core WebApi controller's action:

```<code>namespace VistaBest.XUnitTest.Api.Test
{
    public class Account_UnitTest
    {
        [Fact]
        public void ValidateUserTest()
        {
            const string username = "admin";
            const string password = "admin";
            var usersBusinessObjectMock = new Mock<IUsersBusinessObject>();
            usersBusinessObjectMock.Setup(service => service.ValidateUser(username, password)).Returns(() => true);
            var controller = new AccountController(usersBusinessObjectMock.Object);
            var actionResult = controller.ValidateUser(new LoginModel
            {
                Username = username,
                Password = password
            });
            var okObjectResult = Assert.IsType<OkObjectResult>(actionResult);
            var result = okObjectResult.Value as bool?;
            Assert.True(result);
        }
    }
}
</code>```

AccountController:

```<code>namespace VistaBest.Api.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IUsersBusinessObject _usersBusinessObject;
        public AccountController(IUsersBusinessObject usersBusinessObject)
        {
            _usersBusinessObject = usersBusinessObject;
        }

        [HttpPost]
        public IActionResult ValidateUser(LoginModel model)
        {
            if(!ModelState.IsValid) return BadRequest(ModelState);
            return Ok(_usersBusinessObject.ValidateUser(model.Username, model.Password.ToMd5Hash()));
        }
    }
}
</code>```

IUsersBusinessObject:

```<code>namespace VistaBest.Data.BusinessObjects
{
    public interface IUsersBusinessObject
    {
        bool ValidateUser(string username, string password);
        UserModel SelectByUsername(string username);
    }

    public class UsersBusinessObject : BaseBusinessObject, IUsersBusinessObject
    {
        public UsersBusinessObject(IDbConnection connection) : base(connection)
        {

        }

        private const string TableName = "Users";

        public bool ValidateUser(string username, string password)
        {
            var query = $"SELECT COUNT(*) FROM [{TableName}] WHERE UserName = @username and Password = @password";
            return DbConnection.QueryFirst<int>(query, new { username, password }) == 1;
        }
}
</code>```

As you see I said usersBusinessObjectMock must return true:

```<code>usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password))
    .Returns(() => true);
</code>```

But var result = okObjectResult.Value as bool?; is always false

What's wrong?

答:
After rechecking how the controller calls the validation method I realized that  the problem is that you are not configuring the mock correctly.

The controller is calling

```<code>_usersBusinessObject.ValidateUser(model.Username, model.Password.ToMd5Hash())
</code>```

Note the ToMd5Hash() being called on the password.

You however setup the mock like...

```<code>usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password))
    .Returns(() => true);
</code>```

See the problem?

The mock is expecting the raw password and not its hash, thus wont return true when passed the hashed password. This results in the action's object result always returning false because the mock always returns false. That method was hidden off screen so I did not notice it earlier.

So assuming ToMd5Hash() is some custom extension method,

you either setup the mock to expect the hashed password to match the method under test...

```<code>usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password.ToMd5Hash()))
    .Returns(() => true);
</code>```

or use the It.IsAny<>() methods to loosen the expectations of the mock...

```<code>usersBusinessObjectMock
    .Setup(service => service.ValidateUser(It.IsAny<string>(), It.IsAny<string>()))
    .Returns(() => true);
</code>```

so that is does not matter what values you pass to the mock, it will always return true

Body:
I write the following XUnit test to test a .Net Core WebApi controller's action:

namespace VistaBest.XUnitTest.Api.Test
{
    public class Account_UnitTest
    {
        [Fact]
        public void ValidateUserTest()
        {
            const string username = "admin";
            const string password = "admin";
            var usersBusinessObjectMock = new Mock<IUsersBusinessObject>();
            usersBusinessObjectMock.Setup(service => service.ValidateUser(username, password)).Returns(() => true);
            var controller = new AccountController(usersBusinessObjectMock.Object);
            var actionResult = controller.ValidateUser(new LoginModel
            {
                Username = username,
                Password = password
            });
            var okObjectResult = Assert.IsType<OkObjectResult>(actionResult);
            var result = okObjectResult.Value as bool?;
            Assert.True(result);
        }
    }
}

AccountController:

namespace VistaBest.Api.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IUsersBusinessObject _usersBusinessObject;
        public AccountController(IUsersBusinessObject usersBusinessObject)
        {
            _usersBusinessObject = usersBusinessObject;
        }

        [HttpPost]
        public IActionResult ValidateUser(LoginModel model)
        {
            if(!ModelState.IsValid) return BadRequest(ModelState);
            return Ok(_usersBusinessObject.ValidateUser(model.Username, model.Password.ToMd5Hash()));
        }
    }
}

IUsersBusinessObject:

namespace VistaBest.Data.BusinessObjects
{
    public interface IUsersBusinessObject
    {
        bool ValidateUser(string username, string password);
        UserModel SelectByUsername(string username);
    }

    public class UsersBusinessObject : BaseBusinessObject, IUsersBusinessObject
    {
        public UsersBusinessObject(IDbConnection connection) : base(connection)
        {

        }

        private const string TableName = "Users";

        public bool ValidateUser(string username, string password)
        {
            var query = $"SELECT COUNT(*) FROM [{TableName}] WHERE UserName = @username and Password = @password";
            return DbConnection.QueryFirst<int>(query, new { username, password }) == 1;
        }
}

As you see I said usersBusinessObjectMock must return true:

usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password))
    .Returns(() => true);

But var result = okObjectResult.Value as bool?; is always false

What's wrong?

Body:
After rechecking how the controller calls the validation method I realized that  the problem is that you are not configuring the mock correctly.

The controller is calling

_usersBusinessObject.ValidateUser(model.Username, model.Password.ToMd5Hash())

Note the ToMd5Hash() being called on the password.

You however setup the mock like...

usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password))
    .Returns(() => true);

See the problem?

The mock is expecting the raw password and not its hash, thus wont return true when passed the hashed password. This results in the action's object result always returning false because the mock always returns false. That method was hidden off screen so I did not notice it earlier.

So assuming ToMd5Hash() is some custom extension method,

you either setup the mock to expect the hashed password to match the method under test...

usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password.ToMd5Hash()))
    .Returns(() => true);

or use the It.IsAny<>() methods to loosen the expectations of the mock...

usersBusinessObjectMock
    .Setup(service => service.ValidateUser(It.IsAny<string>(), It.IsAny<string>()))
    .Returns(() => true);

so that is does not matter what values you pass to the mock, it will always return true


问:
Carousel images are not rotating in bootstrap css
I am trying to implement carousel in bootstrap CSS but the carousel is not rotating,I am using HTML images in the carousel,

Here is the code:

```<code>            <!--Indicators-->
            <ol class="carousel-indicators">
                <li class="active" data-target="#myCarousel" data-slide-to="0"></li>
                <li data-target="#myCarousel" data-slide-to="1"></li>
                <li data-target="#myCarousel" data-slide-to="2" ></li>
            </ol><!--End ordered list-->

            <!--Wrapper for slides-->
            <div class="carousel-inner">
                <div class="item active" id="slide1">
                    <img src="http://placehold.it/1200x500">
                    <div class="carousel-caption">
                        <h4>Bootstrap 3</h4>
                        <p>Learn how to build your first responsive website with the brand new Twiter Bootstrap3!</p>
                    </div><!--End carousel caption-->
                </div><!--End item-->

                <div class="item" id="slide2">
                    <img src="http://placehold.it/1200x500">
                    <div class="carousel-caption">
                        <h4>Learn to code a website in 4 hours!</h4>
                        <p>PSD to HTML & CSS3 is a popular Udemy course that has helped thousands of aspiring web designers launch their web design career.</p>
                    </div><!--End carousel caption-->
                </div><!--End item-->

                <div class="item" id="slide3">
                    <img src="http://placehold.it/1200x500">
                    <div class="carousel-caption">
                        <h4>Web Hosting 101</h4>
                        <p>Learn how to buy a perfect domain name and hosting package, and get your website live on the web with ease.</p>
                    </div><!--End carousel caption-->
                </div><!--End item-->
            </div><!--End carousel inner-->

            <!--carousal controls-->
        <a class="left carousel-control" data-slide="prev" href="#myCarousel"><span class="icon-prev"></span></a>
        <a class="right carousel-control" data-slide="next" href="#myCarousel"><span class="icon-next"></span></a>

        </div><!--End myCrousel-->'
</code>```

Where am i doing wrong??Please suggest...

Thanks,
Pranay

答:
It is worth noting for me, I was failing to link to the bootstrap.js files properly.  If you are simply using the examples in the 4.0 beta files from GetBootstrap.com you can likely use the following at the end of your file.

```<code><script src="assets/js/vendor/popper.min.js"></script>
<script src="dist/js/bootstrap.min.js"></script>
</code>```

If you are projecting low traffic and don't want to include the files directly in your project you can use the CDN.

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</code>```

Body:
I am trying to implement carousel in bootstrap CSS but the carousel is not rotating,I am using HTML images in the carousel,

Here is the code:

Bootstrap 3

Learn how to build your first responsive website with the brand new Twiter Bootstrap3!

Learn to code a website in 4 hours!

PSD to HTML & CSS3 is a popular Udemy course that has helped thousands of aspiring web designers launch their web design career.

Web Hosting 101

Learn how to buy a perfect domain name and hosting package, and get your website live on the web with ease.

'

Where am i doing wrong??Please suggest...

Thanks,
Pranay

Body:
It is worth noting for me, I was failing to link to the bootstrap.js files properly.  If you are simply using the examples in the 4.0 beta files from GetBootstrap.com you can likely use the following at the end of your file.

<script src="assets/js/vendor/popper.min.js"></script>
<script src="dist/js/bootstrap.min.js"></script>

If you are projecting low traffic and don't want to include the files directly in your project you can use the CDN.

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>


问:
Get/display individual fields from doc.data() , eg: display the (cost :) field in doc.data()
```<code>firestore.collection("products").where("Product", "==", inputx)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data());
        });
    })
</code>```

here is my database

答:
You're looking for the get(fieldPath) method on DocumentSnapshot:

```<code>doc.get('Cost');
</code>```

Body:
firestore.collection("products").where("Product", "==", inputx)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data());
        });
    })

here is my database

Body:
You're looking for the get(fieldPath) method on DocumentSnapshot:

doc.get('Cost');


问:
Is XML semi structured data?
Can somebody explain me why XML is an semi structured data? Why it cannot be a structured data?
If it is semi structure data , can you please explain me below XML example, so it would be very helpful.</p>

```<code><Node>
    <FirstName>VITTHAL</FirstName>
    <LastName>MUGULI</LastName>
</Node>
</code>```

答: Semi structure data is a set of documents on the web which contain hyperlinks to other document and it cannot be modeled in natural relational data model because the pattern of hyperlinks is not regular across documents.</p>

Title: Is XML semi structured data?

Body:
Can somebody explain me why XML is an semi structured data? Why it cannot be a structured data?
If it is semi structure data , can you please explain me below XML example, so it would be very helpful.

<Node>
    <FirstName>VITTHAL</FirstName>
    <LastName>MUGULI</LastName>
</Node>


问:
Pandas: replace records based on conditional test in column
I have unique records in a dataframe, with no duplicates, as determined by combination of values across several columns:

```<code>import pandas as pd
d = {'Alpha' : ['C', 'B', 'C','D', 'A', 'A'], 'Beta' : ['G', 'F', 'G', 'H', 'A', 'A'],'Year': ['Base', 88, 94, 22, 'Base', 66], 'Zulu' : [1, 2, -3, 4, 5, -3]}
df = pd.DataFrame(d)
</code>```

This gets us:

```<code>  Alpha Beta  Year  Zulu
0     C    G  Base     1
1     B    F    88     2
2     C    G    94    -3
3     D    H    22     4
4     A    A  Base     5
5     A    A    66    -4
</code>```

Index 0 is a near match with index 2, & index 4 is a near match with index 5, except that the 'Year' value for index 0 & index 4 is Base, and 'Zulu' value for index 2 & 5 are negative. I want to replace the negative 'Zulu' values in 2 & 5 with their corresponding Zulu values in index 0 & 4, without disrupting other rows. The output df would look like this:

```<code>  Alpha Beta  Year  Zulu
0     C    G  Base     1
1     B    F    88     2
2     C    G    94     1
3     D    H    22     4
4     A    A  Base     5
5     A    A    66     5
</code>```

I can easily start with a filter & deep copy to avoid slicing issues, & then a backup of original data:

```<code>df_sub = df[df.Zulu < 0].copy(deep=True)
df_sub['Zulu_backup'] = df_sub.Zulu
</code>```

I can then use df_sub to merge with the original:

```<code>df_result = pd.merge(df_sub, df, how='right')
</code>```

Resulting in:

```<code>Alpha Beta  Year    Zulu     Zulu_backup
0     C    G    94    -3         -3.0
1     A    A    66    -3         -3.0
2     C    G  Base     1          NaN
3     B    F    88     2          NaN
4     D    H    22     4          NaN
5     A    A  Base     5          NaN
</code>```

But I don't know where to go from here without messing up the dataframe's other rows. I have a rather convoluted script. I am guessing I could create a series and map it to the dataframe, but I'm at a loss as to how to do so. Iterating through this is not an option as I have millions of rows. Would appreciate any assistance.

答:
EDIT :</p>

```<code>df.Zulu=df.Zulu.mask(df.Zulu.lt(0))

df.Zulu=df.set_index(['Alpha','Beta']).Zulu.fillna(df.set_index(['Alpha','Beta']).dropna().Zulu).values
df
Out[89]:
  Alpha Beta  Year  Zulu
0     C    G  Base   1.0
1     B    F    88   2.0
2     C    G    94   1.0
3     D    H    22   4.0
4     A    A  Base   5.0
5     A    A    66   5.0
</code>```

Body:
I have unique records in a dataframe, with no duplicates, as determined by combination of values across several columns:

import pandas as pd
d = {'Alpha' : ['C', 'B', 'C','D', 'A', 'A'], 'Beta' : ['G', 'F', 'G', 'H', 'A', 'A'],'Year': ['Base', 88, 94, 22, 'Base', 66], 'Zulu' : [1, 2, -3, 4, 5, -3]}
df = pd.DataFrame(d)

This gets us:

  Alpha Beta  Year  Zulu
0     C    G  Base     1
1     B    F    88     2
2     C    G    94    -3
3     D    H    22     4
4     A    A  Base     5
5     A    A    66    -4

Index 0 is a near match with index 2, & index 4 is a near match with index 5, except that the 'Year' value for index 0 & index 4 is Base, and 'Zulu' value for index 2 & 5 are negative. I want to replace the negative 'Zulu' values in 2 & 5 with their corresponding Zulu values in index 0 & 4, without disrupting other rows. The output df would look like this:

  Alpha Beta  Year  Zulu
0     C    G  Base     1
1     B    F    88     2
2     C    G    94     1
3     D    H    22     4
4     A    A  Base     5
5     A    A    66     5

I can easily start with a filter & deep copy to avoid slicing issues, & then a backup of original data:

df_sub = df[df.Zulu < 0].copy(deep=True)
df_sub['Zulu_backup'] = df_sub.Zulu

I can then use df_sub to merge with the original:

df_result = pd.merge(df_sub, df, how='right')

Resulting in:

Alpha Beta  Year    Zulu     Zulu_backup
0     C    G    94    -3         -3.0
1     A    A    66    -3         -3.0
2     C    G  Base     1          NaN
3     B    F    88     2          NaN
4     D    H    22     4          NaN
5     A    A  Base     5          NaN

But I don't know where to go from here without messing up the dataframe's other rows. I have a rather convoluted script. I am guessing I could create a series and map it to the dataframe, but I'm at a loss as to how to do so. Iterating through this is not an option as I have millions of rows. Would appreciate any assistance.

Body:
EDIT :

df.Zulu=df.Zulu.mask(df.Zulu.lt(0))

df.Zulu=df.set_index(['Alpha','Beta']).Zulu.fillna(df.set_index(['Alpha','Beta']).dropna().Zulu).values
df
Out[89]:
  Alpha Beta  Year  Zulu
0     C    G  Base   1.0
1     B    F    88   2.0
2     C    G    94   1.0
3     D    H    22   4.0
4     A    A  Base   5.0
5     A    A    66   5.0


问:
iOS : How to do proper URL encoding?
I'm unable to open a URL into UIWebView so I've seached & found that I need to encode URL, so I tried to encode it but, I've facing problem in URL encoding : My URL is http://somedomain.com/data/Témp%20Page%20-%20Open.html (It's not real URL).

I'm concerned with %20 that I tried to replace using stringByReplacingOccuranceOfString:@"" withString:@"" , it give me the URL I wanted like http://somedomain.com/data/Témp Page - Open.html However its not opening in UIWebView but amazingly it opens in Safari & FireFox perfect. Even I open unencoded URL its automatically converts and open the page I'm looking for.

I've google for URL encoding & it points me to different results I already checked but no results help me out!! I tried different functions answers in different URL encoding question but it just changed all special characters and make my URL like, http%3A%2F%2Fsomedomain.com%2Fdata%2FT... which can't open in UIWebView and even in any browser.

It gives the following Error Log in UIWebView delegate

```<code>- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }
</code>```

Error Code : 101
   & Description : Error Domain=WebKitErrorDomain Code=101 "The operation couldn’t be completed. (WebKitErrorDomain error 101.)" UserInfo=0x6e4cf60 {}

答:
Swift 4.x

```<code>let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)
</code>```

Title: iOS : How to do proper URL encoding?

Body:
I'm unable to open a URL into UIWebView so I've seached & found that I need to encode URL, so I tried to encode it but, I've facing problem in URL encoding : My URL is http://somedomain.com/data/Témp%20Page%20-%20Open.html (It's not real URL).

I'm concerned with %20 that I tried to replace using stringByReplacingOccuranceOfString:@"" withString:@"" , it give me the URL I wanted like http://somedomain.com/data/Témp Page - Open.html However its not opening in UIWebView but amazingly it opens in Safari & FireFox perfect. Even I open unencoded URL its automatically converts and open the page I'm looking for.

I've google for URL encoding & it points me to different results I already checked but no results help me out!! I tried different functions answers in different URL encoding question but it just changed all special characters and make my URL like, http%3A%2F%2Fsomedomain.com%2Fdata%2FT... which can't open in UIWebView and even in any browser.

It gives the following Error Log in UIWebView delegate

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }

Error Code : 101
   & Description : Error Domain=WebKitErrorDomain Code=101 "The operation couldn’t be completed. (WebKitErrorDomain error 101.)" UserInfo=0x6e4cf60 {}

Body:
Swift 4.x

let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)