问:
SQL not working on c# but working in SQL Server Management Studio
Update should be updating the data in the confirm table with the given parameters. However no input gets updated/inputted despite there being no errors.
When the exact same query is inputted into the SQL Server Management Studio there is no errors and the rows are updated.

Why is the table not being updated?

There are 3 columns in the table - orderid (which is passed from another table) and then staffid and confirmed which should both be NULL - and are - until the rows are updated. orderid = int not null, staffid = int, confirmed = string.confirm database

The view is a left outer join, meaning that it shows the values that need to be update by the by.

[sql][2]

database diagram

Form

How can this be fixed, its been like this for two days.

```<code>  using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;

    namespace ComicBookShop
    {
        public partial class orders_confirm : Form
        {

            public orders_confirm()
            {
                InitializeComponent();
            }
            //database details
            string connString = "Data Source = BLAH BLAH BLAH";

            private void btnBack_Click(object sender, EventArgs e)
            {
                this.Hide();
                ManagmentMain fm = new ManagmentMain();
                fm.Show();
            }

            private void orders_confirm_Load(object sender, EventArgs e)
            {

                SqlConnection con = new SqlConnection(connString);
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM staff_view", con))
                    {
                        cmd.CommandType = CommandType.Text;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);

                                //Set AutoGenerateColumns False
                                dataGridView5.AutoGenerateColumns = true;

                                dataGridView5.DataSource = dt;

                            }
                        }
                    }

                    con.Close();
                }

            }
            private void btnUpdate_Click(object sender, EventArgs e)
            {
                if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
                {
                    MessageBox.Show("Please fill textboxes");
                    return;
                }
                //database details
                string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
                SqlConnection con = new SqlConnection(connString);
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    using (SqlCommand command = con.CreateCommand())
                    {
                        try
                        {

                            con.Open();
                            command.CommandText = "Update dbo.confirm set staffid=@staffid, confirmed=@confirmed where orderid =@orderid";

                            command.Parameters.AddWithValue("@orderid", txtorder.Text);
                            command.Parameters.AddWithValue("@staffid", txtstaff.Text);
                            command.Parameters.AddWithValue("@confirmed", txtConfirmed.Text);

                            command.ExecuteNonQuery();

                            con.Close();
                            MessageBox.Show("Updated");

                        }

                        catch (SqlException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }

            }
        }
    }
</code>```

this is the part of the code where the data should be inserted

```<code> private void btnUpdate_Click(object sender, EventArgs e)
            {
                if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
                {
                    MessageBox.Show("Please fill textboxes");
                    return;
                }
                //database details
                string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
                SqlConnection con = new SqlConnection(connString);
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    using (SqlCommand command = con.CreateCommand())
                    {
                        try
                        {

                            con.Open();
                            command.CommandText = "Update dbo.confirm set staffid=@staffid, confirmed=@confirmed where orderid =@orderid";

                            command.Parameters.AddWithValue("@orderid", txtorder.Text);
                            command.Parameters.AddWithValue("@staffid", txtstaff.Text);
                            command.Parameters.AddWithValue("@confirmed", txtConfirmed.Text);

                            command.ExecuteNonQuery();

                            con.Close();
                            MessageBox.Show("Updated");

                        }

                        catch (SqlException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
</code>```

答:
Try setting parameters with their corresponding data types:

```<code> command.Parameters.Add("orderid", SqlDbType.Int);
 command.Parameters["orderid"].Value = int.Parse(txtorder.Text);
</code>```

Do the same for staffid.

I think the issue is you are passing string where int is expected.

Body:
Update should be updating the data in the confirm table with the given parameters. However no input gets updated/inputted despite there being no errors.
When the exact same query is inputted into the SQL Server Management Studio there is no errors and the rows are updated.

Why is the table not being updated?

There are 3 columns in the table - orderid (which is passed from another table) and then staffid and confirmed which should both be NULL - and are - until the rows are updated. orderid = int not null, staffid = int, confirmed = string.confirm database

The view is a left outer join, meaning that it shows the values that need to be update by the by.

[sql][2]

database diagram

Form

How can this be fixed, its been like this for two days.

  using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;

    namespace ComicBookShop
    {
        public partial class orders_confirm : Form
        {

            public orders_confirm()
            {
                InitializeComponent();
            }
            //database details
            string connString = "Data Source = BLAH BLAH BLAH";

            private void btnBack_Click(object sender, EventArgs e)
            {
                this.Hide();
                ManagmentMain fm = new ManagmentMain();
                fm.Show();
            }

            private void orders_confirm_Load(object sender, EventArgs e)
            {

                SqlConnection con = new SqlConnection(connString);
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM staff_view", con))
                    {
                        cmd.CommandType = CommandType.Text;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);

                                //Set AutoGenerateColumns False
                                dataGridView5.AutoGenerateColumns = true;

                                dataGridView5.DataSource = dt;

                            }
                        }
                    }

                    con.Close();
                }

            }
            private void btnUpdate_Click(object sender, EventArgs e)
            {
                if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
                {
                    MessageBox.Show("Please fill textboxes");
                    return;
                }
                //database details
                string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
                SqlConnection con = new SqlConnection(connString);
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    using (SqlCommand command = con.CreateCommand())
                    {
                        try
                        {

                            con.Open();
                            command.CommandText = "Update dbo.confirm set staffid=@staffid, confirmed=@confirmed where orderid =@orderid";

                            command.Parameters.AddWithValue("@orderid", txtorder.Text);
                            command.Parameters.AddWithValue("@staffid", txtstaff.Text);
                            command.Parameters.AddWithValue("@confirmed", txtConfirmed.Text);

                            command.ExecuteNonQuery();

                            con.Close();
                            MessageBox.Show("Updated");

                        }

                        catch (SqlException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }

            }
        }
    }

