问:
Unable to understand the logic of the part to the right of assignment operator when creating object of inner class
I did not find my answer in the questions I searched , that's why I am asking it .

```<code>class outer
{
class inner  // non static .
{
}
}

For creating object of inner class I am unable to understand the logic of the part to the right of assignment operator .

outer o = new outer () ;
outer.inner y = o. new inner () ; //  I have doubt in this line .
</code>```

Here outer.inner is the return type but what about the right portion ?

Thing I know :
We cant write outer.inner y = new outer.inner () ; since inner is non static .

答:
The problem is that a non-static inner class is bound to a specific instance of the containing class. It's like if the class definition has an hidden reference member, sort of:

```<code>class Outer {
  class Inner {
    private final Outer outer;
    Inner(Outer outer) { this.outer = outer; }
  }
}
</code>```

That's what is happening outer.inner y = o.new inner(), since inner is not static it requires an outer to be instantiated and that syntax is used to pass the hidden outer reference to the instance.

If Inner becomes static then it doesn't need a qualifying instance anymore, the name of the outer class is enough, eg: new Outer.Inner().

Body:
I did not find my answer in the questions I searched , that's why I am asking it .

class outer
{
class inner  // non static .
{
}
}

For creating object of inner class I am unable to understand the logic of the part to the right of assignment operator .

outer o = new outer () ;
outer.inner y = o. new inner () ; //  I have doubt in this line .

Here outer.inner is the return type but what about the right portion ?

Thing I know :
We cant write outer.inner y = new outer.inner () ; since inner is non static .

Body:
The problem is that a non-static inner class is bound to a specific instance of the containing class. It's like if the class definition has an hidden reference member, sort of:

class Outer {
  class Inner {
    private final Outer outer;
    Inner(Outer outer) { this.outer = outer; }
  }
}

That's what is happening outer.inner y = o.new inner(), since inner is not static it requires an outer to be instantiated and that syntax is used to pass the hidden outer reference to the instance.

If Inner becomes static then it doesn't need a qualifying instance anymore, the name of the outer class is enough, eg: new Outer.Inner().


来源: stackexchange

问:
How to unpack a list?
When extracting data from a list this way

```<code>line[0:3], line[3][:2], line[3][2:]
</code>```

I receive an array and two variables after it, as should be expected:

```<code>(['a', 'b', 'c'], 'd', 'e')
</code>```

I need to manipulate the list so the end result is

```<code>('a', 'b', 'c', 'd', 'e')
</code>```

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

答:
Obvious answer: Instead of your first line, do:

```<code>line[0:3] + [line[3][:2], line[3][2:]]
</code>```

That works assuming that line[0:3] is a list. Otherwise, you may need to make some minor adjustments.

ContentLicense: CC BY-SA 2.5

Title: How to unpack a list?

Body:
When extracting data from a list this way

line[0:3], line[3][:2], line[3][2:]

I receive an array and two variables after it, as should be expected:

(['a', 'b', 'c'], 'd', 'e')

I need to manipulate the list so the end result is

('a', 'b', 'c', 'd', 'e')

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

Body:
Obvious answer: Instead of your first line, do:

line[0:3] + [line[3][:2], line[3][2:]]

That works assuming that line[0:3] is a list. Otherwise, you may need to make some minor adjustments.


问:
Getting N random numbers whose sum is M
I want to get N random numbers whose sum is a value.

For example, let's suppose I want 5 random numbers that sum to 1.

Then, a valid possibility is:

```<code>0.2 0.2 0.2 0.2 0.2
</code>```

Another possibility is:

```<code>0.8 0.1 0.03 0.03 0.04
</code>```

And so on. I need this for the creation of a matrix of belongings for Fuzzy C-means.

答:
Just generate N random numbers, compute their sum, divide each one by
  the sum.

Expanding on Guillaume's accepted answer, here's a Java function that does exactly that.

public static double[] getRandDistArray(int n, double m)
{
    double randArray[] = new double[n];
    double sum = 0;

    // Generate n random numbers
    for (int i = 0; i < randArray.length; i++)
    {
        randArray[i] = Math.random();
        sum += randArray[i];
    }

    // Normalize sum to m
    for (int i = 0; i < randArray.length; i++)
    {
        randArray[i] /= sum;
        randArray[i] *= m;
    }
    return randArray;
}
```

<p>In a test run, <code>getRandDistArray(5, 1.0)</code> returned the following:</p>

```[0.38106150346121903, 0.18099632814238079, 0.17275044310377025, 0.01732932296660358, 0.24786240232602647]
```

ContentLicense: CC BY-SA 4.0

Title: Getting N random numbers whose sum is M

Body:
I want to get N random numbers whose sum is a value.

For example, let's suppose I want 5 random numbers that sum to 1.

Then, a valid possibility is:

0.2 0.2 0.2 0.2 0.2

Another possibility is:

0.8 0.1 0.03 0.03 0.04

And so on. I need this for the creation of a matrix of belongings for Fuzzy C-means.

Body:
Just generate N random numbers, compute their sum, divide each one by
  the sum.

Expanding on Guillaume's accepted answer, here's a Java function that does exactly that.

public static double[] getRandDistArray(int n, double m)
{
    double randArray[] = new double[n];
    double sum = 0;

    // Generate n random numbers
    for (int i = 0; i < randArray.length; i++)
    {
        randArray[i] = Math.random();
        sum += randArray[i];
    }

    // Normalize sum to m
    for (int i = 0; i < randArray.length; i++)
    {
        randArray[i] /= sum;
        randArray[i] *= m;
    }
    return randArray;
}

In a test run, getRandDistArray(5, 1.0) returned the following:

[0.38106150346121903, 0.18099632814238079, 0.17275044310377025, 0.01732932296660358, 0.24786240232602647]

ContentLicense: CC BY-SA 3.0


问:
VB.NET 2010 - Process.Start("filePath\Test.bat") not opening test.bat?
I have been working on some vb.net 2010 coding and I am stuck on a piece of code that I dont know how to fix it, so thats why I ask you to maybe help me with this code.

Code:

```<code>    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim url As New System.Uri("http://example/one/")
    Dim req As System.Net.WebRequest
    req = System.Net.WebRequest.Create(url)
    Dim resp As System.Net.WebResponse
    Dim filePath As String
    filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\examplepath"
    Try
        resp = req.GetResponse()
        resp.Close()
        req = Nothing
        Process.Start("filePath\Test.exe")
    Catch ex As Exception
        req = Nothing
        Me.Close()
    End Try
End Sub
</code>```

Problem:
The file in %APPDATA%\ExamplePath\Test.bat doesn't open.

I hope you can help me :)

答:
This line seems the problem:

```<code>Process.Start("filePath\Test.exe")
</code>```

Here you're putting a variable as a string, which of course won't work. Instead, concatenate it with the file name:

```<code>Process.Start(filePath & "\Test.exe")
</code>```

That will work, but a better way to handle the file system is to use the Path class and the Combine method to handle a path that has multiple parts:

```<code>Process.Start(Path.Combine(filePath, "Test.exe"))
</code>```

This deals with putting the correct separator and the fact that it may or may not have a trailing backslash.

Body:
I have been working on some vb.net 2010 coding and I am stuck on a piece of code that I dont know how to fix it, so thats why I ask you to maybe help me with this code.

Code:

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim url As New System.Uri("http://example/one/")
    Dim req As System.Net.WebRequest
    req = System.Net.WebRequest.Create(url)
    Dim resp As System.Net.WebResponse
    Dim filePath As String
    filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\examplepath"
    Try
        resp = req.GetResponse()
        resp.Close()
        req = Nothing
        Process.Start("filePath\Test.exe")
    Catch ex As Exception
        req = Nothing
        Me.Close()
    End Try
End Sub

Problem:
The file in %APPDATA%\ExamplePath\Test.bat doesn't open.

I hope you can help me :)

Body:
This line seems the problem:

Process.Start("filePath\Test.exe")

Here you're putting a variable as a string, which of course won't work. Instead, concatenate it with the file name:

Process.Start(filePath & "\Test.exe")

That will work, but a better way to handle the file system is to use the Path class and the Combine method to handle a path that has multiple parts:

Process.Start(Path.Combine(filePath, "Test.exe"))

This deals with putting the correct separator and the fact that it may or may not have a trailing backslash.


问:
Java Multithread Multiple Requests Approach
I want to send to "test.com" a request from 0 to 100, the code i have will send a request every one second... In this way the program will take 100 seconds in order to complete.

What i would like to do is set 10 threads running all at the same time, making the thread 1 going from (0,10); thread 2 going from (10,20) ... and so on, in this way the program should take only 10 seconds or so in order to complete, is that possible ? how can acomplish it ?

```<code>import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

public class Palomo implements Runnable {
    String url = "http://test.com";
    HttpClient client = null;
    PostMethod method = null;
    BufferedReader br = null;
    String contents = null;