this is the part of the code where the data should be inserted

 private void btnUpdate_Click(object sender, EventArgs e)
            {
                if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
                {
                    MessageBox.Show("Please fill textboxes");
                    return;
                }
                //database details
                string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
                SqlConnection con = new SqlConnection(connString);
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    using (SqlCommand command = con.CreateCommand())
                    {
                        try
                        {

                            con.Open();
                            command.CommandText = "Update dbo.confirm set staffid=@staffid, confirmed=@confirmed where orderid =@orderid";

                            command.Parameters.AddWithValue("@orderid", txtorder.Text);
                            command.Parameters.AddWithValue("@staffid", txtstaff.Text);
                            command.Parameters.AddWithValue("@confirmed", txtConfirmed.Text);

                            command.ExecuteNonQuery();

                            con.Close();
                            MessageBox.Show("Updated");

                        }

                        catch (SqlException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }

Body:
Try setting parameters with their corresponding data types:

 command.Parameters.Add("orderid", SqlDbType.Int);
 command.Parameters["orderid"].Value = int.Parse(txtorder.Text);

Do the same for staffid.

I think the issue is you are passing string where int is expected.


来源: stackexchange

问:
Direction Array: reducing complexity
I have a m*n matrix where every element is unique. From a given starting point I have to move to the smallest point(up, down, left, right)and then have to do the same process again. When all other surrounding point is greater than the existing one I have to stop and print the position from start. suppose I have a matrix(5*5)

```<code>1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
</code>```

and starting point is (2,2) then the output will be 13,8,3,2,1.
I have solved this problem my way, But the problem is its complexity. I do not think my solution is efficient. Can anyone suggest me any better solution?

N.B: Except scanner pkg, I am not allowed to import any other pkg. Here is my code:

```<code>import java.util.Scanner;
public class DirectionArray {
public static void main(String [] args) {
        Scanner in = new Scanner(System.in);
        int row = in.nextInt();
        int col = in.nextInt();
        int[][] ara = new int[row][col];
        int[] ara2 = new int[4];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                ara[i][j] = in.nextInt();
            }
        }
        System.out.println("Give starting point(x) ");
        int x= in.nextInt();
        System.out.println("Give starting point(y) ");
        int y= in.nextInt();
        int sx=x;
        int sy =y;
        int [] fx={+1,-1,0,0};
        int [] fy={0,0,+1,-1};
        int p=0;
        int l=0;
        int v=0;
        int r=0;
        int [] result=new int[row*col] ;
        int min=ara[x][y];
        boolean swap=true;
        for(int i=0;i<(row*col)-1;i++) {
            for (int k = 0; k < 4; k++) {
                int nx = x + fx[k];
                int ny = y + fy[k];

                if (nx >= 0 && nx < row && ny >= 0 && ny < col) {
                    if (min > ara[nx][ny]) {

                        ara2[p] = ara[nx][ny];
                        p++;

                    }

                }
}
            p=0;
            while(swap) {
                swap=false;
                r++;

                for (int q = 0; q < ara2.length-r; q++) {
                    if(ara2[q]>ara2[q+1]){
                    int temp = ara2[q];
                        ara2[q]=ara2[q+1];
                        ara2[q+1]=temp;
                        swap=true;
                    }
                }
            }
          for(int j=0;j<ara2.length;j++) {
                    if(ara2[j]!=0)
                    {
                        v=ara2[j];
                        result[l]=v;
                        l++;
                        break;
                    }
                }
                min=v;
            for(int o=0;o<ara2.length;o++) {
                ara2[o]=0;
            }
                for(int m=0;m<row;m++){
                    for(int n=0;n<col;n++){
                        if(ara[m][n]==v) {
                            x = m;
                            y = n;
                        }
                    }
                }
</code>```

答:
I think you need to split up your code in more methods. It would make it easier to read.

For example this is how I would reorganize it:

```<code>private static final int[][] COORDINATES_TO_TRY = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int row = in.nextInt();
    int col = in.nextInt();
    int[][] array = new int[row][col];
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            array[i][j] = in.nextInt();
        }
    }
    System.out.println("Give starting point(x) ");
    int x = in.nextInt();
    System.out.println("Give starting point(y) ");
    int y = in.nextInt();
    findMinimum(array, x, y);
    return;
}

private static int[] findMinimum(int[][] array, int x, int y) {
    for (int i = 0; true; i++) {
        if (i > 0) {
            System.out.print(",");
        }
        System.out.print(array[x][y]);
        int[] coordinates = findLocalMinimum(array, x, y);
        if (x == coordinates[0] && y == coordinates[1]) {
            return coordinates;
        }
        x = coordinates[0];
        y = coordinates[1];
    }
}

private static int[] findLocalMinimum(int[][] array, int x, int y) {
    int min = array[x][y];
    int minX = x;
    int minY = y;
    for (int[] coordinates : COORDINATES_TO_TRY) {
        int i = x + coordinates[0];
        int j = y + coordinates[1];
        if (i >= 0 && i < array.length && j >= 0 && j < array[i].length) {
            if (array[i][j] < min) {
                minX = i;
                minY = j;
                min = array[i][j];
            }
        }
    }
    return new int[]{minX, minY};
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Direction Array: reducing complexity

Body:
I have a m*n matrix where every element is unique. From a given starting point I have to move to the smallest point(up, down, left, right)and then have to do the same process again. When all other surrounding point is greater than the existing one I have to stop and print the position from start. suppose I have a matrix(5*5)

1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

and starting point is (2,2) then the output will be 13,8,3,2,1.
I have solved this problem my way, But the problem is its complexity. I do not think my solution is efficient. Can anyone suggest me any better solution?

N.B: Except scanner pkg, I am not allowed to import any other pkg. Here is my code:

import java.util.Scanner;
public class DirectionArray {
public static void main(String [] args) {
        Scanner in = new Scanner(System.in);
        int row = in.nextInt();
        int col = in.nextInt();
        int[][] ara = new int[row][col];
        int[] ara2 = new int[4];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                ara[i][j] = in.nextInt();
            }
        }
        System.out.println("Give starting point(x) ");
        int x= in.nextInt();
        System.out.println("Give starting point(y) ");
        int y= in.nextInt();
        int sx=x;
        int sy =y;
        int [] fx={+1,-1,0,0};
        int [] fy={0,0,+1,-1};
        int p=0;
        int l=0;
        int v=0;
        int r=0;
        int [] result=new int[row*col] ;
        int min=ara[x][y];
        boolean swap=true;
        for(int i=0;i<(row*col)-1;i++) {
            for (int k = 0; k < 4; k++) {
                int nx = x + fx[k];
                int ny = y + fy[k];

                if (nx >= 0 && nx < row && ny >= 0 && ny < col) {
                    if (min > ara[nx][ny]) {

                        ara2[p] = ara[nx][ny];
                        p++;

                    }

                }
}
            p=0;
            while(swap) {
                swap=false;
                r++;

                for (int q = 0; q < ara2.length-r; q++) {
                    if(ara2[q]>ara2[q+1]){
                    int temp = ara2[q];
                        ara2[q]=ara2[q+1];
                        ara2[q+1]=temp;
                        swap=true;
                    }
                }
            }
          for(int j=0;j<ara2.length;j++) {
                    if(ara2[j]!=0)
                    {
                        v=ara2[j];
                        result[l]=v;
                        l++;
                        break;
                    }
                }
                min=v;
            for(int o=0;o<ara2.length;o++) {
                ara2[o]=0;
            }
                for(int m=0;m<row;m++){
                    for(int n=0;n<col;n++){
                        if(ara[m][n]==v) {
                            x = m;
                            y = n;
                        }
                    }
                }

Body:
I think you need to split up your code in more methods. It would make it easier to read.

For example this is how I would reorganize it:

private static final int[][] COORDINATES_TO_TRY = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int row = in.nextInt();
    int col = in.nextInt();
    int[][] array = new int[row][col];
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            array[i][j] = in.nextInt();
        }
    }
    System.out.println("Give starting point(x) ");
    int x = in.nextInt();
    System.out.println("Give starting point(y) ");
    int y = in.nextInt();
    findMinimum(array, x, y);
    return;
}

private static int[] findMinimum(int[][] array, int x, int y) {
    for (int i = 0; true; i++) {
        if (i > 0) {
            System.out.print(",");
        }
        System.out.print(array[x][y]);
        int[] coordinates = findLocalMinimum(array, x, y);
        if (x == coordinates[0] && y == coordinates[1]) {
            return coordinates;
        }
        x = coordinates[0];
        y = coordinates[1];
    }
}

private static int[] findLocalMinimum(int[][] array, int x, int y) {
    int min = array[x][y];
    int minX = x;
    int minY = y;
    for (int[] coordinates : COORDINATES_TO_TRY) {
        int i = x + coordinates[0];
        int j = y + coordinates[1];
        if (i >= 0 && i < array.length && j >= 0 && j < array[i].length) {
            if (array[i][j] < min) {
                minX = i;
                minY = j;
                min = array[i][j];
            }
        }
    }
    return new int[]{minX, minY};
}


问:
What does "abstract over" mean?
Often in the Scala literature, I encounter the phrase "abstract over", but I don't understand the intent.  For example, Martin Odersky writes

You can pass methods (or "functions") as parameters, or you can abstract over them. You can specify types as parameters, or you can abstract over them.

As another example, in the "Deprecating the Observer Pattern" paper,

A consequence from our event streams being first-class values is that we can abstract over them.

I have read that first order generics "abstract over types", while monads "abstract over type constructors".  And we also see phrases like this in the Cake Pattern paper.  To quote one of many such examples:

Abstract type members provide flexible way to abstract over concrete types of components.

Even relevant stack overflow questions use this terminology.  "can't existentially abstract over parameterized type..."

So... what does "abstract over" actually mean?

答:
To a first approximation, being able to "abstract over" something means that instead of using that something directly, you can make a parameter of it, or otherwise use it "anonymously".

Scala allows you to abstract over types, by allowing classes, methods, and values to have type parameters, and values to have abstract (or anonymous) types.

Scala allows you to abstract over actions, by allowing methods to have function parameters.

Scala allows you to abstract over features, by allowing types to be defined structurally.

Scala allows you to abstract over type parameters, by allowing higher-order type parameters.

Scala allows you to abstract over data access patterns, by allowing you to create extractors.

Scala allows you to abstract over "things that can be used as something else", by allowing implicit conversions as parameters.  Haskell does similarly with type classes.

Scala doesn't (yet) allow you to abstract over classes.  You can't pass a class to something, and then use that class to create new objects.   Other languages do allow abstraction over classes.

("Monads abstract over type constructors" is only true in a very restrictive way.  Don't get hung up on it until you have your "Aha!  I understand monads!!" moment.)

The ability to abstract over some aspect of computation is basically what allows code reuse, and enables the creation of libraries of functionality.  Scala allows many more sorts of things to be abstracted over than more mainstream languages, and libraries in Scala can be correspondingly more powerful.

Title: What does "abstract over" mean?

ContentLicense: CC BY-SA 2.5


问:
How to read a .txt file for each int on a line & storing to array?

```<code>public class assignment2
{
    public static void main(String[] args) throws IOException
    {
        // TODO Auto-generated method stub
        FileInputStream fstream = new FileInputStream("assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console
            System.out.println (strLine);
            String[] numbers = strLine.split(" ");
            System.out.print(numbers[1]);
        }
        //Close the input stream
        br.close();
    }
}
</code>```

I expect that the code will print the String[] numbers as
1 0 10

I get this result 00371010

Please note that the input file is formatted as such:

1 0 10

2 0 9

3 3 5

4 7 4

5 10 6

6 10 7

答:
You need to modify the code by adding another loop like this:

```<code>public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    FileInputStream fstream = new FileInputStream("assignment2.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    String strLine;

    //Read File Line By Line
    while ((strLine = br.readLine()) != null){
        // Print the content on the console
        System.out.println (strLine);
        String[] numbers = strLine.split(" ");
        for (String num : numbers){
            System.out.print(num + " ");
        }
        System.out.println("\n");
    }
    //Close the input stream
    br.close();
}
</code>```

Because, numbers[1] will only print the value at index 1.

Body:
public class assignment2
{
    public static void main(String[] args) throws IOException
    {
        // TODO Auto-generated method stub
        FileInputStream fstream = new FileInputStream("assignment2.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // Print the content on the console
            System.out.println (strLine);
            String[] numbers = strLine.split(" ");
            System.out.print(numbers[1]);
        }
        //Close the input stream
        br.close();
    }
}

I expect that the code will print the String[] numbers as
1 0 10

I get this result 00371010

Please note that the input file is formatted as such:

1 0 10

2 0 9

3 3 5

4 7 4

5 10 6

6 10 7

Body:
You need to modify the code by adding another loop like this:

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    FileInputStream fstream = new FileInputStream("assignment2.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    String strLine;

    //Read File Line By Line
    while ((strLine = br.readLine()) != null){
        // Print the content on the console
        System.out.println (strLine);
        String[] numbers = strLine.split(" ");
        for (String num : numbers){
            System.out.print(num + " ");
        }
        System.out.println("\n");
    }
    //Close the input stream
    br.close();
}

Because, numbers[1] will only print the value at index 1.


问:
ReadFile in TextArea JAVA

I want the textarea show the content of a file txt. Here is my code, it just shows the last line of the text, I know the problem is ta1.settext(). Can someone pls give me some advice?

```<code>public void actionPerformed(ActionEvent arg0) {
    if(arg0.getSource() == btnOK) {
        String link = tf1.getText().toString();
        try(BufferedReader br = new BufferedReader(new FileReader(link)))
        {
            String line;
            while((line = br.readLine()) != null) {
                ta1.setText(line);
            }
            br.close();
        }
</code>```

all the line of the file

The last line

答:
you are resetting your TextArea text by the latest line read from your file. While your need is to append all the lines read and show them.</p>

```<code>while((line = br.readLine()) != null) {
      ta1.append(line);
}
</code>```

Title: ReadFile in TextArea JAVA

Body:
I want the textarea show the content of a file txt. Here is my code, it just shows the last line of the text, I know the problem is ta1.settext(). Can someone pls give me some advice?

public void actionPerformed(ActionEvent arg0) {
    if(arg0.getSource() == btnOK) {
        String link = tf1.getText().toString();
        try(BufferedReader br = new BufferedReader(new FileReader(link)))
        {
            String line;
            while((line = br.readLine()) != null) {
                ta1.setText(line);
            }
            br.close();
        }

all the line of the file

The last line

Body:
you are resetting your TextArea text by the latest line read from your file. While your need is to append all the lines read and show them.

while((line = br.readLine()) != null) {
      ta1.append(line);
}


问:
Can type constructors be aliased in the same way as types?
Consider the following:

```<code>module Module1 =

  type Foo = Bar | Baz

  type Lorem = {Ipsum: int}

module Module2 =

  type Foo = Module1.Foo
  type Lorem = Module1.Lorem

  let foo = Bar // Error: The value or constructor 'Bar' is not defined

  let lorem = {Ipsum = 2} // Error: The record label 'Ipsum' is not defined
</code>```

Is it possible to alias the types in a simple manner and still be able to actually construct them, without opening Module1?

Background: I am creating an app and a corresponding web API. They will talk to each other by serializing and deserializing POCOs (POFOs?) whose definition is available in a module (corresponding to Module1) in a project referenced by both the app and the web API. The API and the types are versioned, so I'd like to have a Types module (corresponding to Module2) in the app and web API where I simply alias the most recent versions of the API types (e.g. type Foo = Shared.V2.Foo), and then I use these aliases inside the app and API, because that means I don't need references to the specific version all over the app/API. (Please shoot me if this is a terrible idea.)

答:
Your type aliases are completely unused in your existing code. This works if you use them explicitly by qualifying those identifiers like this:</p>

```<code>let foo = Foo.Bar

let lorem = {Lorem.Ipsum = 2}
</code>```

Body:
Consider the following:

module Module1 =

  type Foo = Bar | Baz

  type Lorem = {Ipsum: int}

module Module2 =

  type Foo = Module1.Foo
  type Lorem = Module1.Lorem

  let foo = Bar // Error: The value or constructor 'Bar' is not defined

  let lorem = {Ipsum = 2} // Error: The record label 'Ipsum' is not defined

Is it possible to alias the types in a simple manner and still be able to actually construct them, without opening Module1?

Background: I am creating an app and a corresponding web API. They will talk to each other by serializing and deserializing POCOs (POFOs?) whose definition is available in a module (corresponding to Module1) in a project referenced by both the app and the web API. The API and the types are versioned, so I'd like to have a Types module (corresponding to Module2) in the app and web API where I simply alias the most recent versions of the API types (e.g. type Foo = Shared.V2.Foo), and then I use these aliases inside the app and API, because that means I don't need references to the specific version all over the app/API. (Please shoot me if this is a terrible idea.)

Body:
Your type aliases are completely unused in your existing code. This works if you use them explicitly by qualifying those identifiers like this:

let foo = Foo.Bar

let lorem = {Lorem.Ipsum = 2}


问:
Array objects values remove unwanted string
I have the following originaldata  which I would like to remove the div tags from the each objects inside it, leaving it with the content within the tags as the final result, see modifieddata.

What would be the best approach using javascript? filter and map? or something else.

```<code>originaldata = [{
        "name": "john",
        "content": "<div class="ExternalClass06EE5E42165840F48DFA193ACAD4F87A">aa</div>"
    },
    {
        "name": "mary",
        "content": "<div class="ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A">asd</div>"
    }
]

modifieddata = [{
        "name": "john",
        "content": "aa"
    },
    {
      "name": "mary",
      "content": "asd"
    }
]
</code>```

答:
here is a one liner( assuming you will only have letters inside the div tag)

```<code>originaldata.forEach( x => { x.content = x.content.match(/>(\w+?)</)[1] })
</code>```

arrays are reference type, so as object. So you can simply use forEach function to iterate over the array and use regex pattern />(\w+?)</ to match the content inside div tag.That will give you what you want.But be careful.It will change the original data source,in our case originaldata array.

Body:
I have the following originaldata  which I would like to remove the div tags from the each objects inside it, leaving it with the content within the tags as the final result, see modifieddata.

What would be the best approach using javascript? filter and map? or something else.

originaldata = [{
        "name": "john",
        "content": "
aa
"
    },
    {
        "name": "mary",
        "content": "
asd
"
    }
]

modifieddata = [{
        "name": "john",
        "content": "aa"
    },
    {
      "name": "mary",
      "content": "asd"
    }
]

Body:
here is a one liner( assuming you will only have letters inside the div tag)

originaldata.forEach( x => { x.content = x.content.match(/>(\w+?)</)[1] })

arrays are reference type, so as object. So you can simply use forEach function to iterate over the array and use regex pattern />(\w+?)</ to match the content inside div tag.That will give you what you want.But be careful.It will change the original data source,in our case originaldata array.


问:
Data load in Websphere commerce
We have a requirement to include plus sign in logonId column in out of the box dataloader scripts in Websphere commerce. Below is the error log which is observed while loading the csvs with plus sign in email id. I had tried with -DXmlValidation=false in the data load but did not help. Any pointers on how to load the same?</p>

```<code>==================================================================================
WebSphere Commerce Data Load
==================================================================================

Dec 3, 2017 12:10:41 AM com.ibm.commerce.foundation.dataload.DataLoaderMain logStartDate
INFO: Load started at: Sun Dec 03 00:10:41 GMT 2017
Dec 3, 2017 12:10:56 AM com.ibm.commerce.foundation.dataload.DataLoaderMain logInitTime
INFO: Initialization completed in 14.905 seconds.
Dec 3, 2017 12:10:56 AM com.ibm.commerce.foundation.dataload.DataLoaderMain execute
INFO:
Processing Person...
Dec 3, 2017 12:10:57 AM com.ibm.commerce.foundation.dataload.report.error.LoadItemErrorReport generateErrorLog
FINE:
----------------------------------------------------------------------------------
Error report for load item: Person.
----------------------------------------------------------------------------------

Dec 3, 2017 12:10:57 AM com.ibm.commerce.foundation.dataload.report.error.LoadItemErrorReport addReportDetails
FINE:

An exception was caught: com.ibm.commerce.member.dataload.exception.MemberDataLoadApplicationException: The value test+123@txtgmail.com of the LOGONID field is invalid.
Application message:
An error occurred while transforming the data object into physical objects.  Data Object: com.ibm.commerce.member.facade.datatypes.impl.PersonTypeImpl@72e972e9 (accountStatus: <unset>, passwordExpired: <unset>, profileType: <unset>, registrationApprovalStatus: null, registrationStatus: RegisteredPerson), Physical objects:
==================================================
Transformed Physical objects:
==================================================
==================================================

Exception message:
The value test+123@txtgmail.com of the LOGONID field is invalid.
</code>```

答: My understanding is this should work. You should open a PMR with IBM Support.</p>

Title: Data load in Websphere commerce

Body:
We have a requirement to include plus sign in logonId column in out of the box dataloader scripts in Websphere commerce. Below is the error log which is observed while loading the csvs with plus sign in email id. I had tried with -DXmlValidation=false in the data load but did not help. Any pointers on how to load the same?

==================================================================================
WebSphere Commerce Data Load
==================================================================================

Dec 3, 2017 12:10:41 AM com.ibm.commerce.foundation.dataload.DataLoaderMain logStartDate
INFO: Load started at: Sun Dec 03 00:10:41 GMT 2017
Dec 3, 2017 12:10:56 AM com.ibm.commerce.foundation.dataload.DataLoaderMain logInitTime
INFO: Initialization completed in 14.905 seconds.
Dec 3, 2017 12:10:56 AM com.ibm.commerce.foundation.dataload.DataLoaderMain execute
INFO:
Processing Person...
Dec 3, 2017 12:10:57 AM com.ibm.commerce.foundation.dataload.report.error.LoadItemErrorReport generateErrorLog
FINE:
----------------------------------------------------------------------------------
Error report for load item: Person.
----------------------------------------------------------------------------------

Dec 3, 2017 12:10:57 AM com.ibm.commerce.foundation.dataload.report.error.LoadItemErrorReport addReportDetails
FINE:

An exception was caught: com.ibm.commerce.member.dataload.exception.MemberDataLoadApplicationException: The value test+123@txtgmail.com of the LOGONID field is invalid.
Application message:
An error occurred while transforming the data object into physical objects.  Data Object: com.ibm.commerce.member.facade.datatypes.impl.PersonTypeImpl@72e972e9 (accountStatus: <unset>, passwordExpired: <unset>, profileType: <unset>, registrationApprovalStatus: null, registrationStatus: RegisteredPerson), Physical objects:
==================================================
Transformed Physical objects:
==================================================
==================================================

Exception message:
The value test+123@txtgmail.com of the LOGONID field is invalid.


问:
React: How to use same component twice in same page but loading one script tag for both just one time
I created a react component that I want to use twice(or more) inside my page, and I need to load a script tag for it inside the head of my page but just once! I mean even if I use the component twice or more in the page it should add the script tag just once in the head.
The Problem is that this script tag should be absolutely a part of the component and not statically inserted in the head of my page.

Can anyone help me to make the magic happens? Thanks a lot in advance!

答:
You can set the state of the parent component to keep in memory that the script is already added.</p>

```<code>if (!this.state.scriptAdded) {
   // Add script tag
   this.setState({ scriptAdded: true });
}
</code>```

Body:
You can set the state of the parent component to keep in memory that the script is already added.

if (!this.state.scriptAdded) {
   // Add script tag
   this.setState({ scriptAdded: true });
}


问:
Saving to database inside Constructor
I got a problem. I am building a budget app, so therefor i have created 2 classes called 'Year' and 'Month'

When my constructor for Year is called i want to create 12 objects of Month and add them to my SQLite database.

I set an instance of my database class as an paramter for the constructor.

Year class:

```<code>public class Year implements Serializable {

private int id;
private int year;
private Month[] months;
private List<Category> categories;

public Year(int year, MyDBHandler mdb) {
    this.id = mdb.getYearID();
    this.year = year;
    for(int i = 0; i > 12; i ++){
        Month mon = new Month(mdb.getMonthID(), i, this);
        mdb.addMonth(mon);
        months[i] = mon;
    }
    mdb.close();
}
</code>```

}

Month class:

```<code>public class Month implements Serializable{
private int id;
private String name;
private int number;
private Year year;
private List<Entry> entries;
private List<Category> categories;

public Month(int id, int nr, Year year) {
    this.id = id;
    String [] months = {"January", "February", "March", "April", "May", "June", "July", "August", "Septemper", "October", "November", "December"};
    this.name = months[nr];
    this.number = nr;
    this.year = year;
    categories = year.getCategories();
}
</code>```

}

Relevant methods from my DbHandler class

```<code>public void addMonth(Month month){
    ContentValues values = new ContentValues();
    values.put(COLUMN_MONTH_ID, month.getId());
    values.put(COLUMN_MONTH_NUMBER, month.getNumber());
    values.put(COLUMN_MONTH_YEAR_ID, month.getYear().getId());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_MONTH, null, values);
}

public ArrayList<Month> getMonths() {
    ArrayList<Month> list = new ArrayList<Month>();
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_MONTH + " WHERE 1";

    Cursor c = db.rawQuery(query, null);
    c.moveToFirst();

    while (!c.isAfterLast()) {
        if (c.getString(c.getColumnIndex(COLUMN_MONTH_NUMBER)) != null) {
            int x1 = c.getInt(c.getColumnIndex("_id"));
            int x2 = c.getInt(c.getColumnIndex("nr"));

            Month month = new Month(x1, x2, null);
            list.add(month);
            c.moveToNext();
        }
    }
    c.close();
    db.close();
    return list;
}
</code>```

The problem is that even though i can call create a year to the database, my database contains no Months

答:
This would be more suitable for a comment, but since I don't have the rep:

```<code>for(int i = 0; i > 12; i ++)
</code>```

should be

```<code>for (int i = 0; i < 12; i++)
</code>```

Title: Saving to database inside Constructor

Body:
I got a problem. I am building a budget app, so therefor i have created 2 classes called 'Year' and 'Month'

When my constructor for Year is called i want to create 12 objects of Month and add them to my SQLite database.

I set an instance of my database class as an paramter for the constructor.

Year class:

public class Year implements Serializable {

private int id;
private int year;
private Month[] months;
private List<Category> categories;

public Year(int year, MyDBHandler mdb) {
    this.id = mdb.getYearID();
    this.year = year;
    for(int i = 0; i > 12; i ++){
        Month mon = new Month(mdb.getMonthID(), i, this);
        mdb.addMonth(mon);
        months[i] = mon;
    }
    mdb.close();
}

}

Month class:

public class Month implements Serializable{
private int id;
private String name;
private int number;
private Year year;
private List<Entry> entries;
private List<Category> categories;

public Month(int id, int nr, Year year) {
    this.id = id;
    String [] months = {"January", "February", "March", "April", "May", "June", "July", "August", "Septemper", "October", "November", "December"};
    this.name = months[nr];
    this.number = nr;
    this.year = year;
    categories = year.getCategories();
}

}

Relevant methods from my DbHandler class

public void addMonth(Month month){
    ContentValues values = new ContentValues();
    values.put(COLUMN_MONTH_ID, month.getId());
    values.put(COLUMN_MONTH_NUMBER, month.getNumber());
    values.put(COLUMN_MONTH_YEAR_ID, month.getYear().getId());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_MONTH, null, values);
}

public ArrayList<Month> getMonths() {
    ArrayList<Month> list = new ArrayList<Month>();
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_MONTH + " WHERE 1";

    Cursor c = db.rawQuery(query, null);
    c.moveToFirst();

    while (!c.isAfterLast()) {
        if (c.getString(c.getColumnIndex(COLUMN_MONTH_NUMBER)) != null) {
            int x1 = c.getInt(c.getColumnIndex("_id"));
            int x2 = c.getInt(c.getColumnIndex("nr"));

            Month month = new Month(x1, x2, null);
            list.add(month);
            c.moveToNext();
        }
    }
    c.close();
    db.close();
    return list;
}

The problem is that even though i can call create a year to the database, my database contains no Months

Body:
This would be more suitable for a comment, but since I don't have the rep:

for(int i = 0; i > 12; i ++)

should be

for (int i = 0; i < 12; i++)


问:
Java Error "Exception in thread "main" java.util.InputMismatchException" On an Array program
I recently typed out this java program to accept ten areas and their pin-codes and then search to find a particular area and print out it's pin-code.
Here's the code from the program :

```<code>import java.util.Scanner;
public class Sal {

    public static void main (String args []){
        Scanner s=new Scanner(System.in);
        System.out.println("Enter 10 areas and their pincodes");
        String area[]=new String [10];
        int pincode[]=new int [10];
        String search;
        int chk=0;
        int p=0;

        for (int i=0;i<=9;i++){
            area[i]=s.nextLine();
            pincode[i]=s.nextInt();
        }

        System.out.println("Enter Search");
        search=s.nextLine();

        for (int j=0;j<=9;j++){
            if(search==area[j]){
                chk=1;
                j=p;
                break;
            }
        }

        if(chk==1){
            System.out.println("Search Found "+"Pincode : "+pincode[p] );
        } else {
            System.out.println("Search not Found");
        }
    }
}
</code>```

And after entering two areas I get this ERROR:

```<code>Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Sal.main(Sal.java:14)
</code>```

Can someone please tell me what I'm doing wrong! :/
Any help is appreciated.

答: I'm new to Programming. However, I faced the similar issue to over come while creating customers for bank (its just a practice problem). To overcome the problem I have created separate scanners for each input type & Closed all the scanners at the end of program. It worked.</p>

Body:
I recently typed out this java program to accept ten areas and their pin-codes and then search to find a particular area and print out it's pin-code.
Here's the code from the program :

import java.util.Scanner;
public class Sal {

    public static void main (String args []){
        Scanner s=new Scanner(System.in);
        System.out.println("Enter 10 areas and their pincodes");
        String area[]=new String [10];
        int pincode[]=new int [10];
        String search;
        int chk=0;
        int p=0;

        for (int i=0;i<=9;i++){
            area[i]=s.nextLine();
            pincode[i]=s.nextInt();
        }

        System.out.println("Enter Search");
        search=s.nextLine();

        for (int j=0;j<=9;j++){
            if(search==area[j]){
                chk=1;
                j=p;
                break;
            }
        }

        if(chk==1){
            System.out.println("Search Found "+"Pincode : "+pincode[p] );
        } else {
            System.out.println("Search not Found");
        }
    }
}

And after entering two areas I get this ERROR:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Sal.main(Sal.java:14)

Can someone please tell me what I'm doing wrong! :/
Any help is appreciated.


问:
Ways to get external data into own mongodb (different structures)?
I'm having an external Export of XML data which I want to have in my mongoDB. Because the data in the export doesnt fit my needs when it comes to the structure, I'd like to kind of "map" it.

Exmaple of kind of the data structure I'm getting from the XML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ogr:FeatureCollection
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation=""
     xmlns:ogr="http://ogr.maptools.org/"
     xmlns:gml="http://www.opengis.net/gml">
  <gml:boundedBy>
    <gml:Box>
      <gml:coord><gml:X>X.XXX</gml:X><gml:Y>Y.YYY</gml:Y></gml:coord>
      <gml:coord><gml:X>X.XXX</gml:X><gml:Y>Y.YYY</gml:Y></gml:coord>
    </gml:Box>
  </gml:boundedBy>
  <gml:featureMember>
    <ogr:POI_TypeXYZ fid="POI_XYZ">
      <ogr:geometryProperty><gml:Point srsName="XYZ"><gml:coordinates>SAMPLE_DATA</gml:coordinates></gml:Point></ogr:geometryProperty>
      <ogr:ID>SAMPLE_DATA</ogr:ID>
      <ogr:TITLE>SAMPLE_DATA</ogr:TITLE>
      <ogr:STREET>SAMPLE_DATA</ogr:STREET>
      <ogr:NUM>SAMPLE_DATA</ogr:NUM>
      <ogr:PHONE>SAMPLE_DATA</ogr:PHONE>
    </ogr:POI_TypeXYZ>
  </gml:featureMember>
  <gml:featureMember>
    <ogr:POI_TypeXYZ fid="POI_XYZ">
      <ogr:geometryProperty><gml:Point srsName="XYZ"><gml:coordinates>SAMPLE_DATA</gml:coordinates></gml:Point></ogr:geometryProperty>
      <ogr:ID>SAMPLE_DATA</ogr:ID>
      <ogr:TITLE>SAMPLE_DATA</ogr:TITLE>
      <ogr:STREET>SAMPLE_DATA</ogr:STREET>
      <ogr:NUM>SAMPLE_DATA</ogr:NUM>
      <ogr:PHONE>SAMPLE_DATA</ogr:PHONE>
    </ogr:POI_TypeXYZ>
  </gml:featureMember>
</ogr:FeatureCollection>
</code>```

And for example I'd rather have different names for the fields etc. and have full control over that data.

Are there any tools that could help? Or what is the general strategy to handle such things?

答:
It looks like a 3 step process:

Convert xml to JSON.

Change the name of the fields. refer here to know how to change the key of JSON object.(You have full control over data here)

Convert JSON object to BSON and store it into Mongodb.

import json

data = json.loads(document)

mongocollection.insert(data)

Body:
I'm having an external Export of XML data which I want to have in my mongoDB. Because the data in the export doesnt fit my needs when it comes to the structure, I'd like to kind of "map" it.

Exmaple of kind of the data structure I'm getting from the XML:

<?xml version="1.0" encoding="utf-8" ?>
<ogr:FeatureCollection
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation=""
     xmlns:ogr="http://ogr.maptools.org/"
     xmlns:gml="http://www.opengis.net/gml">
  <gml:boundedBy>
    <gml:Box>
      <gml:coord><gml:X>X.XXX</gml:X><gml:Y>Y.YYY</gml:Y></gml:coord>
      <gml:coord><gml:X>X.XXX</gml:X><gml:Y>Y.YYY</gml:Y></gml:coord>
    </gml:Box>
  </gml:boundedBy>
  <gml:featureMember>
    <ogr:POI_TypeXYZ fid="POI_XYZ">
      <ogr:geometryProperty><gml:Point srsName="XYZ"><gml:coordinates>SAMPLE_DATA</gml:coordinates></gml:Point></ogr:geometryProperty>
      <ogr:ID>SAMPLE_DATA</ogr:ID>
      <ogr:TITLE>SAMPLE_DATA</ogr:TITLE>
      <ogr:STREET>SAMPLE_DATA</ogr:STREET>
      <ogr:NUM>SAMPLE_DATA</ogr:NUM>
      <ogr:PHONE>SAMPLE_DATA</ogr:PHONE>
    </ogr:POI_TypeXYZ>
  </gml:featureMember>
  <gml:featureMember>
    <ogr:POI_TypeXYZ fid="POI_XYZ">
      <ogr:geometryProperty><gml:Point srsName="XYZ"><gml:coordinates>SAMPLE_DATA</gml:coordinates></gml:Point></ogr:geometryProperty>
      <ogr:ID>SAMPLE_DATA</ogr:ID>
      <ogr:TITLE>SAMPLE_DATA</ogr:TITLE>
      <ogr:STREET>SAMPLE_DATA</ogr:STREET>
      <ogr:NUM>SAMPLE_DATA</ogr:NUM>
      <ogr:PHONE>SAMPLE_DATA</ogr:PHONE>
    </ogr:POI_TypeXYZ>
  </gml:featureMember>
</ogr:FeatureCollection>

And for example I'd rather have different names for the fields etc. and have full control over that data.

Are there any tools that could help? Or what is the general strategy to handle such things?


问:
Position child div to the left of parent div?
I have an image that has a width of 50% and a div with text that is 65% because I want the heading inside the div to overlap the image. But, the problem is that I don't want the other content inside the div to overlap the image - just the heading. I want the text and the button to be next to the image not on top of it.
But I can't seem to figure it out.

Here's a Codepen: https://codepen.io/tayanderson/pen/EbJZxy

```<code>.project {
    height: 75vh;
    margin: 15em 0;
    position: relative;

    .project-info {
        z-index: 100;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: absolute;
        width: 65%;
        height: 100%;
        right: 0;
        h2 {
            text-transform: initial;
            color: #eee;
        }
        p {
            font-weight: 300;
            color: #ccc;
            margin: 40px 0;
        }
        .project-desc {
            width: 70%;
            .button {display:inline-block;}
        }
    }

    .project-img {
        background-size: cover;
        background-position: center;
        height: 100%;
        -webkit-filter: grayscale(100%) brightness(50%);
        filter: grayscale(100%) brightness(50%);
        width: 51.3%;
    }

    a {text-decoration:none;
        color: #fff;}
    @media only screen and (max-width: 768px) {
        .project-info, .project-img {
            width: 100%;
        }
        .project-info {
            left: 0;
            padding: 0 20px;
            .project-desc>*{
                width: 100% !important;
                float: left !important;
            }
            p {display: none;}
        }
    }
}
</code>```

答:
I think I understand what you are describing. Instead of using the percentages to position the items use position: relative instead and float the image (remember to put it first in the flow).

Check this out:
https://codepen.io/alexplummer/pen/eeoRmN

```<code>.project-info {
    display: inline-block;
    width: calc(50% - 10px);
    height: 100%;
    padding-left: 10px;
    ...
}
.project-img {
    width: 50%;
    float: left;
    ...
}
</code>```

Body:
I have an image that has a width of 50% and a div with text that is 65% because I want the heading inside the div to overlap the image. But, the problem is that I don't want the other content inside the div to overlap the image - just the heading. I want the text and the button to be next to the image not on top of it.
But I can't seem to figure it out.

Here's a Codepen: https://codepen.io/tayanderson/pen/EbJZxy

.project {
    height: 75vh;
    margin: 15em 0;
    position: relative;

    .project-info {
        z-index: 100;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: absolute;
        width: 65%;
        height: 100%;
        right: 0;
        h2 {
            text-transform: initial;
            color: #eee;
        }
        p {
            font-weight: 300;
            color: #ccc;
            margin: 40px 0;
        }
        .project-desc {
            width: 70%;
            .button {display:inline-block;}
        }
    }

    .project-img {
        background-size: cover;
        background-position: center;
        height: 100%;
        -webkit-filter: grayscale(100%) brightness(50%);
        filter: grayscale(100%) brightness(50%);
        width: 51.3%;
    }

    a {text-decoration:none;
        color: #fff;}
    @media only screen and (max-width: 768px) {
        .project-info, .project-img {
            width: 100%;
        }
        .project-info {
            left: 0;
            padding: 0 20px;
            .project-desc>*{
                width: 100% !important;
                float: left !important;
            }
            p {display: none;}
        }
    }
}

Body:
I think I understand what you are describing. Instead of using the percentages to position the items use position: relative instead and float the image (remember to put it first in the flow).

Check this out:
https://codepen.io/alexplummer/pen/eeoRmN

.project-info {
    display: inline-block;
    width: calc(50% - 10px);
    height: 100%;
    padding-left: 10px;
    ...
}
.project-img {
    width: 50%;
    float: left;
    ...
}


问:
mediasoup - miss match between PayloadTypes
I'm trying to use mediasoup to forward RTP streams with room.createRtpStreamer

my problem is that the payload type (for OPUS) I get from producer.rtpParameters.codecs[i].payloadType is 111,

while the one I get on the actual RTP packets is 100 (seen on Wireshark)

I tried to set preferredPayloadType in my server's config, but it seems to make no difference.

Note:
if I hardcode 100 as the Payload Type for the OPUS stream I can view/hear the stream using FFPlay

I'm using Chrome 55 (latest) and mediasoup 2.0.5 (latest)

any help will be appreciated.

答:
The Producer has the RTP parameters decided by the client (browser), so the PT of OPUS is 111 (the default value generated by Chrome).

But, once in mediasoup server, the Consumers associated to that Producer use the RTP parameters given during the room creation. So, if the codecs given to room = new server.Room(codecs) [1] have a preferredPayloadType field, that will be used within the Consumers (otherwise it will be randomly chosen by the server).

So, when you call room.createRtpStreamer() you provide a Producer, and the generated RtpStreamer [2] has an associated Consumer and PlainRtpTransport. So, you should read the rtpStreamer.consumer.rtpParameters rather than the producer's ones.

[1] https://mediasoup.org/documentation/mediasoup/api/#server-Room

[2] https://mediasoup.org/documentation/mediasoup/api/#RtpStreamer


问:
How can I avoid duplicate rows from SQL statement?
My problem is, that the following SQL query returns duplicate rows:

```<code>select
inv.i4201 as pmid,
inv.i4235 as calPlace,
inv.i4204 as device,
inv.i4203 as type,
inv.i4202 as manufacturer,
inv.i4206 as serialNumber,
cal.c2323 as condition,
inv.i4299 as availability,
inv.i4236 as dateRegistration,
max(cal.c2301) as dateCalibration,
inv.i4229 as interval,
max(cal.c2303) as dateExpiry,
inv.i4228 as intervallType,
loc.l2803 as costCenter,
inv.i4242 as location,
cust.k4601 as CustomerNumber,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
calPlace,
device,
type,
manufacturer,
serialNumber,
condition,
availability,
dateRegistration,
interval,
intervallType,
costCenter,
location,
CustomerNumber,
CustomerName

order by pmid;
</code>```

What do I do to get just one row for each pmid with the latest dateCalibration and/or dateExpiry?

答:
Please try this.</p>

```<code>select
inv.i4201 as pmid,
max(cal.c2301) as dateCalibration,
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid
order by pmid;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My problem is, that the following SQL query returns duplicate rows:

select
inv.i4201 as pmid,
inv.i4235 as calPlace,
inv.i4204 as device,
inv.i4203 as type,
inv.i4202 as manufacturer,
inv.i4206 as serialNumber,
cal.c2323 as condition,
inv.i4299 as availability,
inv.i4236 as dateRegistration,
max(cal.c2301) as dateCalibration,
inv.i4229 as interval,
max(cal.c2303) as dateExpiry,
inv.i4228 as intervallType,
loc.l2803 as costCenter,
inv.i4242 as location,
cust.k4601 as CustomerNumber,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
calPlace,
device,
type,
manufacturer,
serialNumber,
condition,
availability,
dateRegistration,
interval,
intervallType,
costCenter,
location,
CustomerNumber,
CustomerName

order by pmid;

What do I do to get just one row for each pmid with the latest dateCalibration and/or dateExpiry?

Body:
Please try this.

select
inv.i4201 as pmid,
max(cal.c2301) as dateCalibration,
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid
order by pmid;


问:
Cheapest way to send SMS for number verification?
My application needs to verify phone numbers that are provided by the user. What is the absolute cheapest way to send an SMS to a phone? Which company/API should I go to? I'm not looking for a hack solution to send out 10 SMS a month kind of thing, I need to roll this out for a company that will be sending mass amount of verifications. But they want to do it at the lowest cost. (Each user will only need to verify once)

Sorry forgot mention the SMS needs to be international

答:
The absolute cheapest way (I can think of) is set up a system yourself.

By a contract to some cell phone provider and hook this up to your linux computer.

http://www.dealextreme.com/details.dx/sku.12057

Here is a thread discussing the set up process on linux.
It's not a walk in the park but it is cheap.

https://web.archive.org/web/20100130041340/http://www.dealextreme.com/forums/Default.dx/sku.12057~threadid.88670


问:
How can I create a map from object properties?
I get an object via some 3rd party api. I use a wrapper function to get it and then return a map from its properties:

```<code>wrapperFunc() {
    def myObj = someapi.getblah().getSomeObect()
    return [
        aaa: myObj.aaa,
        bbb: myObj.bbb,
        ccc: myObj.ccc
    ]
}
</code>```

Now I could manually go through EVERY property in the object like this, but is there an elegant groovy feature to dynamically build a map from the object's properties?

答:
const obj = { foo: 'bar', baz: 42 };
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baenter code herez: 42 }

Body:
I get an object via some 3rd party api. I use a wrapper function to get it and then return a map from its properties:

wrapperFunc() {
    def myObj = someapi.getblah().getSomeObect()
    return [
        aaa: myObj.aaa,
        bbb: myObj.bbb,
        ccc: myObj.ccc
    ]
}

Now I could manually go through EVERY property in the object like this, but is there an elegant groovy feature to dynamically build a map from the object's properties?


问:
Combine two collections with predicate using Stream API
I have two collections of type Entity.

```<code>class Entity {
    long id;
    // other fields
}

Collection<Entity> first = ...
Collection<Entity> second = ...
</code>```

I need to combine them in a such way that all elements in first should be replaced by elements from second if their ids are equal.

So, e.g if first contains [{"id": 1}, {"id": 2}, {"id": 3}] and second contains [{"id": 3}, {"id": 4}, {"id": 5}]

the result should be like this: [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}] where {"id": 3} from second replaced {"id": 3} from first.

Is there a way how to implement it in a Java 8 way, using Stream API.

答:
While it is possible to do the entire operation with one stream operation, the result would not be very efficient due to the repeated iteration over the collections. It’s strongly recommended to use two operations here

```<code>Map<Long,Entity> secondById = second.stream()
    .collect(Collectors.toMap(Entity::getId, Function.identity()));

Collection<Entity> result = first.stream()
    .map(e -> secondById.getOrDefault(e.getId(), e))
    .collect(Collectors.toList());
</code>```

Note that I took your task description “elements in first should be replaced by elements from second if their ids are equal” literally, e.g. it will not insert elements from the second not having a matching element in first. If first has a defined encounter order, it will be retained.

Note that if first is a mutable list, you could replace the elements in-place:

```<code>List<Entity> first = ...
Collection<Entity> second = ...

Map<Long,Entity> secondById = second.stream()
    .collect(Collectors.toMap(Entity::getId, Function.identity()));

first.replaceAll(e -> secondById.getOrDefault(e.getId(), e));
</code>```

Changing it to not just replace elements of first, but add all elements of second is not so hard:

```<code>Map<Long,Entity> secondById = second.stream()
    .collect(Collectors.toMap(Entity::getId, Function.identity()));

Collection<Entity> result = Stream.concat(
    first.stream().filter(e -> !secondById.containsKey(e.getId())),
    second.stream()
  ).collect(Collectors.toList());
</code>```

Body:
I have two collections of type Entity.

class Entity {
    long id;
    // other fields
}

Collection<Entity> first = ...
Collection<Entity> second = ...

I need to combine them in a such way that all elements in first should be replaced by elements from second if their ids are equal.

So, e.g if first contains [{"id": 1}, {"id": 2}, {"id": 3}] and second contains [{"id": 3}, {"id": 4}, {"id": 5}]

the result should be like this: [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}] where {"id": 3} from second replaced {"id": 3} from first.

Is there a way how to implement it in a Java 8 way, using Stream API.

Body:
While it is possible to do the entire operation with one stream operation, the result would not be very efficient due to the repeated iteration over the collections. It’s strongly recommended to use two operations here

Map<Long,Entity> secondById = second.stream()
    .collect(Collectors.toMap(Entity::getId, Function.identity()));

Collection<Entity> result = first.stream()
    .map(e -> secondById.getOrDefault(e.getId(), e))
    .collect(Collectors.toList());

Note that I took your task description “elements in first should be replaced by elements from second if their ids are equal” literally, e.g. it will not insert elements from the second not having a matching element in first. If first has a defined encounter order, it will be retained.

Note that if first is a mutable list, you could replace the elements in-place:

List<Entity> first = ...
Collection<Entity> second = ...

Map<Long,Entity> secondById = second.stream()
    .collect(Collectors.toMap(Entity::getId, Function.identity()));

first.replaceAll(e -> secondById.getOrDefault(e.getId(), e));

Changing it to not just replace elements of first, but add all elements of second is not so hard:

Map<Long,Entity> secondById = second.stream()
    .collect(Collectors.toMap(Entity::getId, Function.identity()));

Collection<Entity> result = Stream.concat(
    first.stream().filter(e -> !secondById.containsKey(e.getId())),
    second.stream()
  ).collect(Collectors.toList());


问:
Load ngFor inside insertAdjacentHTML
I am attaching element inside template dynamically by user click, this way:

```<code>this.optionValue = [];

youClickMe(){
  var moreput = '';
      moreput += '<select">';
        moreput += '<option *ngFor="let lup of optionValue">{{lup.name}}</option>';
      moreput += '</select>';
  var pElement = document.querySelector('.somewhereyoubelong');
      pElement.insertAdjacentHTML('beforeend', moreput);
}
</code>```

However the {{lup.name}} doesn't print the actual value but as how it is typed there. How to make it works? Anybody?

UPDATE:

I've tried with this way, but still it's said that

```<code>const templating = '<p *ngFor="let sizeCat of sizeCategoryBySubCategory" [value]="sizeCat.id">{{sizeCat.name}}</p>';

const tmpCmp = Component({template: templating})(class {});
const tmpModule = NgModule({declarations: [tmpCmp]})(class {});

this._compiler.compileModuleAndAllComponentsAsync(tmpModule).then((factories) => {
  const f = factories.componentFactories[0];
  const cmpRef = f.create(this._injector, [], null, this._m);

  //cmpRef.instance.testText = 'B component';
  cmpRef.instance.sizeCategoryBySubCategory = [
    { id:1, name: 'a'},
    { id:2, name: 'b'},
  ];

  this._container.insert(cmpRef.hostView);
});
</code>```

Property binding ngForOf not used by any directive on an embedded template

答:
Angular doesn't process Angular specific markup like matching component or directive selectors or bindings for dynamically added HTML.

Angular generates code for these things when it compiles components.
What is not in a components template when the component is compiled, is completely ignored by Angular.

What you can do is to dynamically create and compile Angular components at runtime. For more details see How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

Title: Load ngFor inside insertAdjacentHTML

Body:
I am attaching element inside template dynamically by user click, this way:

this.optionValue = [];

youClickMe(){
  var moreput = '';
      moreput += '<select">';
        moreput += '<option *ngFor="let lup of optionValue">{{lup.name}}</option>';
      moreput += '</select>';
  var pElement = document.querySelector('.somewhereyoubelong');
      pElement.insertAdjacentHTML('beforeend', moreput);
}

However the {{lup.name}} doesn't print the actual value but as how it is typed there. How to make it works? Anybody?

UPDATE:

I've tried with this way, but still it's said that

const templating = '
{{sizeCat.name}}
';

const tmpCmp = Component({template: templating})(class {});
const tmpModule = NgModule({declarations: [tmpCmp]})(class {});

this._compiler.compileModuleAndAllComponentsAsync(tmpModule).then((factories) => {
  const f = factories.componentFactories[0];
  const cmpRef = f.create(this._injector, [], null, this._m);

  //cmpRef.instance.testText = 'B component';
  cmpRef.instance.sizeCategoryBySubCategory = [
    { id:1, name: 'a'},
    { id:2, name: 'b'},
  ];

  this._container.insert(cmpRef.hostView);
});

Property binding ngForOf not used by any directive on an embedded template


问:
PrimeNG select datatable cell
I am working on a project using Angular 4 and PrimeNG where I need to be able to double click on a cell, selected it and open a dialog to do some modifications on the cell's underlying data.

As far as I can see from the documentation, currently there is no way to accomplish this.  What is the best way to handle this situation?

Thanks.

答:
So after some playing around I came up with a solution, which being far from perfect serves the purpose while we wait for the folks from PrimeNG (which I love, btw) to include this functionality.

The first issue was to determine which cell the user double-clicked on.  I did that by having all column's templates in a div which I can get a reference to:

            <ng-template let-col let-data="rowData" pTemplate="body">

            </ng-template>

```
</div>
</div>
</p>

<p>All columns I am interested in handling on double click are wrapped in the div with class cell-content.  Also notice the id attribute.  It is set to match the field.  Then in the onRowDblclick event:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>editTemplate(e: any) {
        let target = e.originalEvent.toElement.closest('div.cell-content');
        if (target && target.id) {
            let td = target.closest('td');
            if (td) {
                td.style.backgroundColor = 'darkorange';
                td.style.color = 'white';
            }

            let fieldValue = e.data[target.id];
            //do something with this data
        }
    }</code>```

The key here is the id attribute.  Once we have that now we know which cell was clicked and we can proceed to do what we need to do.  Also notice that I get a reference of the parent TD element and set the background and the color of the cell.  Once you are finished working with it, you can clear the formatting to go back to normal.

You can also use the onRowClick event to clear the selection like so:

    clearSelection(e: any) {
        let target = e.originalEvent.toElement.closest('div.cell-content');
        if (target && target.id) {
            let td = target.closest('td');
            if (td) {
                td.style.backgroundColor = 'white';
                td.style.color = 'black';
            }
        }
    }```

I know manipulating the DOM directly is not the way to go, but until we get the new version of PrimeNG that includes this functionality, this will do, at least for me.

Please let me know if you have a better way of doing this.

Title: PrimeNG select datatable cell

Body:
So after some playing around I came up with a solution, which being far from perfect serves the purpose while we wait for the folks from PrimeNG (which I love, btw) to include this functionality.

The first issue was to determine which cell the user double-clicked on.  I did that by having all column's templates in a div which I can get a reference to:

<p-dataTable #grd [value]="view"
               (onRowDblclick)="editTemplate($event)"
               (onRowClick)="clearSelection($event)">
        <p-column field="SomeFieldName" header="Header" [editable]="false">
            <ng-template let-col let-data="rowData" pTemplate="body">
                <div [id]="col.field" class="cell-content">
                    <div [innerHTML]="data[col.field]" class="center-parent-screen"></div>
                </div>
            </ng-template>
        </p-column>

All columns I am interested in handling on double click are wrapped in the div with class cell-content.  Also notice the id attribute.  It is set to match the field.  Then in the onRowDblclick event:

editTemplate(e: any) {
        let target = e.originalEvent.toElement.closest('div.cell-content');
        if (target && target.id) {
            let td = target.closest('td');
            if (td) {
                td.style.backgroundColor = 'darkorange';
                td.style.color = 'white';
            }

            let fieldValue = e.data[target.id];
            //do something with this data
        }
    }

The key here is the id attribute.  Once we have that now we know which cell was clicked and we can proceed to do what we need to do.  Also notice that I get a reference of the parent TD element and set the background and the color of the cell.  Once you are finished working with it, you can clear the formatting to go back to normal.

You can also use the onRowClick event to clear the selection like so:

    clearSelection(e: any) {
        let target = e.originalEvent.toElement.closest('div.cell-content');
        if (target && target.id) {
            let td = target.closest('td');
            if (td) {
                td.style.backgroundColor = 'white';
                td.style.color = 'black';
            }
        }
    }

I know manipulating the DOM directly is not the way to go, but until we get the new version of PrimeNG that includes this functionality, this will do, at least for me.

Please let me know if you have a better way of doing this.


问:
"Source" VsDevCmd.bat from Cygwin
So VsDevCmd.bat is a nifty script that sets environment variables for Visual Studio tools:

'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat'

I am using Visual Studio tools cl, link, etc. from Cygwin. How can I use that script to set all the same environment variable without reinventing the script in bash?

I can run the batch script from cmd shell then launch bash, but this is unsatisfactory—I need to initiate the process of "sourcing" the batch file from within Cygwin.

答:
I found that all you need is the path.

Run VsDevCmd.bat from DOS, then pipe out SET to a file (SET > c:\temp\set.txt)

From that file extract the PATH and convert it to Linux format - C:\Program Files becomes /cygdrive/c/Program Files and the \ all become /. The replace the ; with :.

Then edit your "${HOME}/.bashrc" file - append the above to the PATH - don't forget to add a : to the end of the original path.

My "${HOME}/.bashrc" now says the following - but copy it at your own risk.

export PATH="/c/bin:/usr/local/bin:/usr/bin:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/VC/Tools/MSVC/14.11.25503/bin/HostX86/x86:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/IDE/VC/VCPackages:/cygdrive/c/Program Files/Microsoft SDKs/TypeScript/2.3:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/IDE/CommonExtensions/Microsoft/TestWindow:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/IDE/CommonExtensions/Microsoft/TeamFoundation/Team Explorer:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/MSBuild/15.0/bin/Roslyn:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Team Tools/Performance Tools:/cygdrive/c/Program Files/HTML Help Workshop:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional//MSBuild/15.0/bin:C:/Windows/Microsoft.NET/Framework/v4.0.30319:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/IDE/:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/Tools/:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/VC/Tools/MSVC/14.11.25503/bin/HostX86/x86:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/IDE/VC/VCPackages:/cygdrive/c/Program Files/Microsoft SDKs/TypeScript/2.3:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/IDE/CommonExtensions/Microsoft/TestWindow:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/IDE/CommonExtensions/Microsoft/TeamFoundation/Team Explorer:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/MSBuild/15.0/bin/Roslyn:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Team Tools/Performance Tools:/cygdrive/c/Program Files/HTML Help Workshop:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional//MSBuild/15.0/bin:C:/Windows/Microsoft.NET/Framework/v4.0.30319:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/IDE/:/cygdrive/c/Program Files/Microsoft Visual Studio/2017/Professional/Common7/Tools/:/cygdrive/c/Program Files/Windows Kits/8.0/bin/x86:/cygdrive/c/Program Files/Microsoft SDKs/F#/3.0/Framework/v4.0/:C:/Windows/Microsoft.NET/Framework/v4.0.30319:/cygdrive/c/Program Files/CMake/bin:$PATH:$HOME/bin"

Title: "Source" VsDevCmd.bat from Cygwin


问:
mybatis <id> tag in <resultMap> behavior
I wrote mapping file like below.

```<code><resultMap id="fooResultMap" type="Foo" >
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>
</code>```

When I get 2 record of same NAME colmun value, mybatis return only 1 Foo object.
I want 2 Foo object becouse bar's column is different.

So, I workaround below.

```<code><resultMap id="fooResultMap" type="Foo" >
  <id column="dummy_column_for_unique" />
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>
</code>```

I added <id> tag in <resultMap> and "dummy_column_for_unique" column is dummy(not exists).
I successfully got 2 Foo object.

I suppose dummy column result in null, and mybatis probably handle null value as different record.
But such behavior is not explained in manual or other resources on internet I searched.

Is there any information of this behavior ?

答:
MyBatis maps the objects using the ID. If there is no ID in the ResultMap, they are all mapped in the same object.
Your table should have a primary key, but I guess that creating a fake ID as you did might serve as a workaround.</p>

Body:
I wrote mapping file like below.

<resultMap id="fooResultMap" type="Foo" >
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>

When I get 2 record of same NAME colmun value, mybatis return only 1 Foo object.
I want 2 Foo object becouse bar's column is different.

So, I workaround below.

<resultMap id="fooResultMap" type="Foo" >
  <id column="dummy_column_for_unique" />
  <result column="NAME" property="name" jdbcType="VARCHAR" />
  <association property="bar" resultMap="barResultMap" />
</resultMap>

I added <id> tag in <resultMap> and "dummy_column_for_unique" column is dummy(not exists).
I successfully got 2 Foo object.

I suppose dummy column result in null, and mybatis probably handle null value as different record.
But such behavior is not explained in manual or other resources on internet I searched.

Is there any information of this behavior ?


问:
Concatenating or cascading multiple pretrained keras models
I'm trying to build a concatenated or cascaded(actually don't even know if this is the correct definiton) set of models.
For the simplicity my base models are looking like below.

```<code>                              ----Input----
                                    |
                                  L1-1
                                    |
                                  L1-2
                                    |
                                  Dense
                                    |
                                 Softmax
</code>```

I got 7 of these models trained with cross-validation and trying to wrap up them in a cascade fashion such as:

```<code>            -----------------------Input---------------------
            |       |       |       |       |       |       |
          L1-1    L1-2    L1-3    L1-4     L1-5   L1-6    L1-7
            |       |       |       |       |       |       |
          L2-1    L2-2    L2-3    L2-4     L2-5   L2-6    L2-7
            |       |       |       |       |       |       |
            |_______|_______|_______|_______|_______|_______|
            |                  Concatenated                 |
            |___________________Dense Layer_________________|
                                    |
                                 SoftMax
</code>```

Each one of Dense Layers got 512 neurons so in the end Concatenated Dense Layer would have a total of7*512=3584 neurons.

What I've done is:

Trained all models and saved them in a list named as models[].

Popped the bottom Softmax Layer in all models.

Then I try to concatenate them but got the error:

```<code>Layer merge was called with an input that isn't a symbolic tensor.
</code>```

What I'm gonna do after forming the cascade is freezing all the intermediate layers except Concatenated Dense Layer and tuning it up a little bit. But I'm stuck at as explained in all the details.

答:
You need to use the functional API model for that. This kind of model works with tensors.

First you define a common input tensor:

```<code>inputTensor = Input(inputShape)
</code>```

Then you call each model with this input to get the output tensors:

```<code>outputTensors = [m(inputTensor) for m in models]
</code>```

Then you pass these tensors to the concatenate layer:

```<code>output = Concatenate()(outputTensors)
output = Dense(...)(output)
#you might want to use an Average layer instead of these two....

output = Activation('softmax')(output)
</code>```

Finally, you define the complete model from start tensors to end tensors:

```<code>fullModel = Model(inputTensor,output)
</code>```

Body:
I'm trying to build a concatenated or cascaded(actually don't even know if this is the correct definiton) set of models.
For the simplicity my base models are looking like below.

                              ----Input----
                                    |
                                  L1-1
                                    |
                                  L1-2
                                    |
                                  Dense
                                    |
                                 Softmax

I got 7 of these models trained with cross-validation and trying to wrap up them in a cascade fashion such as:

            -----------------------Input---------------------
            |       |       |       |       |       |       |
          L1-1    L1-2    L1-3    L1-4     L1-5   L1-6    L1-7
            |       |       |       |       |       |       |
          L2-1    L2-2    L2-3    L2-4     L2-5   L2-6    L2-7
            |       |       |       |       |       |       |
            |_______|_______|_______|_______|_______|_______|
            |                  Concatenated                 |
            |___________________Dense Layer_________________|
                                    |
                                 SoftMax

Each one of Dense Layers got 512 neurons so in the end Concatenated Dense Layer would have a total of7*512=3584 neurons.

What I've done is:

Trained all models and saved them in a list named as models[].

Popped the bottom Softmax Layer in all models.

Then I try to concatenate them but got the error:

Layer merge was called with an input that isn't a symbolic tensor.

What I'm gonna do after forming the cascade is freezing all the intermediate layers except Concatenated Dense Layer and tuning it up a little bit. But I'm stuck at as explained in all the details.

Body:
You need to use the functional API model for that. This kind of model works with tensors.

First you define a common input tensor:

inputTensor = Input(inputShape)

Then you call each model with this input to get the output tensors:

outputTensors = [m(inputTensor) for m in models]

Then you pass these tensors to the concatenate layer:

output = Concatenate()(outputTensors)
output = Dense(...)(output)
#you might want to use an Average layer instead of these two....

output = Activation('softmax')(output)

Finally, you define the complete model from start tensors to end tensors:

fullModel = Model(inputTensor,output)


问:
Reduce redirects for website - web.config
I need help with the (number of) redirects on my website.  At the moment I have 3 working redirects,

One goes from the WWW to the non www version.
Another goes from the non SSL to https.

Finally I removed Server header to increase security.

They work but I think they are slowing my site down.  Is there any way I can reduce the redirects to 2 ? I am looking for https://website.com

Here is my web.config:

```<code>    <configuration>
   <system.webServer>
      <staticContent>
            <clientCache cacheControlMode="UseExpires" httpExpires="Tue, 19 Jan 2038 03:14:07 GMT" />
      </staticContent>
      <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url=".*" />
                      <conditions>
                         <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                      </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>

                <rule name="Redirect to non-www" stopProcessing="true">
                  <match url="(.*)" negate="false"></match>
                  <action type="Redirect" url="http://website.com/{R:1}"></action>
                  <conditions>
                      <add input="{HTTP_HOST}" pattern="^website\.com$" negate="true"></add>
                  </conditions>
                </rule>

            </rules>
        </rewrite>
         <rewrite>
        <outboundRules rewriteBeforeCache="true">
          <rule name="Remove Server header">
            <match serverVariable="RESPONSE_Server" pattern=".+" />
            <action type="Rewrite" value="" />
          </rule>
        </outboundRules>

</rewrite>
   </system.webServer>
</configuration>
</code>```

I came up with something like this but it seems to have made it worse   :

```<code><rules>
<clear />
    <rule name="Redirect www and non-https to https://">
                  <match url=".*" />
                    <conditions logicalGrouping="MatchAny">
                         <add input="{HTTP_HOST}" pattern="^website\.com$" negate="true"></add>
                        <add input="{HTTPS}" pattern="off" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
     </rule>
</rules>
</code>```

答:
Here is my answer, I hope it can help someone with their SEO.
I got redirects down from the highs of:

3 redirects for using www ,

1 redirect for no www,

2 redirects for www (https)

0 redirects for no www (https)

to a maximum of 1:

1 redirect for www,

1 redirect for no www,

1 redirect for www(https)

0 redirects for no www(https)

I just needed to add a s in one line and remove {HTTP_HOST} and instead put in the website name.

```<code><rewrite>
       <rules>
            <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url=".*" />
                      <conditions>
                          <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                      </conditions>
                    <action type="Redirect" url="https://website.com{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>

                <rule name="Redirect to non-www" stopProcessing="true">
                  <match url="(.*)" negate="false" />
                  <conditions>
                      <add input="{HTTP_HOST}" pattern="^website\.com$" negate="true" />
                  </conditions>
                  <action type="Redirect" url="https://website.com/{R:1}" />
                </rule>

        </rules>
</rewrite>
</code>```

Body:
I need help with the (number of) redirects on my website.  At the moment I have 3 working redirects,

One goes from the WWW to the non www version.
Another goes from the non SSL to https.

Finally I removed Server header to increase security.

They work but I think they are slowing my site down.  Is there any way I can reduce the redirects to 2 ? I am looking for https://website.com

Here is my web.config:

    <configuration>
   <system.webServer>
      <staticContent>
            <clientCache cacheControlMode="UseExpires" httpExpires="Tue, 19 Jan 2038 03:14:07 GMT" />
      </staticContent>
      <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url=".*" />
                      <conditions>
                         <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                      </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>

                <rule name="Redirect to non-www" stopProcessing="true">
                  <match url="(.*)" negate="false"></match>
                  <action type="Redirect" url="http://website.com/{R:1}"></action>
                  <conditions>
                      <add input="{HTTP_HOST}" pattern="^website\.com$" negate="true"></add>
                  </conditions>
                </rule>

            </rules>
        </rewrite>
         <rewrite>
        <outboundRules rewriteBeforeCache="true">
          <rule name="Remove Server header">
            <match serverVariable="RESPONSE_Server" pattern=".+" />
            <action type="Rewrite" value="" />
          </rule>
        </outboundRules>

</rewrite>
   </system.webServer>
</configuration>

I came up with something like this but it seems to have made it worse   :

<rules>
<clear />
    <rule name="Redirect www and non-https to https://">
                  <match url=".*" />
                    <conditions logicalGrouping="MatchAny">
                         <add input="{HTTP_HOST}" pattern="^website\.com$" negate="true"></add>
                        <add input="{HTTPS}" pattern="off" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
     </rule>
</rules>

Body:
Here is my answer, I hope it can help someone with their SEO.
I got redirects down from the highs of:

3 redirects for using www ,

1 redirect for no www,

2 redirects for www (https)

0 redirects for no www (https)

to a maximum of 1:

1 redirect for www,

1 redirect for no www,

1 redirect for www(https)

0 redirects for no www(https)

I just needed to add a s in one line and remove {HTTP_HOST} and instead put in the website name.

<rewrite>
       <rules>
            <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url=".*" />
                      <conditions>
                          <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                      </conditions>
                    <action type="Redirect" url="https://website.com{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>

                <rule name="Redirect to non-www" stopProcessing="true">
                  <match url="(.*)" negate="false" />
                  <conditions>
                      <add input="{HTTP_HOST}" pattern="^website\.com$" negate="true" />
                  </conditions>
                  <action type="Redirect" url="https://website.com/{R:1}" />
                </rule>

        </rules>
</rewrite>


问:
Why can't we use *.cshtml files as custom error pages now that (v4.7) we have "Razor Web Pages"?
B"H

Trying to revamp my global error handling, and running into the mess that is ASP.net error handlers.

I would really like to consolidate my solution as much as possible. So if possible I'd like to use the same pages to display from httpErrors and customErrors. I'd also like to use the appropriate Layout pages if possible. But it seems that if I want to use some kind of dynamic page as a custom error page that it needs to be *.aspx. Why is that? Especially now that we have Razor Web Pages?

PS. This is for an MVC (.net v4.7 ie not asp core) Site

答:
If you are using the .cshtml file as a Razor Web Page, then can't you give the URL of the file, excluding the .cshtml?  As per the table here: https://learn.microsoft.com/en-us/aspnet/core/mvc/razor-pages/?tabs=visual-studio

A standalone .cshtml file is will normally depend on a Code behind file (if using Razor Web Pages) or a MVC Controller Action to provide it with its data.  I guess this is why you are not allowed to redirect directly to one.


问:
How to disable console logging in spring-boot?
I'm using the default logging configuration of spring-boot.

How can I prevent the console output, while keeping the logging into a logfile configured with logging.file=myfile.log?

My goal is to not having console windows output, but only logging to that file.

Without having to create a specific logback.xml configuration. Because I'm using spring-boot for not having to configure the logging myself.

答:
I created a file called logback.xml with the content:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework" level="ERROR"/>
    <logger name="org.hibernate" level="ERROR"/>
</configuration>
</code>```

See this link for more information: https://www.mkyong.com/spring-boot/spring-boot-test-how-to-stop-debug-logs/

Body:
I created a file called logback.xml with the content:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework" level="ERROR"/>
    <logger name="org.hibernate" level="ERROR"/>
</configuration>

See this link for more information: https://www.mkyong.com/spring-boot/spring-boot-test-how-to-stop-debug-logs/