    public void run() {
        for (int i = 0; i <= 100; i++) {
            synchronized (this) {
                doPost(i);
            }
                      try {
        Thread.sleep(1000);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
        }
    }

    public void doPost(int i) {
        try {
            client = new HttpClient();
            method = new PostMethod(url);

            this.method.addParameter("myPostRequest", Integer.toString(i));

            client.executeMethod(method);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }

    public static void main(String[] args) {
        new Thread(new Palomo()).start();
    }
}
</code>```

Thanks a lot !

EDIT

Reading the indications you gave me, i created this horrible monster...

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpExec {
    public static void main(String args[]) {

        ExecutorService es = Executors.newFixedThreadPool(4);

        es.execute(new MyThread("A"));
        es.execute(new MyThread("B"));
        es.execute(new MyThread("C"));
        es.execute(new MyThread("D"));

        es.shutdown();
    }
}

class MyThread implements Runnable {
    String name;

    MyThread(String n) {
        name = n;
        new Thread(this);
    }

    public void run() {
        if (name=="A"){
            for (int i=1;i<=10;i++){
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (name=="B"){
            for (int i=10;i<=20;i++){
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (name=="C"){
            for (int i=20;i<=30;i++){
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (name=="D"){
            for (int i=30;i<=40;i++){
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
</code>```

I know this is probably the most awful piece of code you ever watched, but is making exactly what i want, if you can give me some directions on how i should accomplish this in the right way that would be great.

THANKS A LOT FOR ALL YOUR GREAT ADVICES

答:
I have done something similar, I will share my first POC as it feels good to share.

```<code>package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ThreadCreater {

    // use getShape method to get object of type shape
    public Thread threadRunner(int start, int end, int threadCount, String url) {
    Thread thread = null;
    int tempEnd = 0;
    for (int i = 0; i <= end; i = i + 10) {
        start = i;
        tempEnd = i + 10;
        thread = getThread(start, tempEnd, threadCount, url);
        thread.start();
    }

    return null;
    }

    public static Thread getThread(int start, int end, int threadCount, String url) {
    Thread thread = new Thread() {
        public void run() {
        try {
            sendGET(start, end, url);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }

        private void sendGET(int start, int end, String url) throws Exception {
        url += "start=" + start + "&end=" + end;
        URL obj = new URL(url);
        // Send post request
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // basic reuqest header to simulate a browser request
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/51.0");
        con.setRequestProperty("Upgrade-Insecure-Requests", "1");
        con.setRequestProperty("Connection", "keep-alive");
        con.setDoOutput(true);

        // reading the HTML output of the POST HTTP request
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        }
    };
    return thread;
    }

    public static void main(String[] args) {
    ThreadCreater obj = new ThreadCreater();
    int start = 0;
    int end = 100;
    int threadCount = 10;
    String url = "http://iseebug.com/test.php?";

    obj.threadRunner(start, end, threadCount, url);
    }

}
</code>```

simple test.php code below

```<code><?php
/**
 * Created by PhpStorm.
 * User: polo
 * Date: 02-04-2017
 * Time: 22:28
 */

$q1 = isset($_GET['start']) ? $_GET['start'] : 'fakeMIP';
$q2 = isset($_GET['end']) ? $_GET['end'] : 'fakeMIP';

if($q1>=0&&$q2<=10){
echo $q2;
}elseif ($q1>=10&&$q2<=20){
    echo $q2;
}elseif ($q1>=20&&$q2<=30){
    echo $q2;
}elseif ($q1>=30&&$q2<=40){
    echo $q2;
}elseif ($q1>=40&&$q2<=50){
    echo $q2;
}elseif ($q1>=50&&$q2<=60){
    echo $q2;
}elseif ($q1>=60&&$q2<=70){
    echo $q2;
}elseif ($q1>=70&&$q2<=80){
    echo $q2;
}elseif ($q1>=80&&$q2<=90){
    echo $q2;
}elseif ($q1>=90&&$q2<=100){
    echo $q2;
}
</code>```

Good luck.

But i will prefer java's ExecutorService for high usage, for limited requirement , you can go for basic threading.

Ping me on any help.

Body:
I want to send to "test.com" a request from 0 to 100, the code i have will send a request every one second... In this way the program will take 100 seconds in order to complete.

What i would like to do is set 10 threads running all at the same time, making the thread 1 going from (0,10); thread 2 going from (10,20) ... and so on, in this way the program should take only 10 seconds or so in order to complete, is that possible ? how can acomplish it ?

import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

public class Palomo implements Runnable {
    String url = "http://test.com";
    HttpClient client = null;
    PostMethod method = null;
    BufferedReader br = null;
    String contents = null;

    public void run() {
        for (int i = 0; i <= 100; i++) {
            synchronized (this) {
                doPost(i);
            }
                      try {
        Thread.sleep(1000);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
        }
    }

    public void doPost(int i) {
        try {
            client = new HttpClient();
            method = new PostMethod(url);

            this.method.addParameter("myPostRequest", Integer.toString(i));

            client.executeMethod(method);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }

    public static void main(String[] args) {
        new Thread(new Palomo()).start();
    }
}

Thanks a lot !

EDIT

Reading the indications you gave me, i created this horrible monster...

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpExec {
    public static void main(String args[]) {

        ExecutorService es = Executors.newFixedThreadPool(4);

        es.execute(new MyThread("A"));
        es.execute(new MyThread("B"));
        es.execute(new MyThread("C"));
        es.execute(new MyThread("D"));

        es.shutdown();
    }
}

class MyThread implements Runnable {
    String name;

    MyThread(String n) {
        name = n;
        new Thread(this);
    }

    public void run() {
        if (name=="A"){
            for (int i=1;i<=10;i++){
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (name=="B"){
            for (int i=10;i<=20;i++){
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (name=="C"){
            for (int i=20;i<=30;i++){
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (name=="D"){
            for (int i=30;i<=40;i++){
                System.out.println(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

I know this is probably the most awful piece of code you ever watched, but is making exactly what i want, if you can give me some directions on how i should accomplish this in the right way that would be great.

THANKS A LOT FOR ALL YOUR GREAT ADVICES

Body:
I have done something similar, I will share my first POC as it feels good to share.

package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ThreadCreater {

    // use getShape method to get object of type shape
    public Thread threadRunner(int start, int end, int threadCount, String url) {
    Thread thread = null;
    int tempEnd = 0;
    for (int i = 0; i <= end; i = i + 10) {
        start = i;
        tempEnd = i + 10;
        thread = getThread(start, tempEnd, threadCount, url);
        thread.start();
    }

    return null;
    }

    public static Thread getThread(int start, int end, int threadCount, String url) {
    Thread thread = new Thread() {
        public void run() {
        try {
            sendGET(start, end, url);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }

        private void sendGET(int start, int end, String url) throws Exception {
        url += "start=" + start + "&end=" + end;
        URL obj = new URL(url);
        // Send post request
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // basic reuqest header to simulate a browser request
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/51.0");
        con.setRequestProperty("Upgrade-Insecure-Requests", "1");
        con.setRequestProperty("Connection", "keep-alive");
        con.setDoOutput(true);

        // reading the HTML output of the POST HTTP request
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        }
    };
    return thread;
    }

    public static void main(String[] args) {
    ThreadCreater obj = new ThreadCreater();
    int start = 0;
    int end = 100;
    int threadCount = 10;
    String url = "http://iseebug.com/test.php?";

    obj.threadRunner(start, end, threadCount, url);
    }

}

simple test.php code below

<?php
/**
 * Created by PhpStorm.
 * User: polo
 * Date: 02-04-2017
 * Time: 22:28
 */

$q1 = isset($_GET['start']) ? $_GET['start'] : 'fakeMIP';
$q2 = isset($_GET['end']) ? $_GET['end'] : 'fakeMIP';

if($q1>=0&&$q2<=10){
echo $q2;
}elseif ($q1>=10&&$q2<=20){
    echo $q2;
}elseif ($q1>=20&&$q2<=30){
    echo $q2;
}elseif ($q1>=30&&$q2<=40){
    echo $q2;
}elseif ($q1>=40&&$q2<=50){
    echo $q2;
}elseif ($q1>=50&&$q2<=60){
    echo $q2;
}elseif ($q1>=60&&$q2<=70){
    echo $q2;
}elseif ($q1>=70&&$q2<=80){
    echo $q2;
}elseif ($q1>=80&&$q2<=90){
    echo $q2;
}elseif ($q1>=90&&$q2<=100){
    echo $q2;
}

Good luck.

But i will prefer java's ExecutorService for high usage, for limited requirement , you can go for basic threading.

Ping me on any help.


问:
Explicit conversion from data type date to int is not allowed
I am trying to calculate AGE of contracts, however I am getting the error

Explicit conversion from data type date to int is not allowed

This is my code:

```<code>SELECT
    Contract_hist.*,
    IB.*,
    CAST((CASE
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT))/365 <= 0
                THEN 0
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365 > 0
                THEN (CAST(CONVERT(INT, Setup.[Start]) CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365
          END) AS INT) AS AGE
FROM
    Setup, Contract_hist
INNER JOIN
    IB ON Contract_hist.[System No] = IB.System_ID
</code>```

Where "Setup.[Start]" & "[IB].[Install_Date]" are datetime2 values.

答: Seems like casting to a float/int is not supported in the latter versions of sql server. Try using DATEDIFF(dd, '12/30/1899', mydatefield)

Body:
I am trying to calculate AGE of contracts, however I am getting the error

Explicit conversion from data type date to int is not allowed

This is my code:

SELECT
    Contract_hist.*,
    IB.*,
    CAST((CASE
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT))/365 <= 0
                THEN 0
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365 > 0
                THEN (CAST(CONVERT(INT, Setup.[Start]) CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365
          END) AS INT) AS AGE
FROM
    Setup, Contract_hist
INNER JOIN
    IB ON Contract_hist.[System No] = IB.System_ID

Where "Setup.[Start]" & "[IB].[Install_Date]" are datetime2 values.


问:
Do you need to use Bootstrap's "container" and "row" if your content is to span the whole width?
I think the standard of Bootstrap 3 and 4 is

```<code><div class="container">
    <div class="row">
        <div class="col-md-4"> ... </div>
        <div class="col-md-8"> ... </div>   <!-- just add up to 12 -->
    </div>
</div>
</code>```

But what if you have a div, table, form, or any element, that you plan to just let it span the whole width?  Then do you need the container or row or col-md-12 at all, for the whole page to display well under the styling rules of Bootstrap 3 and 4?

P.S. if possible, please point to or quote the official Bootstrap docs related to this.

答: Use fluid-container to span entire width of parent. </p>

Body:
I think the standard of Bootstrap 3 and 4 is

 ...

 ...

But what if you have a div, table, form, or any element, that you plan to just let it span the whole width?  Then do you need the container or row or col-md-12 at all, for the whole page to display well under the styling rules of Bootstrap 3 and 4?

P.S. if possible, please point to or quote the official Bootstrap docs related to this.


问:
Nginx downloading file instead of serving it (Not PHP)
I'm trying to implement universal links from my iOS app, thus I need to have the "apple-app-site-association" file at the root of my web server.

I am using nginx and everything is (supposedly) setup correctly. My website works, php works, my api works. The only problem is that when I go to my site "test.com/apple-app-site-association" the browser (as well as the iOS browser) downloads the file instead of just displaying it, thus making my universal link not work.

If anyone has any ideas on how to stop nginx from offering the site as a download and serving it instead I would be glad.

Below is my server's configuration, with my site edited out:

```<code>server {
  listen 80 default_server;
  listen [::]:80 default_server;

  server_name test.com www.test.com;
  return 301 https://$server_name$request_uri;
}

server {
  # SSL configuration
  listen 443 ssl http2 default_server;
  listen [::]:443 ssl http2 default_server;

  include snippets/ssl-test.com.conf;
  include snippets/ssl-params.conf;

  client_max_body_size 1m;

  root /var/www/test.com/web;
  index  index.html index.htm index.php;

  access_log            /var/log/nginx/test.com.access.log;
  error_log             /var/log/nginx/test.com.error.log;

  #Default url rewrites
  location / {

    #root  /var/www/test.com/web;
    try_files $uri $uri/ /index.html;
    autoindex off;
    index  index.html index.htm index.php;

  }

  location ~ \.php$ {
    # try_files $uri =404;
    set $path_info $fastcgi_path_info;
    root  /var/www/test.com/web;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    try_files $uri $uri/ /index.php$is_args$args;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;

    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param APP_ENV dev;

  }

  #Apple universal links
  location = /apple-app-site-association {
    default_type application/pkcs7-mime;
  }

  #Redirect all requests under /user/ to the "get App" page
  location /user/ {
    return 301 https://test.com/get_app.html;
    # try_files $uri $uri/ /get_app.html;
  }

  #Let's Encrypt SSL Validation
  include snippets/letsencrypt.conf;
}
</code>```

Using a REST API client, requesting the file gives the following headers, that appear to be correct (no "attachment" header):

```<code>Server: nginx/1.10.3
Date: Sun, 02 Apr 2017 17:25:42 GMT
Content-Type: application/pkcs7-mime
Content-Length: 149
Last-Modified: Sun, 02 Apr 2017 16:07:02 GMT
Connection: keep-alive
Etag: "58e121a6-95"
Strict-Transport-Security: max-age=63072000; includeSubdomains
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Accept-Ranges: bytes
</code>```

答:
Your browser as well as the ios browser may not support the Content-Type: application/pkcs7-mime. If the content is human readable try setting Content-Type: text/plain.

Also see if this link is of any help.

Body:
I'm trying to implement universal links from my iOS app, thus I need to have the "apple-app-site-association" file at the root of my web server.

I am using nginx and everything is (supposedly) setup correctly. My website works, php works, my api works. The only problem is that when I go to my site "test.com/apple-app-site-association" the browser (as well as the iOS browser) downloads the file instead of just displaying it, thus making my universal link not work.

If anyone has any ideas on how to stop nginx from offering the site as a download and serving it instead I would be glad.

Below is my server's configuration, with my site edited out:

server {
  listen 80 default_server;
  listen [::]:80 default_server;

  server_name test.com www.test.com;
  return 301 https://$server_name$request_uri;
}

server {
  # SSL configuration
  listen 443 ssl http2 default_server;
  listen [::]:443 ssl http2 default_server;

  include snippets/ssl-test.com.conf;
  include snippets/ssl-params.conf;

  client_max_body_size 1m;

  root /var/www/test.com/web;
  index  index.html index.htm index.php;

  access_log            /var/log/nginx/test.com.access.log;
  error_log             /var/log/nginx/test.com.error.log;

  #Default url rewrites
  location / {

    #root  /var/www/test.com/web;
    try_files $uri $uri/ /index.html;
    autoindex off;
    index  index.html index.htm index.php;

  }

  location ~ \.php$ {
    # try_files $uri =404;
    set $path_info $fastcgi_path_info;
    root  /var/www/test.com/web;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    try_files $uri $uri/ /index.php$is_args$args;
    include /etc/nginx/fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;

    fastcgi_param SCRIPT_FILENAME $request_filename;
    fastcgi_param APP_ENV dev;

  }

  #Apple universal links
  location = /apple-app-site-association {
    default_type application/pkcs7-mime;
  }

  #Redirect all requests under /user/ to the "get App" page
  location /user/ {
    return 301 https://test.com/get_app.html;
    # try_files $uri $uri/ /get_app.html;
  }

  #Let's Encrypt SSL Validation
  include snippets/letsencrypt.conf;
}

Using a REST API client, requesting the file gives the following headers, that appear to be correct (no "attachment" header):

Server: nginx/1.10.3
Date: Sun, 02 Apr 2017 17:25:42 GMT
Content-Type: application/pkcs7-mime
Content-Length: 149
Last-Modified: Sun, 02 Apr 2017 16:07:02 GMT
Connection: keep-alive
Etag: "58e121a6-95"
Strict-Transport-Security: max-age=63072000; includeSubdomains
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Accept-Ranges: bytes


问:
Form submit add domain to username field if missing
I have a login form that includes a username and password field.

Users will be able to login using:

Domain\username
And
Username@domain.org.uk

However many users attempt to login using just 'username'

I want to help users by adding domain\ or @domain.org.uk to there username when they enter just 'username', when they click the login button I want to add the domain part of the username.

How can I do this in pure JavaScript?

答:
Something along the lines of</p>

```<code>var username = document.getElementById('username')
if(username.indexOf('@') < 0){
   username = usename + '@domain.org.uk';
}
</code>```

Body:
Something along the lines of

var username = document.getElementById('username')
if(username.indexOf('@') < 0){
   username = usename + '@domain.org.uk';
}


答:
```<code>outer o = new outer () ;
outer.inner y = o. new inner () ;
</code>```

So, the first portion outer.inner is the return type as you've stated.

Second, the o is a reference to the outer object which contains the inner object, you will only access the inner object if you have a reference to the outer object. now o. new inner () ;  simply says "go into the object o, then create an object of type inner".

Title: Unable to understand the logic of the part to the right of assignment operator when creating object of inner class

Body:
outer o = new outer () ;
outer.inner y = o. new inner () ;

So, the first portion outer.inner is the return type as you've stated.

Second, the o is a reference to the outer object which contains the inner object, you will only access the inner object if you have a reference to the outer object. now o. new inner () ;  simply says "go into the object o, then create an object of type inner".


问:
Android firebase create and display username
I am using Firebase user sign up method with email and password. While creating a new user I also store information such username that later on needs to be displayed in app profile page.

How could I retrieve the username of currently logged in person ?

Thank you in advance

```<code>private void registration(){

    final String email = Email.getText().toString().toString().trim();
    final String password = Password.getText().toString().trim();
    final String username = Username.getText().toString().trim();
    final String age = Age.getText().toString().trim();
    final String userID = userAuth.getCurrentUser().getUid();

    if (!TextUtils.isEmpty(email)&& !TextUtils.isEmpty(password)&& !TextUtils.isEmpty(username)&& !TextUtils.isEmpty(age)){

        showProgress.setMessage("Registration in progress...");
        showProgress.show();

        userAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if(task.isSuccessful()) {

                    String user_id = userAuth.getCurrentUser().getUid();
                    DatabaseReference current_user_db = DatbaseOfUsers.child(user_id);
                    current_user_db.child("email").setValue(email);
                    current_user_db.child("username").setValue(username);
                    current_user_db.child("Age").setValue(age);
                    current_user_db.child("uID").setValue(userID);

                    showProgress.dismiss();

                    //After user is created main screen intent is called
                    Intent mainpage = new Intent(RegisterActivity.this, MainPageActivity.class);
                    mainpage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(mainpage);
                }

                else if(!task.isSuccessful()){
                    showProgress.dismiss();
                    Toast.makeText(RegisterActivity.this,"Error While Register",Toast.LENGTH_LONG).show();
                }
            }

        });

    }

    else{
        showProgress.dismiss();
        Toast.makeText(RegisterActivity.this,"Please Enter All Required Fields",Toast.LENGTH_LONG).show();
    }
</code>```

答:
```<code>private FirebaseAuth mAuth;
    mAuth = FirebaseAuth.getInstance();
    final FirebaseUser Theuser = mAuth.getCurrentUser();
      if (Theuser !=null)
    _UID = Theuser.getUid();
</code>```

Body:
I am using Firebase user sign up method with email and password. While creating a new user I also store information such username that later on needs to be displayed in app profile page.

How could I retrieve the username of currently logged in person ?

Thank you in advance

private void registration(){

    final String email = Email.getText().toString().toString().trim();
    final String password = Password.getText().toString().trim();
    final String username = Username.getText().toString().trim();
    final String age = Age.getText().toString().trim();
    final String userID = userAuth.getCurrentUser().getUid();

    if (!TextUtils.isEmpty(email)&& !TextUtils.isEmpty(password)&& !TextUtils.isEmpty(username)&& !TextUtils.isEmpty(age)){

        showProgress.setMessage("Registration in progress...");
        showProgress.show();

        userAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if(task.isSuccessful()) {

                    String user_id = userAuth.getCurrentUser().getUid();
                    DatabaseReference current_user_db = DatbaseOfUsers.child(user_id);
                    current_user_db.child("email").setValue(email);
                    current_user_db.child("username").setValue(username);
                    current_user_db.child("Age").setValue(age);
                    current_user_db.child("uID").setValue(userID);

                    showProgress.dismiss();

                    //After user is created main screen intent is called
                    Intent mainpage = new Intent(RegisterActivity.this, MainPageActivity.class);
                    mainpage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(mainpage);
                }

                else if(!task.isSuccessful()){
                    showProgress.dismiss();
                    Toast.makeText(RegisterActivity.this,"Error While Register",Toast.LENGTH_LONG).show();
                }
            }

        });

    }

    else{
        showProgress.dismiss();
        Toast.makeText(RegisterActivity.this,"Please Enter All Required Fields",Toast.LENGTH_LONG).show();
    }


问:
problem with UIRef in visual Studio
Hi i'm having a problem with UIRef in Visual Studio when i try to add a wxs file.

```<code><UIRef Id="MyWixUI_FeatureTree"/>
<UIRef Id="WixUI_ErrorProgressText" />
</code>```

This is the error:
error LGHT0094 : Unresolved reference to symbol 'WixUI:MyWixUI_FeatureTree' in section 'Product:*'.

I don't know if i must make some changes on the VS settings.
or if I must add other reference.

Thanks!!!

答: Did you create the UI Element "MyWixUI_FeatureTree"?  Is MyWixUI_FeatureTree really WixUI_FeatureTree?  If you reference an element, you need to make sure that element is actually in scope.</p>

Title: problem with UIRef in visual Studio

Body:
Hi i'm having a problem with UIRef in Visual Studio when i try to add a wxs file.

<UIRef Id="MyWixUI_FeatureTree"/>
<UIRef Id="WixUI_ErrorProgressText" />

This is the error:
error LGHT0094 : Unresolved reference to symbol 'WixUI:MyWixUI_FeatureTree' in section 'Product:*'.

I don't know if i must make some changes on the VS settings.
or if I must add other reference.

Thanks!!!


问:
Executing a package manager command on just one project in a solution
I have two projects in my solution, one is a WPF application and the other is a WCF.

I have entity framework on my WCF application and want to execute the Update-Database command since I have added to my initial seed method. How can I run this on the WCF project alone? As of now I get a warning telling me that migrations are not enabled for my WPF project.

答: You may also select the project in the "Default project:" ComboBox in the Package Manager Console in Visual Studio:


答:
You should use the .container-fluid class if you want your content to span the full width of the document. Without this class the negative margins of .row will cause horizontal scrolling.

You could possibly omit the container-fluid and row but this may cause unexpected results when using other Bootstrap components.

.col-md-4 {
  background: red;
}

.col-md-8 {
  background: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container-fluid">
  <div class="row">
    <div class="col-md-4"> ... </div>
    <div class="col-md-8"> ... </div>
  </div>
</div></code>```

Title: Do you need to use Bootstrap's "container" and "row" if your content is to span the whole width?

Body:
You should use the .container-fluid class if you want your content to span the full width of the document. Without this class the negative margins of .row will cause horizontal scrolling.

You could possibly omit the container-fluid and row but this may cause unexpected results when using other Bootstrap components.

.col-md-4 {
  background: red;
}

.col-md-8 {
  background: green;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container-fluid">
  <div class="row">
    <div class="col-md-4"> ... </div>
    <div class="col-md-8"> ... </div>
  </div>
</div>


问:
How can I add a second nic in Test Kitchen with the ec2 driver?
Looking at the readme I see lots of options for adding extra storage but nothing for a second nic. Is it possible?</p>

答: This is not possible at this time. This would usually only matter for multi-server or cluster testing in general which is something we don't currently support very well (or really, at all). You could try using Kitchen-Terraform to work around this.</p>


问:
AnimationDrawable doesn't autostart on Lollipop
I have an Android App where looped AnimationDrawbale where autostarted. With latest Lollipop it doesn't autostart no more.

There is a simple ImageView where the src address the next drawable xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<level-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="0" android:drawable="@drawable/ic_weather_sun" />
    <item android:maxLevel="1" android:drawable="@drawable/ic_weather_cloudsun" />
    <item android:maxLevel="2" android:drawable="@drawable/ic_weather_cloud" />
    <item android:maxLevel="3" android:drawable="@drawable/ic_weather_rain" />
    <item android:maxLevel="4" android:drawable="@drawable/ic_weather_rainstorm" />
</level-list>
</code>```

each item of the level list is another drawable xml.
Some of them are animation-list (Animationdrawable), others are layer-list with one or more layer composed by an animation-list. Here an example:

```<code><layer-list
   xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <animation-list android:oneshot="false">
            <item android:drawable="@drawable/ic_weather_layer_rain1" android:duration="100" />
            <item android:drawable="@drawable/ic_weather_layer_rain2" android:duration="100" />
            <item android:drawable="@drawable/ic_weather_layer_rain3" android:duration="100" />
            <item android:drawable="@drawable/ic_weather_layer_rain4" android:duration="100" />
        </animation-list>
    </item>
    <item android:drawable="@drawable/ic_weather_layer_cloudcolor1" />
    <item android:drawable="@drawable/ic_weather_layer_cloud2" />
    <item android:drawable="@drawable/ic_weather_layer_cloud1" />
</layer-list>
</code>```

The ImageView level is set invisible at activity start and it is simply selected in this way.

```<code>    final ImageView meteo = (ImageView)findViewById(R.id.image_meteo);
    meteo.setVisibility(View.VISIBLE);
    meteo.setImageLevel( weatherIdx );
</code>```

Any idea on th reason? And how I should manage that?
I cannot address all AnimationDrawables, because there are several of them in a not known structure.

Thanks

答:
Here is a class based on AppCompatImageView that will autostart both the source and background AnimationDrawables.

```<code>public class AnimationImageView extends AppCompatImageView
{
    public AnimationImageView(Context context)
    {
        super(context);
    }

    public AnimationImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public AnimationImageView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setBackgroundResource(@DrawableRes int resId)
    {
        super.setBackgroundResource(resId);
        startAnimation(getBackground());
    }

    @Override
    public void setBackgroundDrawable(Drawable background)
    {
        super.setBackgroundDrawable(background);
        startAnimation(background);
    }

    @Override
    public void setImageResource(@DrawableRes int resId)
    {
        super.setImageResource(resId);
        startAnimation(getDrawable());
    }

    @Override
    public void setImageDrawable(@Nullable Drawable drawable)
    {
        super.setImageDrawable(drawable);
        startAnimation(drawable);
    }

    protected void startAnimation(Drawable drawable)
    {
        if (drawable instanceof AnimationDrawable)
        {
            ((AnimationDrawable) drawable).start();
        }
    }
}
</code>```

You can use it in your layouts as follows (change com.sample.ui.views to match the package where you will place the class above):

```<code><com.sample.ui.views.AnimationImageView
    android:id="@+id/iv_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_src_animation"
    android:background="@drawable/my_bg_animation"/>
</code>```

Body:
I have an Android App where looped AnimationDrawbale where autostarted. With latest Lollipop it doesn't autostart no more.

There is a simple ImageView where the src address the next drawable xml:

<?xml version="1.0" encoding="utf-8"?>
<level-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="0" android:drawable="@drawable/ic_weather_sun" />
    <item android:maxLevel="1" android:drawable="@drawable/ic_weather_cloudsun" />
    <item android:maxLevel="2" android:drawable="@drawable/ic_weather_cloud" />
    <item android:maxLevel="3" android:drawable="@drawable/ic_weather_rain" />
    <item android:maxLevel="4" android:drawable="@drawable/ic_weather_rainstorm" />
</level-list>

each item of the level list is another drawable xml.
Some of them are animation-list (Animationdrawable), others are layer-list with one or more layer composed by an animation-list. Here an example:

<layer-list
   xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <animation-list android:oneshot="false">
            <item android:drawable="@drawable/ic_weather_layer_rain1" android:duration="100" />
            <item android:drawable="@drawable/ic_weather_layer_rain2" android:duration="100" />
            <item android:drawable="@drawable/ic_weather_layer_rain3" android:duration="100" />
            <item android:drawable="@drawable/ic_weather_layer_rain4" android:duration="100" />
        </animation-list>
    </item>
    <item android:drawable="@drawable/ic_weather_layer_cloudcolor1" />
    <item android:drawable="@drawable/ic_weather_layer_cloud2" />
    <item android:drawable="@drawable/ic_weather_layer_cloud1" />
</layer-list>

The ImageView level is set invisible at activity start and it is simply selected in this way.

    final ImageView meteo = (ImageView)findViewById(R.id.image_meteo);
    meteo.setVisibility(View.VISIBLE);
    meteo.setImageLevel( weatherIdx );

Any idea on th reason? And how I should manage that?
I cannot address all AnimationDrawables, because there are several of them in a not known structure.

Thanks

Body:
Here is a class based on AppCompatImageView that will autostart both the source and background AnimationDrawables.

public class AnimationImageView extends AppCompatImageView
{
    public AnimationImageView(Context context)
    {
        super(context);
    }

    public AnimationImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public AnimationImageView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setBackgroundResource(@DrawableRes int resId)
    {
        super.setBackgroundResource(resId);
        startAnimation(getBackground());
    }

    @Override
    public void setBackgroundDrawable(Drawable background)
    {
        super.setBackgroundDrawable(background);
        startAnimation(background);
    }

    @Override
    public void setImageResource(@DrawableRes int resId)
    {
        super.setImageResource(resId);
        startAnimation(getDrawable());
    }

    @Override
    public void setImageDrawable(@Nullable Drawable drawable)
    {
        super.setImageDrawable(drawable);
        startAnimation(drawable);
    }

    protected void startAnimation(Drawable drawable)
    {
        if (drawable instanceof AnimationDrawable)
        {
            ((AnimationDrawable) drawable).start();
        }
    }
}

You can use it in your layouts as follows (change com.sample.ui.views to match the package where you will place the class above):

<com.sample.ui.views.AnimationImageView
    android:id="@+id/iv_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_src_animation"
    android:background="@drawable/my_bg_animation"/>


问:
How does srand relate to rand function?
I understand that rand() function generates the same number(s) each you run it if you don't change the seed number. That's where srand() comes in. Time is always changing so I know that you should pass the time(null) parameter to srand. My question is with the code below from a tutorial site.

```<code>int main()
{
    int i, n=5;
    time_t t;

    /* Intializes random number generator */
    srand((unsigned) time(&t));

    /* Print 5 random numbers from 0 to 50 */
    for( i = 0 ; i < n ; i++ ) {
        printf("%d\n", rand() % 50);
    }

    return(0);
}
</code>```

I see no link from the srand

```<code>((unsigned) time(&t));
</code>```

and rand.

```<code>printf("%d\n", rand() % 50);
</code>```

Where is the connection between rand and srand? What I mean or expect is I assume rand() will get some parameter from srand() so it knows to generate different numbers each time. I assume it would look something like rand(srand(time(null));

It's like initializing a variable without using it to me. srand is being initialized, but I don't see it being used.

Does rand generate different numbers because srand is called first before rand?

答:
rand gives you a pseudo random sequence of numbers.

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.

srand  on each call sets the pointer to some location in the list which you are getting in. If you don't call it on each attempt or give it a fix seed it will give you the same sequence. So many suggest giving the current second as seed. But if you try running your code in the same second twice, it will give you same sequence.

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand for further explanation

Title: How does srand relate to rand function?

Body:
I understand that rand() function generates the same number(s) each you run it if you don't change the seed number. That's where srand() comes in. Time is always changing so I know that you should pass the time(null) parameter to srand. My question is with the code below from a tutorial site.

int main()
{
    int i, n=5;
    time_t t;

    /* Intializes random number generator */
    srand((unsigned) time(&t));

    /* Print 5 random numbers from 0 to 50 */
    for( i = 0 ; i < n ; i++ ) {
        printf("%d\n", rand() % 50);
    }

    return(0);
}

I see no link from the srand

((unsigned) time(&t));

and rand.

printf("%d\n", rand() % 50);

Where is the connection between rand and srand? What I mean or expect is I assume rand() will get some parameter from srand() so it knows to generate different numbers each time. I assume it would look something like rand(srand(time(null));

It's like initializing a variable without using it to me. srand is being initialized, but I don't see it being used.

Does rand generate different numbers because srand is called first before rand?


问:
access denied for load data infile in MySQL
I use MySQL queries all the time in PHP, but when I try

LOAD DATA INFILE
```

I get the following error

#1045 - Access denied for user 'user'@'localhost' (using password: YES)

Does anyone know what this means?

答:
Try using this command:

```<code>load data local infile 'home/data.txt' into table customer;
</code>```

This should work. It worked in my case.

Body:
I use MySQL queries all the time in PHP, but when I try

LOAD DATA INFILE

I get the following error

#1045 - Access denied for user 'user'@'localhost' (using password: YES)

Does anyone know what this means?

Body:
Try using this command:

load data local infile 'home/data.txt' into table customer;

This should work. It worked in my case.


问:
java.lang.ClassNotFoundException: org.springframework.expression.ParserContext Spring HelloWorld?
I have simple Spring HelloWorld program. Its contents are as follows:

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mahesha999.examples.spring</groupId>
    <artifactId>SpringExamples</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
    </dependencies>

</project>
</code>```

eg1.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean id="helloBean" class="com.mahesha999.examples.spring.eg1.HelloWorld">
        <property name="name" value="Mahesha999" />
    </bean>

</beans>
</code>```

HelloWorld.java

```<code>public class HelloWorld {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void printHello() {
        System.out.println("Spring  : Hello ! " + name);
    }
}
</code>```

App.java

```<code>import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("eg1.xml");

        HelloWorld obj = (HelloWorld) context.getBean("helloBean");
        obj.printHello();
    }
}
</code>```

This gave me following error:

```<code>INFO: Loading XML bean definitions from class path resource [eg1.xml]
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/expression/ParserContext
    at org.springframework.context.support.AbstractApplicationContext.prepareBeanFactory(AbstractApplicationContext.java:628)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:516)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.mahesha999.examples.spring.eg1.App.main(App.java:8)
Caused by: java.lang.ClassNotFoundException: org.springframework.expression.ParserContext
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 5 more
</code>```

When I changed spring version from 4.3.2 to 4.2.2 in pom.xml, it worked fine. Why is it so?

答: I was also getting the same error and it got fixed after adding the spring-expression jar </p>

Body:
I have simple Spring HelloWorld program. Its contents are as follows:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mahesha999.examples.spring</groupId>
    <artifactId>SpringExamples</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
    </dependencies>

</project>

eg1.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean id="helloBean" class="com.mahesha999.examples.spring.eg1.HelloWorld">
        <property name="name" value="Mahesha999" />
    </bean>

</beans>

HelloWorld.java

public class HelloWorld {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void printHello() {
        System.out.println("Spring  : Hello ! " + name);
    }
}

App.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("eg1.xml");

        HelloWorld obj = (HelloWorld) context.getBean("helloBean");
        obj.printHello();
    }
}

This gave me following error:

INFO: Loading XML bean definitions from class path resource [eg1.xml]
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/expression/ParserContext
    at org.springframework.context.support.AbstractApplicationContext.prepareBeanFactory(AbstractApplicationContext.java:628)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:516)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.mahesha999.examples.spring.eg1.App.main(App.java:8)
Caused by: java.lang.ClassNotFoundException: org.springframework.expression.ParserContext
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 5 more

When I changed spring version from 4.3.2 to 4.2.2 in pom.xml, it worked fine. Why is it so?


问:
Regex in Python?
I have a string:

```<code>line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
</code>```

I want to get this result:

```<code>[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]
</code>```

I tried this:

```<code>match = re.findall("(^[a-z]+[^://](^[a-z]+\d))", line)
</code>```

I'm a beginner in Python.  If there is somebody who can explain, it would be very nice :D

答:
Instead of using regex, try using line.split(',') Then iterate through the list, like

myList=[]
for l in line.split(','):
    myList.append(tuple(m.split('/')[0:2]))

It isn't pretty, but it gets around the problem of regex. It doesn't get into the specifics of the URL and FTP, but you can eliminate those systematically.

Title: Regex in Python?

Body:
I have a string:

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

I want to get this result:

[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]

I tried this:

match = re.findall("(^[a-z]+[^://](^[a-z]+\d))", line)

I'm a beginner in Python.  If there is somebody who can explain, it would be very nice :D


问:
How to differentiate model classes between webapp and unittest
I've started looking in to unittest when using google app engine. And it seems to bit tricky from what I've read. Since you can't (and not suppose to) run your test's against the datastore.

I've written an abstract class to emulate a datastore model class. And it quite works pretty nice returning mockup data on get, all, fetch and so on (only tried on a small scale) returning dbModel like results.

The one thing I haven't found a solution I'm satisfied with is how to differentiate which model class to use. I want to use the mock-ups for unit tests and the actual db.Model for when webapp is running.

My current solution looks like this in my .py containing all db.Models:

```<code>if 'SERVER_SOFTWARE' in os.environ:
    class dbTest(db.Model):
        content = db.StringProperty()
        comments = db.ListProperty(str)
else:
    class dbTest(Abstract):
        content = 'Test'
        comments = ['test1', 'test2']
</code>```

And it kinda feels like it could break any minute. Is this the way to go or could one combine these as one class and if the db.Model is invoked properly use that else the mockup?

答:
There's more than one problem you're trying to address here...

First, for running tests with GAE emulation you can take a look at gaeunit, which I like best. If you don't want to run them from the browser then you can take a look at noseGAE (part of nose). This should give you command-line testing.

Second, regarding your comment about about 'creating an overhead of dependencies' it sounds like you're searching for a good unit testing and mocking framework. These will let you mock out the database for tests which don't need to hit it. Try mox and mockito for python.

Body:
I've started looking in to unittest when using google app engine. And it seems to bit tricky from what I've read. Since you can't (and not suppose to) run your test's against the datastore.

I've written an abstract class to emulate a datastore model class. And it quite works pretty nice returning mockup data on get, all, fetch and so on (only tried on a small scale) returning dbModel like results.

The one thing I haven't found a solution I'm satisfied with is how to differentiate which model class to use. I want to use the mock-ups for unit tests and the actual db.Model for when webapp is running.

My current solution looks like this in my .py containing all db.Models:

if 'SERVER_SOFTWARE' in os.environ:
    class dbTest(db.Model):
        content = db.StringProperty()
        comments = db.ListProperty(str)
else:
    class dbTest(Abstract):
        content = 'Test'
        comments = ['test1', 'test2']

And it kinda feels like it could break any minute. Is this the way to go or could one combine these as one class and if the db.Model is invoked properly use that else the mockup?


问:
DocumentDb .NET Core SDK - IQueryable.OrderBy generates invalid query
The following code is for an ASP.NET Core API that uses Microsoft.Azure.DocumentDB.Core(version 1.2.1) package and LINQ to construct a query against DocumentDb database.

However, the generated query is invalid!

```<code>public async Task<IEnumerable<T>> QueryAsync
  (Expression<Func<T, bool>> predicate, string orderByProperty)
{
   client.CreateDocumentQuery<T>(myCollectionUri)
       .Where(predicate)
       .OrderBy(x => orderByProperty)
       .AsDocumentQuery();

   /* rest of the code... */
}

// And I call it:
await repository.QueryAsync<Book>(x => x.Author == "Joe", "Price");

// class Book is a POCO with 3 properties: string Title, string Author, and decimal Price

/*
INVALID generated query:
    SELECT * FROM root WHERE (root["Author"] = "Joe") ORDER BY "Price"

Correct query:
    SELECT * FROM root WHERE (root["Author"] = "Joe") ORDER BY root["Price"]
*/
</code>```

Is it possible to change this behavior?

Maybe by writing an extension method on IQueryable<T> and calling it like this:

```<code>client.CreateDocumentQuery<T>(myCollectionUri)
    .Where(predicate)
    .DocumentDbOrderBy(orderByProperty) // new extension method
    .AsDocumentQuery();
</code>```

答:
I resolved this issue by using Dynamic LINQ.

Added the using statement to my repository class:

```<code>using System.Linq.Dynamic.Core;
</code>```

And a small change in the method:

```<code>public async Task<IEnumerable<T>> QueryAsync
  (Expression<Func<T, bool>> predicate, string orderByProperty)
{
   client.CreateDocumentQuery<T>(myCollectionUri)
       .Where(predicate)
       .OrderBy(orderByProperty)   // uses dynamic LINQ
       .AsDocumentQuery();

   /* rest of the code... */
}
</code>```

Body:
The following code is for an ASP.NET Core API that uses Microsoft.Azure.DocumentDB.Core(version 1.2.1) package and LINQ to construct a query against DocumentDb database.

However, the generated query is invalid!

public async Task<IEnumerable<T>> QueryAsync
  (Expression<Func<T, bool>> predicate, string orderByProperty)
{
   client.CreateDocumentQuery<T>(myCollectionUri)
       .Where(predicate)
       .OrderBy(x => orderByProperty)
       .AsDocumentQuery();

   /* rest of the code... */
}

// And I call it:
await repository.QueryAsync<Book>(x => x.Author == "Joe", "Price");

// class Book is a POCO with 3 properties: string Title, string Author, and decimal Price

/*
INVALID generated query:
    SELECT * FROM root WHERE (root["Author"] = "Joe") ORDER BY "Price"

Correct query:
    SELECT * FROM root WHERE (root["Author"] = "Joe") ORDER BY root["Price"]
*/

Is it possible to change this behavior?

Maybe by writing an extension method on IQueryable<T> and calling it like this:

client.CreateDocumentQuery<T>(myCollectionUri)
    .Where(predicate)
    .DocumentDbOrderBy(orderByProperty) // new extension method
    .AsDocumentQuery();

Body:
I resolved this issue by using Dynamic LINQ.

Added the using statement to my repository class:

using System.Linq.Dynamic.Core;

And a small change in the method:

public async Task<IEnumerable<T>> QueryAsync
  (Expression<Func<T, bool>> predicate, string orderByProperty)
{
   client.CreateDocumentQuery<T>(myCollectionUri)
       .Where(predicate)
       .OrderBy(orderByProperty)   // uses dynamic LINQ
       .AsDocumentQuery();

   /* rest of the code... */
}


问:
Is PouchDB with LevelDB adapter supposed to create a local file?
This leaflet example (Leaflet.TileLayer.PouchDBCached) is using an "idb" adapter and for electron/node it looks like I want to use a "leveldb" adapter. So I followed the instructions here: PouchDB in Node.js

In Node.js, the adapter situation is much simpler than in browsers. By
  default, if you create a PouchDB like this one:

var pouch = new PouchDB('./path/to/db');

then a LevelDB-based database will be created in the directory
  ./path/to/db. The LevelDB implementation uses LevelDOWN.

In my "main.js" (Electron entry point) I create a db like this:

```<code>var dbPath = path.join(__dirname, 'main-db');
var myDB = new PouchDB(dbPath);
console.log('myDB', myDB.adapter);
</code>```

And though the adapter type is reported as "leveldb" it does not show up on disk.

Question: Where is the database created? I've looked in my app directory, in the node_modules/pouchdb directory. I've even looked for "hidden files" (this is on OSX). What gives? If I dump the db instance to the console, it looks like it was created (in memory). Am I "doing it wrong"?

答:
So it turns out I had a couple of things going wrong.

The path I was using was incorrect. Even though I was trying to create the pouchDB instance from a Javascript file attached to an index.html file inside my app folder, this path did not work: './db/todo-db'. I was able to create the db instance using this path: './app/db/todo-db'.

This seems odd to me and I don't understand it. The __dirname reports that my JS context was './path/to/app/ – so I am already inside the app folder.

I was getting an error message about a mismatch between the NODE version which levelDB (the adapter I was requesting) was compiled for. I was able to solve this by using electron-rebuild in a postinstall call:

In my package.json:

```<code>  "scripts": {
    "start": "electron .",
    "postinstall": "electron-rebuild",
   etc.
  }
</code>```

Body:
This leaflet example (Leaflet.TileLayer.PouchDBCached) is using an "idb" adapter and for electron/node it looks like I want to use a "leveldb" adapter. So I followed the instructions here: PouchDB in Node.js

In Node.js, the adapter situation is much simpler than in browsers. By
  default, if you create a PouchDB like this one:

var pouch = new PouchDB('./path/to/db');

then a LevelDB-based database will be created in the directory
  ./path/to/db. The LevelDB implementation uses LevelDOWN.

In my "main.js" (Electron entry point) I create a db like this:

var dbPath = path.join(__dirname, 'main-db');
var myDB = new PouchDB(dbPath);
console.log('myDB', myDB.adapter);

And though the adapter type is reported as "leveldb" it does not show up on disk.

Question: Where is the database created? I've looked in my app directory, in the node_modules/pouchdb directory. I've even looked for "hidden files" (this is on OSX). What gives? If I dump the db instance to the console, it looks like it was created (in memory). Am I "doing it wrong"?

Body:
So it turns out I had a couple of things going wrong.

The path I was using was incorrect. Even though I was trying to create the pouchDB instance from a Javascript file attached to an index.html file inside my app folder, this path did not work: './db/todo-db'. I was able to create the db instance using this path: './app/db/todo-db'.

This seems odd to me and I don't understand it. The __dirname reports that my JS context was './path/to/app/ – so I am already inside the app folder.

I was getting an error message about a mismatch between the NODE version which levelDB (the adapter I was requesting) was compiled for. I was able to solve this by using electron-rebuild in a postinstall call:

In my package.json:

  "scripts": {
    "start": "electron .",
    "postinstall": "electron-rebuild",
   etc.
  }


问:
What separates a content management system from just a bunch of web pages?
I have a website that has related pages.  They have links that point back and forth to one another but I have no integrated system, nor do I know what that would mean.

What is the minimum code that a group of web pages must have to be considered a Content Management System (CMS).  Is it that all the settings are in the database and the pages are generated somehow?  Is there some small snippet that all my pages could share that makes them a CMS, database or not?

Thanks.  I was also hoping not to have to study a giant CMS to see what makes it a CMS .  After maybe a basic understanding I would know what I was looking for.

edit:  here's why I ask about code.  Whenever I have looked at a CMS, and maybe they aren't all the same, I saw that to develop a module you always had to inherit from certain classes and had some necessary code.  I didn't know if there was some magic model that I just don't get that all cms makers understand.

edit:  perhaps my question is more about being extendable or pluggable.  What would a minimum look like?  Is it possible to show that here?

edit:  how about this?  Is something a CMS if it is not extendable and/or pluggable?

答:
A Content Management System is a System that Manages Content. :)
So if you got many pages that share the same layout, you can create a system that stores the content into a database and when a page is requested, it gets that content, merges it with a template that contains the page header, menu, etc.. and outputs the result.

The basis idea is that you don't want to copy HTML pages, and have to edit hundreds of them when you want to change your layout.

Such a system can be very complex, featuring wysiwyg editors, toolbars, version control, multiple user publishing and much more, but it could be as simple as a single page behind a standard loging, that contains only an input field for the title and a textarea in which you type the html content.


问:
Android Here Maps classes missing
Using here Android maps SDK. Registered at site, downloaded sdk BUT
can't find there classes that I really need:

```<code>MapLoader and MapLoader.Listener
</code>```

and

```<code>installMapPackages(List<Integer> packageIdList)
</code>```

Seems that SDK changed dramatically or what is the point?

https://developer.here.com/mobile-sdks/documentation/android-premium/topics/maps-offline.html

答: I think you need to download SDK here anroid sdk</p>

Title: Android Here Maps classes missing

Body:
Using here Android maps SDK. Registered at site, downloaded sdk BUT
can't find there classes that I really need:

MapLoader and MapLoader.Listener

and

installMapPackages(List<Integer> packageIdList)

Seems that SDK changed dramatically or what is the point?

https://developer.here.com/mobile-sdks/documentation/android-premium/topics/maps-offline.html


问:
Angular file upload with rest easy jax rs java ee web service
I am trying to upload an image to a server using Angular as the front end and java ee web service jax rs rest easy as my back end. This my code for the angular/front end:

HTML page:

```<code><md-card>
  <input type="file" (change)="onChange($event)" placeholder="Upload          files" >

</md-card>
</code>```

For the component:

```<code>fileChange(event) {
    let fileList: FileList = event.target.files;
    let fileListLength = fileList.length;
    if(fileListLength > 0) {
        let formData:FormData = new FormData();
        for (var i = 0; i < fileListLength; i++) {
        formData.append("uploadFile[]", fileList[i]);
    }

    let headers = new Headers();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post("http://localhost:8080/BCWEB/uploadProdImage", formData, options)
        .map(res => res.json())
        .catch(error => Observable.throw(error))
        .subscribe(
             data => console.log('success'),
             error => console.log(error)
        )
    }
}
</code>```

For the backend java ee restful web service:

```<code>private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://Users/007EAA/Downloads/tes/";

@POST
@Path("/uploadProdImage")
@Consumes("multipart/form-data")
public Response uploadFile2(MultipartFormDataInput input) {

    String fileName = "";

    Map<String, List<InputPart>> formParts = input.getFormDataMap();

    List<InputPart> inPart = formParts.get("file");

    for (InputPart inputPart : inPart) {

         try {

            // Retrieve headers, read the Content-Disposition header to obtain the original name of the file
            MultivaluedMap<String, String> headers = inputPart.getHeaders();
            fileName = parseFileName(headers);

            // Handle the body of that part with an InputStream
            InputStream istream = inputPart.getBody(InputStream.class,null);

            fileName = SERVER_UPLOAD_LOCATION_FOLDER + fileName;

            saveFile(istream,fileName);

          } catch (IOException e) {
            e.printStackTrace();
          }

        }

            String output = "File saved to server location : " + fileName;

    return Response.status(200).entity(output).build();
}

// Parse Content-Disposition header to get the original file name
private String parseFileName(MultivaluedMap<String, String> headers) {

    String[] contentDispositionHeader = headers.getFirst("Content-Disposition").split(";");

    for (String name : contentDispositionHeader) {

        if ((name.trim().startsWith("filename"))) {

            String[] tmp = name.split("=");

            String fileName = tmp[1].trim().replaceAll("\"","");

            return fileName;
        }
    }
    return "randomName";
}

// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream,
    String serverLocation) {

    try {
        OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        outpuStream = new FileOutputStream(new File(serverLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            outpuStream.write(bytes, 0, read);
        }
        outpuStream.flush();
        outpuStream.close();
    } catch (IOException e) {

        e.printStackTrace();
    }
}
</code>```

The problem is No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had an HTTP status code of 500.

But when I try to add a user on the server, it gets added without any problem, so it's not a server problem. Can anyone help?

答:
The issue is that your frontend and backend exist across different local hosts, and by default cross-origin requests are denied for security reasons.

You'll want to enable cross origin requests on your backend during testing, and disable it for production when your frontend and backend live in the same area. To enable cross origin, you'll need to add this provider snippet:

```<code>package com.yourdomain.package;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSFilter implements ContainerResponseFilter {

   @Override
   public void filter(final ContainerRequestContext requestContext,
                      final ContainerResponseContext cres) throws IOException {
      cres.getHeaders().add("Access-Control-Allow-Origin", "*");
      cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
      cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
      cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
      cres.getHeaders().add("Access-Control-Max-Age", "1209600");
   }

}
</code>```

Info on CORS

Snippet pulled from this SO question

Body:
I am trying to upload an image to a server using Angular as the front end and java ee web service jax rs rest easy as my back end. This my code for the angular/front end:

HTML page:

<md-card>
  <input type="file" (change)="onChange($event)" placeholder="Upload          files" >

</md-card>

For the component:

fileChange(event) {
    let fileList: FileList = event.target.files;
    let fileListLength = fileList.length;
    if(fileListLength > 0) {
        let formData:FormData = new FormData();
        for (var i = 0; i < fileListLength; i++) {
        formData.append("uploadFile[]", fileList[i]);
    }

    let headers = new Headers();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post("http://localhost:8080/BCWEB/uploadProdImage", formData, options)
        .map(res => res.json())
        .catch(error => Observable.throw(error))
        .subscribe(
             data => console.log('success'),
             error => console.log(error)
        )
    }
}

For the backend java ee restful web service:

private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://Users/007EAA/Downloads/tes/";

@POST
@Path("/uploadProdImage")
@Consumes("multipart/form-data")
public Response uploadFile2(MultipartFormDataInput input) {

    String fileName = "";

    Map<String, List<InputPart>> formParts = input.getFormDataMap();

    List<InputPart> inPart = formParts.get("file");

    for (InputPart inputPart : inPart) {

         try {

            // Retrieve headers, read the Content-Disposition header to obtain the original name of the file
            MultivaluedMap<String, String> headers = inputPart.getHeaders();
            fileName = parseFileName(headers);

            // Handle the body of that part with an InputStream
            InputStream istream = inputPart.getBody(InputStream.class,null);

            fileName = SERVER_UPLOAD_LOCATION_FOLDER + fileName;

            saveFile(istream,fileName);

          } catch (IOException e) {
            e.printStackTrace();
          }

        }

            String output = "File saved to server location : " + fileName;

    return Response.status(200).entity(output).build();
}

// Parse Content-Disposition header to get the original file name
private String parseFileName(MultivaluedMap<String, String> headers) {

    String[] contentDispositionHeader = headers.getFirst("Content-Disposition").split(";");

    for (String name : contentDispositionHeader) {

        if ((name.trim().startsWith("filename"))) {

            String[] tmp = name.split("=");

            String fileName = tmp[1].trim().replaceAll("\"","");

            return fileName;
        }
    }
    return "randomName";
}

// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream,
    String serverLocation) {

    try {
        OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        outpuStream = new FileOutputStream(new File(serverLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            outpuStream.write(bytes, 0, read);
        }
        outpuStream.flush();
        outpuStream.close();
    } catch (IOException e) {

        e.printStackTrace();
    }
}

The problem is No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had an HTTP status code of 500.

But when I try to add a user on the server, it gets added without any problem, so it's not a server problem. Can anyone help?

Body:
The issue is that your frontend and backend exist across different local hosts, and by default cross-origin requests are denied for security reasons.

You'll want to enable cross origin requests on your backend during testing, and disable it for production when your frontend and backend live in the same area. To enable cross origin, you'll need to add this provider snippet:

package com.yourdomain.package;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSFilter implements ContainerResponseFilter {

   @Override
   public void filter(final ContainerRequestContext requestContext,
                      final ContainerResponseContext cres) throws IOException {
      cres.getHeaders().add("Access-Control-Allow-Origin", "*");
      cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
      cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
      cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
      cres.getHeaders().add("Access-Control-Max-Age", "1209600");
   }

}

Info on CORS

Snippet pulled from this SO question


问:
Explicit conversion from data type date to int is not allowed
I am trying to calculate AGE of contracts, however I am getting the error

Explicit conversion from data type date to int is not allowed

This is my code:

```<code>SELECT
    Contract_hist.*,
    IB.*,
    CAST((CASE
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT))/365 <= 0
                THEN 0
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365 > 0
                THEN (CAST(CONVERT(INT, Setup.[Start]) CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365
          END) AS INT) AS AGE
FROM
    Setup, Contract_hist
INNER JOIN
    IB ON Contract_hist.[System No] = IB.System_ID
</code>```

Where "Setup.[Start]" & "[IB].[Install_Date]" are datetime2 values.

答:
Maybe this?</p>

```<code>SELECT
Contract_hist.*
,IB.*
,CASE
        WHEN DATEDIFF(year,[IB].[Install_Date], Setup.[Start] ) <= 0 THEN 0
        ELSE DATEDIFF(year, [IB].[Install_Date], Setup.[Start])
 END AS AGE

FROM Setup, Contract_hist
    INNER JOIN IB ON Contract_hist.[System No] = IB.System_ID
</code>```

Body:
I am trying to calculate AGE of contracts, however I am getting the error

Explicit conversion from data type date to int is not allowed

This is my code:

SELECT
    Contract_hist.*,
    IB.*,
    CAST((CASE
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT))/365 <= 0
                THEN 0
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365 > 0
                THEN (CAST(CONVERT(INT, Setup.[Start]) CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365
          END) AS INT) AS AGE
FROM
    Setup, Contract_hist
INNER JOIN
    IB ON Contract_hist.[System No] = IB.System_ID

Where "Setup.[Start]" & "[IB].[Install_Date]" are datetime2 values.

Body:
Maybe this?

SELECT
Contract_hist.*
,IB.*
,CASE
        WHEN DATEDIFF(year,[IB].[Install_Date], Setup.[Start] ) <= 0 THEN 0
        ELSE DATEDIFF(year, [IB].[Install_Date], Setup.[Start])
 END AS AGE

FROM Setup, Contract_hist
    INNER JOIN IB ON Contract_hist.[System No] = IB.System_ID


问:
Symfony Built-in server terminated unexpectedly
I am having a very hard problem to solve, which is that my symfony application server terminates and never loads anything. The message is giving after running the: php bin/console server:run and then load the site in the browser. The browser starts loading the site but after a few minutes it throws this message in the console (not in the web browser): [ERROR] Built-in server terminated unexpectedly. Run the command again with -v option for more details..

I have tried to solve this problem in many ways:

Changed my OS to Windows (I am using Ubuntu 16.04). This did not work, the application just throw a blank page in the browser with not even one error.

Cleared cache.

Changed default port.

Please if any person has been involved in this situation and has left alive from it, help me out, I will appreciate it a lot...

答: I already solved the problem. I upgraded from php 7.0 to php 7.1, it is a bug of php I guess, I can't have any certain conclusion about what the problem was, but this solved it. </p>


问:
Docker, How can I locate the image files after pulling
After pulling image, for example ubuntu, how can I locate the image file on local disk.

```<code>$ docker pull ubuntu
</code>```

Will the image work if I copy the image file to another machine?

OS: macOS

答:
If your Aim is to copy any image from one machine to other.

execute the following in the machine where the images are present

```<code>docker save -o <save image to path> <image name>
</code>```

Then copy your image files to the other machine using any regular file transfer tools such as cp or scp. Then execute the following command there

```<code>docker load -i <path to image tar file>
</code>```

Body:
After pulling image, for example ubuntu, how can I locate the image file on local disk.

$ docker pull ubuntu

Will the image work if I copy the image file to another machine?

OS: macOS

Body:
If your Aim is to copy any image from one machine to other.

execute the following in the machine where the images are present

docker save -o <save image to path> <image name>

Then copy your image files to the other machine using any regular file transfer tools such as cp or scp. Then execute the following command there

docker load -i <path to image tar file>


问:
JavaScript Globals - Method Handling
I have multiple global arrays that a single method performs operations on. The method will only need to operate on one array at a time. I would like to accomplish this by passing a parameter to the method and then let the method decide which array it needs to modify based on that parameter. For example,

```<code>var globalarray1;
var globalarray2;

Operate(globalarray1);

function Operate(globalarray){
   globalarray.push("test");
}
</code>```

Of course, the code above only changes the value of the array local to the scope of the method. I know I can do something like this:

```<code>var globalarray1;
var globalarray2;

Operate(1);

function Operate(flag){
   if (flag == 1){
      globalarray1.push("test1");
   }
   else if (flag == 2){
      globalarray2.push("test2")
   }
}
</code>```

However, it just doesn't feel right. How can I change the value of the globals using parameters in a single method without using a bunch of conditional statements?

答:
Your first approach is correct.  This statement, however, is not:

Of course, the code above only changes the value of the array local to the scope of the method.

Array objects are passed by reference called by sharing (i.e. the reference is passed by value, not the value itself).  When you pass the array to the method, it can (and in your case does) actually modified the global variable.  This would not be the case if you passed in an immutable or primitive value such as a number or a string.  In those cases, the value is in fact local to the scope of the method.

The fact that your variables are global have nothing to do with it.  Take this code, for example:

```<code>function Hello(){
   var localArray = [];
   Operate(localArray);

   // now, localArray has been modified by Operate
}

Hello();
</code>```

Above, localArray is not a global variable, but it can still be affected by Operate() if you pass the array in directly.

Title: JavaScript Globals - Method Handling

Body:
I have multiple global arrays that a single method performs operations on. The method will only need to operate on one array at a time. I would like to accomplish this by passing a parameter to the method and then let the method decide which array it needs to modify based on that parameter. For example,

var globalarray1;
var globalarray2;

Operate(globalarray1);

function Operate(globalarray){
   globalarray.push("test");
}

Of course, the code above only changes the value of the array local to the scope of the method. I know I can do something like this:

var globalarray1;
var globalarray2;

Operate(1);

function Operate(flag){
   if (flag == 1){
      globalarray1.push("test1");
   }
   else if (flag == 2){
      globalarray2.push("test2")
   }
}

However, it just doesn't feel right. How can I change the value of the globals using parameters in a single method without using a bunch of conditional statements?

Body:
Your first approach is correct.  This statement, however, is not:

Of course, the code above only changes the value of the array local to the scope of the method.

Array objects are passed by reference called by sharing (i.e. the reference is passed by value, not the value itself).  When you pass the array to the method, it can (and in your case does) actually modified the global variable.  This would not be the case if you passed in an immutable or primitive value such as a number or a string.  In those cases, the value is in fact local to the scope of the method.

The fact that your variables are global have nothing to do with it.  Take this code, for example:

function Hello(){
   var localArray = [];
   Operate(localArray);

   // now, localArray has been modified by Operate
}

Hello();

Above, localArray is not a global variable, but it can still be affected by Operate() if you pass the array in directly.


问:
Angular2: How to implement more than 2 method
how can i implement Oninit & Ondestroy. I tried below but didn't work for me.

I am extracting id from URL for that i want to use OnDestroy to avoid memory problem and need to call service onInit

import { Component, OnInit, OnDestroy } from '@angular/core';
import { DetailService } from '../detail.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-detail-page',
  templateUrl: './detail-page.component.html',
  styleUrls: ['./detail-page.component.css'],
  providers: [DetailService]
})
export class DetailPageComponent implements OnInit, OnDestroy {
detailData: any;
id:string;
private subscription: Subscription;
  constructor(private detailService: DetailService, private router: Router, private activatedRoute: ActivatedRoute) {
    this.subscription = this.activatedRoute.queryParams.subscribe(
      (param: any) => this.id = param['id']
    );
  }

  ngOnInit() {
        this.detailService.getDetailData()
  .subscribe(
    data => this.detailData = data
  );
}

ngOnDestroy(){
  this.subscription.unsubscribe();
}

}```

答:
Your code syntax looks fine. Did you include DetailService into the snippet?

Notice: Unsubscribing from Activated route is not necessary:

The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

UPDATED:
Instead of activatedRoute.queryParams you might want to use activatedRoute.params

```<code>  constructor(route: ActivatedRoute) {
    this.params = route.params.subscribe(
      params => this.id = params['id']
    );
  }
</code>```

UPDATE2:

Use params when it's a part of the path, e.g {path: 'page/:id'}

Use queryParams when it's an optional query param, e.g: page?id=1

More info is here

Body:
Your code syntax looks fine. Did you include DetailService into the snippet?

Notice: Unsubscribing from Activated route is not necessary:

The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

UPDATED:
Instead of activatedRoute.queryParams you might want to use activatedRoute.params

  constructor(route: ActivatedRoute) {
    this.params = route.params.subscribe(
      params => this.id = params['id']
    );
  }

UPDATE2:

Use params when it's a part of the path, e.g {path: 'page/:id'}

Use queryParams when it's an optional query param, e.g: page?id=1

More info is here


答:
I suggest to use urlparse lib that has everything you need instead of a regex.</p>

```<code>from urllib.parse import urlparse
def getparts(url):
    return (url.scheme, url.hostname, url.port)

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg,\file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
urls = [getparts(urlparse(url)) for url in line.split(',')]
</code>```

Title: Regex in Python?

Body:
I suggest to use urlparse lib that has everything you need instead of a regex.

from urllib.parse import urlparse
def getparts(url):
    return (url.scheme, url.hostname, url.port)

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg,\file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
urls = [getparts(urlparse(url)) for url in line.split(',')]


问:
Has anybody some advice on programming realtime audio synthesis?
I'm currently working on a personal project: creating a library for realtime audio synthesis in Flash. In short: tools to connect wavegenarators, filters, mixers, etc with eachother and supply the soundcard with raw (realtime) data. Something like max/msp or Reaktor.

I already have some working stuff, but I'm wondering if the basic setup that I wrote is right. I don't want to run into problems later on that force me to change the core of my app (although that can always happen).

Basically, what I do now is start at the end of the chain, at the place where the (raw) sounddata goes 'out' (to the soundcard). To do that, I need to write chunks of bytes (ByteArrays) to an object, and to get that chunk I ask whatever module is connected to my 'Sound Out' module to give me his chunk. That module does the same request to the module that's connected to his input, and that keeps happening until the start of the chain is reached.

Is this the right approach? I can imagine running into problems if there's a feedbackloop, or if there's another module with no output: if i were to connect a spectrumanalyzer somewhere, that would be a dead end in the chain (a module with no outputs, just an input). In my current setup, such a module wouldnt work because i only start calculating from the sound-output module.

Has anyone experience with programming something like this? I'd be very interested in some thoughts about the right approach. (For clarity: i'm not looking for specific Flash-implementations, and that's why i didnt tag this question under flash or actionscript)

答:
I did a similar thing a while back, and I used the same approach as you do - start at the virtual line out, and trace the signal back to the top. I did this per sample though, not per buffer; if I were to write the same application today, I might choose per-buffer instead though, because I suspect it would perform better.

The spectrometer was designed as an insert module, that is, it would only work if both its input and its output were connected, and it would pass its input to the output unchanged.

To handle feedback, I had a special helper module that introduced a 1-sample delay and would only fetch its input once per cycle.

Also, I think doing all your internal processing with floats, and thus arrays of floats as the buffers, would be a lot easier than byte arrays, and it would save you the extra effort of converting between integers and floats all the time.