问:
Replace elements in a nested dict with the appropriate in a list
I have such following a dict and a list.

```<code>mylist= ['1H1.PyModule.md',
         '1H2.Class.md',
         '1H3.MetaObject.md',
         '2B1D0.Data.md',
         '2B1D1.Primitive.md',
         '2B1D2.Operator.md',
         '2B2D3.Container.md',
         '2B2S0.Function.md',
         '2B2S0.Statemment.md',
         '2B2S1.Controlled_Loop.md',
         '2B2S2.Conditions.md',
         '2B2S3.Except.md',
         ...
         ]
 mydict = {'Body': {'Data': ['1.primitive', '2.operator', '3.container'],
   'Statement': ['0.function', '1.controlled_loop', '2.condition', '3.except']},
   'Header': ['1.Modle', '2.Class', '3.Object'],
   ...}
</code>```

I attempt to repalce the strings in mydict with the appropriate in mylist

I can figure out '2B1D0.Data.md' has the shortest length,
So I slice the keyward 'Data'

```<code>In [82]: '2B1D0.Data.md'[-7:-3]
Out[82]: 'Data'
</code>```

The dict has both a nested list and nested dict.

So I write a iteration function with type checking

if an item's value isinstance(value,list), renew that value,

if an item's value isinstance(value, dict),call the function replace_ele()to continue.

I name string in mylist as str_of_list,
while string in mydict as str_of_dict for readable concerns.

```<code>#replace one string in mydict
def replace_ele(mydict, str_of_list):
    for key, value in mydict.items():
        if isinstance(value, list): #type checking
            for str_of_dict in value:
                #replace str_of_dict with str_of_list
                if str_of_list[-7:-3].lower() == str_of_dict[-4:]: #[-7:-3] the shortest length
                    value.remove(str_of_dict)
                    value.append(str_of_list)
                    value.sort()
                    mydict[key] = value
        #iteration if a dict
        if isinstance(value, dict):
            replace_ele(value,str_of_list)

for str_of_list in mylist:
    replace_ele(mydict, str_of_list)
</code>```

Then running and outputs:

```<code>Out[117]:
{'Body': {'Data': ['2B1D1.Primitive.md',
   '2B1D2.Operator.md',
   '2B2D3.Container.md'],
  'Statement': ['2B2S0.Function.md',
   '2B2S0.Function.md',
   '2B2S1.Controlled_Loop.md',
   '2B2S3.Except.md']},
 'Header': ['1.Modle', '1H2.Class.md', '1H3.MetaObject.md']
 ....}
</code>```

I assume that such a problem can be solved with less codes.
 However, I cannot find that solution with the limited knowledge.

How to accomplish it elegantly?

答:
My suggestion is that you create a function to reduce element of mylist and elements in lists of mydict values to the same format:

For example, you can split by '.' character, take the second field, convert it to lower case:

```<code>def f(s):
    return s.split('.')[1].lower()
</code>```

E.g.:

```<code>>>> f('2B2S1.Controlled_Loop.md')
'controlled_loop'
>>> f('1.controlled_loop')
'controlled_loop'
</code>```

Now, from mylist create a dict to hold replacements:

```<code>mylist_repl={f(x): x for x in mylist}
</code>```

i.e. mylist_repl contains key: value items such as 'metaobject': '1H3.MetaObject.md'.

With dict mylist_repl and function f, it is easy to transform a list from mydict to the desired value, example:

```<code>>>> [mylist_repl[f(x)] for x in ['1.primitive', '2.operator', '3.container']]
['2B1D1.Primitive.md', '2B1D2.Operator.md', '2B2D3.Container.md']
</code>```

Also note that this dictionary lookup is more efficient (i.e.: faster) than a nested for loop!

If you have different replacement logic, you probably only need to change how f maps items from two different sets to a common key.

Body:
I have such following a dict and a list.

mylist= ['1H1.PyModule.md',
         '1H2.Class.md',
         '1H3.MetaObject.md',
         '2B1D0.Data.md',
         '2B1D1.Primitive.md',
         '2B1D2.Operator.md',
         '2B2D3.Container.md',
         '2B2S0.Function.md',
         '2B2S0.Statemment.md',
         '2B2S1.Controlled_Loop.md',
         '2B2S2.Conditions.md',
         '2B2S3.Except.md',
         ...
         ]
 mydict = {'Body': {'Data': ['1.primitive', '2.operator', '3.container'],
   'Statement': ['0.function', '1.controlled_loop', '2.condition', '3.except']},
   'Header': ['1.Modle', '2.Class', '3.Object'],
   ...}

I attempt to repalce the strings in mydict with the appropriate in mylist

I can figure out '2B1D0.Data.md' has the shortest length,
So I slice the keyward 'Data'

In [82]: '2B1D0.Data.md'[-7:-3]
Out[82]: 'Data'

The dict has both a nested list and nested dict.

So I write a iteration function with type checking

if an item's value isinstance(value,list), renew that value,

if an item's value isinstance(value, dict),call the function replace_ele()to continue.

I name string in mylist as str_of_list,
while string in mydict as str_of_dict for readable concerns.

#replace one string in mydict
def replace_ele(mydict, str_of_list):
    for key, value in mydict.items():
        if isinstance(value, list): #type checking
            for str_of_dict in value:
                #replace str_of_dict with str_of_list
                if str_of_list[-7:-3].lower() == str_of_dict[-4:]: #[-7:-3] the shortest length
                    value.remove(str_of_dict)
                    value.append(str_of_list)
                    value.sort()
                    mydict[key] = value
        #iteration if a dict
        if isinstance(value, dict):
            replace_ele(value,str_of_list)

for str_of_list in mylist:
    replace_ele(mydict, str_of_list)

Then running and outputs:

Out[117]:
{'Body': {'Data': ['2B1D1.Primitive.md',
   '2B1D2.Operator.md',
   '2B2D3.Container.md'],
  'Statement': ['2B2S0.Function.md',
   '2B2S0.Function.md',
   '2B2S1.Controlled_Loop.md',
   '2B2S3.Except.md']},
 'Header': ['1.Modle', '1H2.Class.md', '1H3.MetaObject.md']
 ....}

I assume that such a problem can be solved with less codes.
 However, I cannot find that solution with the limited knowledge.

How to accomplish it elegantly?

Body:
My suggestion is that you create a function to reduce element of mylist and elements in lists of mydict values to the same format:

For example, you can split by '.' character, take the second field, convert it to lower case:

def f(s):
    return s.split('.')[1].lower()

E.g.:

>>> f('2B2S1.Controlled_Loop.md')
'controlled_loop'
>>> f('1.controlled_loop')
'controlled_loop'

Now, from mylist create a dict to hold replacements:

mylist_repl={f(x): x for x in mylist}

i.e. mylist_repl contains key: value items such as 'metaobject': '1H3.MetaObject.md'.

With dict mylist_repl and function f, it is easy to transform a list from mydict to the desired value, example:

>>> [mylist_repl[f(x)] for x in ['1.primitive', '2.operator', '3.container']]
['2B1D1.Primitive.md', '2B1D2.Operator.md', '2B2D3.Container.md']

Also note that this dictionary lookup is more efficient (i.e.: faster) than a nested for loop!

If you have different replacement logic, you probably only need to change how f maps items from two different sets to a common key.


来源: stackexchange

问:
Searching a nested list with recursion
I want to check if a certain number exists in a nested list

```<code>Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

if t==L:
    return True
else:

    return  ASearch(t, L[0]) or ASearch(t, L[1])

ASearch(15,Slist)
</code>```

What is the problem?

Update:

The OP meant to post this:

```<code>Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

    if t==L:
        return True
    return ASearch(t, L[0]) or ASearch(t, L[1])

print(ASearch(15, Slist))
print(ASearch(50, Slist))
</code>```

Expected output:

```<code>False
True
</code>```

Actual output:

```<code>TypeError: 'int' object is not subscriptable
</code>```

答:
Another approach would be flattening the list separately and then checking if the element is included in the flattened list:

```<code>def flatten(L):
    flat = []
    if isinstance(L, list):
        for item in L:
            flat += flatten(item)
    else:
        flat.append(L)
    return flat

def ASearch(t, L):
    return t in flatten(L)
</code>```

You can now call your ASearch function using the element and the list: ASearch(50, nested_list).

Alternatively, you can make ASearch a lambda-function now:

```<code>ASearch = lambda t,L: t in flatten(L)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Searching a nested list with recursion

Body:
I want to check if a certain number exists in a nested list

Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

if t==L:
    return True
else:

    return  ASearch(t, L[0]) or ASearch(t, L[1])

ASearch(15,Slist)

What is the problem?

Update:

The OP meant to post this:

Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

    if t==L:
        return True
    return ASearch(t, L[0]) or ASearch(t, L[1])

print(ASearch(15, Slist))
print(ASearch(50, Slist))

Expected output:

False
True

Actual output:

TypeError: 'int' object is not subscriptable

Body:
Another approach would be flattening the list separately and then checking if the element is included in the flattened list:

def flatten(L):
    flat = []
    if isinstance(L, list):
        for item in L:
            flat += flatten(item)
    else:
        flat.append(L)
    return flat

def ASearch(t, L):
    return t in flatten(L)

You can now call your ASearch function using the element and the list: ASearch(50, nested_list).

Alternatively, you can make ASearch a lambda-function now:

ASearch = lambda t,L: t in flatten(L)


问:
Normalize newlines in C#
I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them.  Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?

So something that would yield this kind of translation table:

```<code>\r     --> \r\n
\n     --> \r\n
\n\n   --> \r\n\r\n
\n\r   --> \r\n
\r\n   --> \r\n
\r\n\n --> \r\n\r\n
</code>```

答:
This is the answer to the question. The given solution replaces a string by the given translation table.
It does not use an expensive regex function.
It also does not use multiple replacement functions that each individually did loop over the data with several checks etc.

So the search is done directly in 1 for loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy function. That are all the loops.
In some cases, a larger page size might be more efficient.

```<code>public static string NormalizeNewLine(this string val)
{
    if (string.IsNullOrEmpty(val))
        return val;

    const int page = 6;
    int a = page;
    int j = 0;
    int len = val.Length;
    char[] res = new char[len];

    for (int i = 0; i < len; i++)
    {
        char ch = val[i];

        if (ch == '\r')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\n')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) //ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else if (ch == '\n')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\r')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) //ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else
        {
            res[j++] = ch;
        }
    }

    return new string(res, 0, j);
}
</code>```

The translation table really appeals to me even if '\n\r' is not actually used on basic platforms. Who would use two types of linebreaks for indicate 2 linebreaks?
If you want to know that, than you need to take a look before to know if the \n and \r both are used seperatly in the same document.

OwnerDisplayName: ctacke

ContentLicense: CC BY-SA 2.5

Title: Normalize newlines in C#

Body:
I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them.  Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?

So something that would yield this kind of translation table:

\r     --> \r\n
\n     --> \r\n
\n\n   --> \r\n\r\n
\n\r   --> \r\n
\r\n   --> \r\n
\r\n\n --> \r\n\r\n

LastEditorDisplayName: Chris

Body:
This is the answer to the question. The given solution replaces a string by the given translation table.
It does not use an expensive regex function.
It also does not use multiple replacement functions that each individually did loop over the data with several checks etc.

So the search is done directly in 1 for loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy function. That are all the loops.
In some cases, a larger page size might be more efficient.

public static string NormalizeNewLine(this string val)
{
    if (string.IsNullOrEmpty(val))
        return val;

    const int page = 6;
    int a = page;
    int j = 0;
    int len = val.Length;
    char[] res = new char[len];

    for (int i = 0; i < len; i++)
    {
        char ch = val[i];

        if (ch == '\r')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\n')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) //ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else if (ch == '\n')
        {
            int ni = i + 1;
            if (ni < len && val[ni] == '\r')
            {
                res[j++] = '\r';
                res[j++] = '\n';
                i++;
            }
            else
            {
                if (a == page) //ensure capacity
                {
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;
                }

                res[j++] = '\r';
                res[j++] = '\n';
                a++;
            }
        }
        else
        {
            res[j++] = ch;
        }
    }

    return new string(res, 0, j);
}

The translation table really appeals to me even if '\n\r' is not actually used on basic platforms. Who would use two types of linebreaks for indicate 2 linebreaks?
If you want to know that, than you need to take a look before to know if the \n and \r both are used seperatly in the same document.

ContentLicense: CC BY-SA 4.0


问:
How to format the data retrieved from a database
Please help me to format the data retrieved from a DB. I want to retrieve data from a DB and display it in a webpage.
The database used here is postgres.
netbeans platform is used for developing web application.

I get the output as a single row

```<code>eg-SSN :1 Subbu TVM SSN :2 Kailas KZH
</code>```

I want it in different rows

```<code>eg-
SSN :1 Subbu TVM
SSN :2 Kailas KZH
</code>```

my code:

```<code>import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class view extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
 out.println("<html>");
    out.println("<head><title>All Employees</title></head>");
    out.println("<body>");
    out.println("<center><h1>All Employees</h1>");
    String ls=System.getProperty("line.separator");
    Connection con = null;
    Statement stmt = null;
    try {
      Class.forName("org.postgresql.Driver");
      con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Project","postgres","1234");
      stmt = con.createStatement();

      ResultSet rs = stmt.executeQuery("SELECT * FROM chef;");
      while (rs.next()) {
        String ssn = rs.getString("ssn");
        String cname = rs.getString("cname");
        String allocation = rs.getString("allocation");
        out.println("SSN :"+ssn+"  "+cname+"  "+allocation);

        //out.print("ssn : " + ssn +"\n" );
        //out.print("name : "+cname+"\n" );
        //out.print("allocation : "+allocation+"\n" );

      }
      rs.close();

    } catch (SQLException e) {
      out.println("An error occured while retrieving " + "all employees: "
          + e.toString());
    } catch (ClassNotFoundException e) {
      throw (new ServletException(e.toString()));
    } finally {
      try {
        if (stmt != null) {
          stmt.close();
        }
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
      }
    }
   out.println("</center>");
    out.println("</body>");
    out.println("</html>");
    out.close();
  }
}
</code>```

答:
Just use

out.write("
");

out.write("SSN :"+ssn+"  "+cname+"  "+allocation);

Body:
Please help me to format the data retrieved from a DB. I want to retrieve data from a DB and display it in a webpage.
The database used here is postgres.
netbeans platform is used for developing web application.

I get the output as a single row

eg-SSN :1 Subbu TVM SSN :2 Kailas KZH

I want it in different rows

eg-
SSN :1 Subbu TVM
SSN :2 Kailas KZH

my code:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class view extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
 out.println("");
    out.println("<title>All Employees</title>");
    out.println("");
    out.println("
All Employees
");
    String ls=System.getProperty("line.separator");
    Connection con = null;
    Statement stmt = null;
    try {
      Class.forName("org.postgresql.Driver");
      con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Project","postgres","1234");
      stmt = con.createStatement();

      ResultSet rs = stmt.executeQuery("SELECT * FROM chef;");
      while (rs.next()) {
        String ssn = rs.getString("ssn");
        String cname = rs.getString("cname");
        String allocation = rs.getString("allocation");
        out.println("SSN :"+ssn+"  "+cname+"  "+allocation);

        //out.print("ssn : " + ssn +"\n" );
        //out.print("name : "+cname+"\n" );
        //out.print("allocation : "+allocation+"\n" );

      }
      rs.close();

    } catch (SQLException e) {
      out.println("An error occured while retrieving " + "all employees: "
          + e.toString());
    } catch (ClassNotFoundException e) {
      throw (new ServletException(e.toString()));
    } finally {
      try {
        if (stmt != null) {
          stmt.close();
        }
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
      }
    }
   out.println("");
    out.println("");
    out.println("");
    out.close();
  }
}

Body:
Just use <br/>

out.write("<br />");

out.write("SSN :"+ssn+"  "+cname+"  "+allocation);


问:
problem with tcp server and client
Hii all, I have already created some programs related to client and server. Today it was my sessional[practical exam] of Client-server technology.

Problem was: i was to add two no's at server sent from client and result back to client.

I tried this solution but some strange solution was there:
Server.java

```<code>import java.net.*;
import java.io.*;

public class Server{
    public static void main(String args[]) throws Exception{
        ServerSocket s = new ServerSocket(7896);
        Socket cs = s.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(cs.getOutputStream()));
        bw.write(br.read() + br.read());
    }
}
</code>```

Client.java

```<code>import java.io.*;
import java.net.*;

public class Client{
public static void main(String args[]) throws Exception{
    Socket s = new Socket("localhost", 7896);
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
    bw.write(3);
    bw.write(4);
    System.out.println("Output is: " + br.read());
}
}
</code>```

when i ran it on dos prompt i got two blank screens; one at client site and one at server site(which was a bit surprising). then i closed server then suddenly i got error msg at client something like connection closed.

Then i ran same program on my ubuntu linux with same jdk 1.6 as it was in windows, and here also blank screens but when i closed server i got:

```<code>Output is: -1
</code>```

Although in exam i done this using DataOutputStream and DataInputStream.

But why the above code is not working.

Can Anyone explain what is happening in the code there.

Thanks

答:
A few comments which might help you reach the correct answer:

The server code as it is can accept
only a single client request since
the accept() call isn't present in
an infinite loop.

When using buffered
streams, make sure you always flush
the OuputStream/Writer to ensure
that the data is actually written
to the client instead of just lying
around in the buffer.

DataInput/OutputStream is absolutely required (or any other approach which logically reads the "number" string and converts it to an appropriate representation which can be added) since just reading from the BufferedReader doesn't fetch you the "numbers".

But the question is, why flushing is required? To answer this question, one has to understand why "buffering" is used in the first place. Why bother wrapping your streams in another stream when you can directly write to your stream? The reason is that I/O operations are really expensive (at least when compared to accessing your RAM or CPU cache/registers). Frequent writes/reads accessing/writing small chunks of data to the HDD can choke up your HDD and bring down the overall performance of your application.

So what's the solution? Write data to the HDD less frequently. Two ways this can be achieved:

Manually allocate a large byte array
and fill up the entire array in a
single read. This is way better than
single byte reads. The byte array
size does require tuning as per your
application needs but for general
purposes 8K should be good to go.

Use a buffered stream. This has the advantage of not exposing the clients to the low level details. Your application can use the "stream" as it sees fit (continuously writing single bytes to it) and the stream would assume the complete responsibility of flushing the buffered data when it sees fit (this depends on the buffer size which you set when creating a buffered stream).

Though the explanation was HDD specific, the same applies to other types of stream like in your case socket.

TL;DR: Buffering improves IO throughput/performance. :)

Title: problem with tcp server and client

Body:
Hii all, I have already created some programs related to client and server. Today it was my sessional[practical exam] of Client-server technology.

Problem was: i was to add two no's at server sent from client and result back to client.

I tried this solution but some strange solution was there:
Server.java

import java.net.*;
import java.io.*;

public class Server{
    public static void main(String args[]) throws Exception{
        ServerSocket s = new ServerSocket(7896);
        Socket cs = s.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(cs.getOutputStream()));
        bw.write(br.read() + br.read());
    }
}

Client.java

import java.io.*;
import java.net.*;

public class Client{
public static void main(String args[]) throws Exception{
    Socket s = new Socket("localhost", 7896);
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
    bw.write(3);
    bw.write(4);
    System.out.println("Output is: " + br.read());
}
}

when i ran it on dos prompt i got two blank screens; one at client site and one at server site(which was a bit surprising). then i closed server then suddenly i got error msg at client something like connection closed.

Then i ran same program on my ubuntu linux with same jdk 1.6 as it was in windows, and here also blank screens but when i closed server i got:

Output is: -1

Although in exam i done this using DataOutputStream and DataInputStream.

But why the above code is not working.

Can Anyone explain what is happening in the code there.

Thanks


问:
Why is the counter decrementing correctly but the countdown is not?
Here is my angular code to define a countdown timer for my website:

function AlbumCtrl($scope, $timeout) {
  $scope.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    $scope.counter--;
    var distance = $scope.counter;
    $scope.countdown = Math.floor(distance / (1000 * 60 * 60 * 24)) + "d " +
      Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + "h " +
      Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + "m " +
      Math.floor(((distance % (1000 * 60)) / 1000)) + "s ";
    if ($scope.counter > 0) {
      mytimeout = $timeout($scope.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!-- added for a working snippet -->

<!doctype html>
<html ng-app>

<head>
  <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
  <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>

<body>
  <div ng-controller="AlbumCtrl">
    {{counter}} {{countdown}}
  </div>
</body>

</html></code>```

The 'counter' appears to decrement correctly on my page but the 'countdown' stays fixed and shows the correct value only on page load or refresh. For example, I get the following output as time passes:

```<code>    1115148833 12d 21h 45m 48s
    1115148745 12d 21h 45m 48s
    1115148693 12d 21h 45m 48s
</code>```

What exactly is going wrong? Thanks for your help.

答:
This is interesting . Your Math.floor function is giving round figure of the fraction and your fraction number changes so minutely with counter , only seconds string  decreases from one number when counter comes to 1095904999. So you are not able to notice the change , see yourself :

function AlbumCtrl($scope, $timeout) {
  $scope.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    --$scope.counter;
    var distance = $scope.counter;
   $scope.countdown = $scope.counter/ (1000 * 60 * 60 * 24) + "d " +
  ( $scope.counter% (1000 * 60 * 60 * 24)) / (1000 * 60 * 60) + "h " +
 ( $scope.counter% (1000 * 60 * 60)) / (1000 * 60)+ "m " +
 (( $scope.counter% (1000 * 60)) / 1000) + "s ";
    if ($scope.counter > 0) {
      mytimeout = $timeout($scope.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!-- added for a working snippet -->

<!doctype html>
<html ng-app>

<head>
  <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
  <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>

<body>
  <div ng-controller="AlbumCtrl">
    {{counter}} {{countdown}}
  </div>
</body>

</html></code>```

Body:
Here is my angular code to define a countdown timer for my website:

function AlbumCtrl($scope, $timeout) {
  $scope.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    $scope.counter--;
    var distance = $scope.counter;
    $scope.countdown = Math.floor(distance / (1000 * 60 * 60 * 24)) + "d " +
      Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) + "h " +
      Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)) + "m " +
      Math.floor(((distance % (1000 * 60)) / 1000)) + "s ";
    if ($scope.counter > 0) {
      mytimeout = $timeout($scope.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}

<!doctype html>

    {{counter}} {{countdown}}

The 'counter' appears to decrement correctly on my page but the 'countdown' stays fixed and shows the correct value only on page load or refresh. For example, I get the following output as time passes:

    1115148833 12d 21h 45m 48s
    1115148745 12d 21h 45m 48s
    1115148693 12d 21h 45m 48s

What exactly is going wrong? Thanks for your help.

Body:
This is interesting . Your Math.floor function is giving round figure of the fraction and your fraction number changes so minutely with counter , only seconds string  decreases from one number when counter comes to 1095904999. So you are not able to notice the change , see yourself :

function AlbumCtrl($scope, $timeout) {
  $scope.counter = new Date("Nov 30, 2017 09:00:00").getTime() - new Date().getTime();
  $scope.onTimeout = function() {
    --$scope.counter;
    var distance = $scope.counter;
   $scope.countdown = $scope.counter/ (1000 * 60 * 60 * 24) + "d " +
  ( $scope.counter% (1000 * 60 * 60 * 24)) / (1000 * 60 * 60) + "h " +
 ( $scope.counter% (1000 * 60 * 60)) / (1000 * 60)+ "m " +
 (( $scope.counter% (1000 * 60)) / 1000) + "s ";
    if ($scope.counter > 0) {
      mytimeout = $timeout($scope.onTimeout, 1000);
    } else {
      alert("Time is up!");
    }
  }

  var mytimeout = $timeout($scope.onTimeout, 1000);
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!-- added for a working snippet -->

<!doctype html>
<html ng-app>

<head>
  <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
  <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>

<body>
  <div ng-controller="AlbumCtrl">
    {{counter}} {{countdown}}
  </div>
</body>

</html>


问:
Mockito- thenReturn(true) still returns false on a mock object
I recently started reading up about Mockito. The following line of code must return true as per my understanding, but it returns false.

Test Class

```<code>public class PersonServiceImplTest {

   Car car;

   @InjectMocks
   CarServiceImpl carService;

   @Mock
   CarDAOImpl carDAO;

   @Before
   public void setUp() {
     MockitoAnnotations.initMocks(this);
   }

   @Test
   public void testUpdateCar() {
     int carId = 1;
     Mockito.when(carDAO.getCarById(any(Integer.class))).thenReturn(new Car());
     carService.updateCar(carId);
Mockito.when(carDAO.isLicenseExpired(any(Car.class))).thenReturn(true);
     Mockito.verify(carDAO).updateCar(any(Car.class));
     Mockito.verify(carDAO, times(1)).isLicenseExpired(any(Car.class));
     Mockito.verify(carDAO, times(1)).issueLicense(any(Car.class));
   }
}
</code>```

Class to be tested

```<code>public class CarServiceImpl implements CarService {

@Autowired carDAO carDAO;

@Override
public Response updateCar(int carId) {

    Car car =carDAO.getCarById(carId);

    try {

        carDAO.updateCar(car);

        if(carDAO.isLicenseExpired(car)))
            carDAO.issueLicense(car);

    } catch (Exception e) {

        log.error(e.getMessage());

        return Response.status(Status.INTERNAL_SERVER_ERROR).build();

    }

    return Response.ok(Status.CREATED).build();
}
</code>```

CarDAOImpl deals with the database, if needed, will update that too.

Thanks in advance.

答:
These two lines are ordered incorrectly:

```<code>carService.updateCar(carId);
Mockito.when(carDAO.isLicenseExpired(Mockito.any(Car.class))).thenReturn(true);
</code>```

The first line in that pair invokes the class-under-test and the second line sets up an expectation of how your carDAO should behave inside the class-under-test. So, you are setting the expectation after you invoke the class-under-test.

The following test will pass:

```<code>@Test
public void testUpdateCar() {
    int carId = 1;

    // establish expectations of how carDAO should behave inside updateCar()
    Mockito.when(carDAO.getCarById(Mockito.any(Integer.class))).thenReturn(new Car());
    Mockito.when(carDAO.isLicenseExpired(Mockito.any(Car.class))).thenReturn(true);

    // invoke the class-under-test
    carService.updateCar(carId);

    // verify that CarService used CarDAO correctly
    Mockito.verify(carDAO).updateCar(Mockito.any(Car.class));
    Mockito.verify(carDAO).isLicenseExpired(Mockito.any(Car.class));
    Mockito.verify(carDAO).issueLicense(Mockito.any(Car.class));
}
</code>```

Body:
I recently started reading up about Mockito. The following line of code must return true as per my understanding, but it returns false.

Test Class

public class PersonServiceImplTest {

   Car car;

   @InjectMocks
   CarServiceImpl carService;

   @Mock
   CarDAOImpl carDAO;

   @Before
   public void setUp() {
     MockitoAnnotations.initMocks(this);
   }

   @Test
   public void testUpdateCar() {
     int carId = 1;
     Mockito.when(carDAO.getCarById(any(Integer.class))).thenReturn(new Car());
     carService.updateCar(carId);
Mockito.when(carDAO.isLicenseExpired(any(Car.class))).thenReturn(true);
     Mockito.verify(carDAO).updateCar(any(Car.class));
     Mockito.verify(carDAO, times(1)).isLicenseExpired(any(Car.class));
     Mockito.verify(carDAO, times(1)).issueLicense(any(Car.class));
   }
}

Class to be tested

public class CarServiceImpl implements CarService {

@Autowired carDAO carDAO;

@Override
public Response updateCar(int carId) {

    Car car =carDAO.getCarById(carId);

    try {

        carDAO.updateCar(car);

        if(carDAO.isLicenseExpired(car)))
            carDAO.issueLicense(car);

    } catch (Exception e) {

        log.error(e.getMessage());

        return Response.status(Status.INTERNAL_SERVER_ERROR).build();

    }

    return Response.ok(Status.CREATED).build();
}

CarDAOImpl deals with the database, if needed, will update that too.

Thanks in advance.

Body:
These two lines are ordered incorrectly:

carService.updateCar(carId);
Mockito.when(carDAO.isLicenseExpired(Mockito.any(Car.class))).thenReturn(true);

The first line in that pair invokes the class-under-test and the second line sets up an expectation of how your carDAO should behave inside the class-under-test. So, you are setting the expectation after you invoke the class-under-test.

The following test will pass:

@Test
public void testUpdateCar() {
    int carId = 1;

    // establish expectations of how carDAO should behave inside updateCar()
    Mockito.when(carDAO.getCarById(Mockito.any(Integer.class))).thenReturn(new Car());
    Mockito.when(carDAO.isLicenseExpired(Mockito.any(Car.class))).thenReturn(true);

    // invoke the class-under-test
    carService.updateCar(carId);

    // verify that CarService used CarDAO correctly
    Mockito.verify(carDAO).updateCar(Mockito.any(Car.class));
    Mockito.verify(carDAO).isLicenseExpired(Mockito.any(Car.class));
    Mockito.verify(carDAO).issueLicense(Mockito.any(Car.class));
}


问:
Send Outlook email with attachment using Excel VBA
I am trying to send email with attachment using Excel VBA.

My code is sending email if I am not including the attachment code line.

When I write that line to send an attachment it is showing error.

```<code>Set MyApp = CreateObject("Outlook.Application")
Set MyItem = MyApp.CreateItem(0)
With MyItem
    .To = "saurabh.ad.sharma@accenture.com"
    .Subject = "Subject"
    .ReadReceiptRequested = False
    .HTMLBody = "resport"
    .Attachment = "C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx"
End With
MyItem.Send
</code>```

答:
A simple example to send mail with attachment
try this out </p>

```<code>Dim objOutl
Set objOutl = CreateObject("Outlook.Application")
Set objMailItem = objOutl.CreateItem(olMailItem)
'comment the next line if you do not want to see the outlook window
objMailItem.Display
strEmailAddr  = "me.me@you.com"
objMailItem.Recipients.Add strEmailAddr
objMailItem.Body = "Hi"
objMailItem.Attachments.Add "file.xml"
objMailItem.Send
Set objMailItem = nothing
Set objOutl = nothing
</code>```

Body:
I am trying to send email with attachment using Excel VBA.

My code is sending email if I am not including the attachment code line.

When I write that line to send an attachment it is showing error.

Set MyApp = CreateObject("Outlook.Application")
Set MyItem = MyApp.CreateItem(0)
With MyItem
    .To = "saurabh.ad.sharma@accenture.com"
    .Subject = "Subject"
    .ReadReceiptRequested = False
    .HTMLBody = "resport"
    .Attachment = "C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx"
End With
MyItem.Send

Body:
A simple example to send mail with attachment
try this out

Dim objOutl
Set objOutl = CreateObject("Outlook.Application")
Set objMailItem = objOutl.CreateItem(olMailItem)
'comment the next line if you do not want to see the outlook window
objMailItem.Display
strEmailAddr  = "me.me@you.com"
objMailItem.Recipients.Add strEmailAddr
objMailItem.Body = "Hi"
objMailItem.Attachments.Add "file.xml"
objMailItem.Send
Set objMailItem = nothing
Set objOutl = nothing


问:
How to use Hub API using Curl in php
I have purchase Hub API from RouteHappy website for search flights using Source and Destination.

They give me below code for using their API

```<code>curl \
  -H "Auth: YOUR_API_KEY" \
  -H "Accept: application/vnd.api.v3+json" \
  -G \
  -d ids=DSM-ORD-AA-3558-20160907-FIRST \
  -d include=seat,wifi \
  YOUR_HOST/segments
</code>```

But I am not able to use Flight API using Curl in PHP, Laravel.Please help me out to access API and get desire result.

答:
the equivalent using hhb_curl  would be

```<code>echo (new hhb_curl ( '', true ))->setopt_array ( array (
        CURLOPT_URL => 'YOUR_HOST/segments',
        CURLOPT_HTTPHEADER => array (
                "Auth: YOUR_API_KEY",
                "Accept: application/vnd.api.v3+json"
        ),
        CURLOPT_POSTFIELDS => http_build_query ( array (
                'ids' => 'DSM-ORD-AA-3558-20160907-FIRST',
                'include' => 'seat,wifi'
        ) )
) )->exec ()->getStdOut ();
</code>```

and the equivalent using the native curl_ api would be very much like that, but with a lot more manual labour (checking return types of setopt and exec, and creating a temporary output file for curl, cleaning up the resources/memory of the temp file and curl when you're finished, etc, all of which hhb_curl does for you automatically. and curl errors are converted to RuntimeExceptions)

Title: How to use Hub API using Curl in php

Body:
I have purchase Hub API from RouteHappy website for search flights using Source and Destination.

They give me below code for using their API

curl \
  -H "Auth: YOUR_API_KEY" \
  -H "Accept: application/vnd.api.v3+json" \
  -G \
  -d ids=DSM-ORD-AA-3558-20160907-FIRST \
  -d include=seat,wifi \
  YOUR_HOST/segments

But I am not able to use Flight API using Curl in PHP, Laravel.Please help me out to access API and get desire result.

Body:
the equivalent using hhb_curl  would be

echo (new hhb_curl ( '', true ))->setopt_array ( array (
        CURLOPT_URL => 'YOUR_HOST/segments',
        CURLOPT_HTTPHEADER => array (
                "Auth: YOUR_API_KEY",
                "Accept: application/vnd.api.v3+json"
        ),
        CURLOPT_POSTFIELDS => http_build_query ( array (
                'ids' => 'DSM-ORD-AA-3558-20160907-FIRST',
                'include' => 'seat,wifi'
        ) )
) )->exec ()->getStdOut ();

and the equivalent using the native curl_ api would be very much like that, but with a lot more manual labour (checking return types of setopt and exec, and creating a temporary output file for curl, cleaning up the resources/memory of the temp file and curl when you're finished, etc, all of which hhb_curl does for you automatically. and curl errors are converted to RuntimeExceptions)


问:
HA is not enabled for this namenode when using "hdfs zkfc -formatZK"
I am establishing a single node hadoop cluster using zookeeper
my zookeeper cluster has three nodes which on the same machine with different ports.they are working fine.
my hadoop cluster has only one node.my hadoop and zookeepers are on the same machine.when using "hdfs zkfc -formatZK" they tells me:Exception in thread "main" org.apache.Hadoop.HadoopIllegalArgumentException: HA is not enabled for this namenode

my core-site.xml:

<configuration>
 <property>
      <name>fs.defaultFS</name>
      <value>hdfs://yavin</value>
 </property>
 <property>
      <name>hadoop.tmp.dir</name>
      <value>/usr/local/hadoop/hdfs/temp</value>
 </property>
 <property>
      <name>io.file.buffer.size</name>
      <value>4096</value>
 </property>
 <property>
      <name>ha.zookeeper.quorum</name>
      <value>coruscant:2181,coruscant:2182,coruscant:2183</value>
 </property>
 </configuration>
```

<p>coruscant is mapping my ip address in hosts file. all my zookeepers are on coruscant using port 2181 2182 2183</p>

<p>my hdfs-site.xml:</p>

<pre class="lang-xml prettyprint-override"><code><configuration>
    <property>
        <name>dfs.nameservices</name>
        <value>yavin</value>
    </property>
    <property>
       <name>dfs.ha.namenodes.yavin</name>
       <value>nn1</value>
    </property>
    <property>
       <name>dfs.namenode.rpc-address.yavin.nn1</name>
       <value>coruscant:9000</value>
    </property>
    <property>
        <name>dfs.namenode.http-address.yavin.nn1</name>
        <value>coruscant:50070</value>
    </property>
    <property>
        <name>dfs.namenode.servicerpc-address.yavin.nn1</name>
        <value>coruscant:53310</value>
    </property>
    <property>
         <name>dfs.namenode.shared.edits.dir</name>
         <value>qjournal://coruscant:8485;coruscant:8486;coruscant:8487/yavin</value>
    </property>
    <property>
          <name>dfs.journalnode.edits.dir</name>
          <value>/usr/local/hadoop/journal</value>
    </property>
    <property>
          <name>dfs.ha.automatic-failover.enabled</name>
          <value>true</value>
    </property>
    <property>
            <name>dfs.client.failover.proxy.provider.yavin</name>
            <value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
    </property>
    <property>
             <name>dfs.ha.fencing.methods</name>
             <value>sshfence</value>
    </property>
    <property>
            <name>dfs.ha.fencing.ssh.private-key-files</name>
            <value>/root/.ssh/id_rsa</value>
    </property>
    <property>
        <name>dfs.namenode.name.dir</name>
        <value>file:///usr/local/hadoop/hdfs/name</value>
    </property>
    <property>
        <name>dfs.datanode.data.dir</name>
        <value>file:///usr/local/hadoop/hdfs/data</value>
    </property>
    <property>
       <name>dfs.replication</name>
       <value>2</value>
    </property>                                                                     <property>
       <name>dfs.webhdfs.enabled</name>
       <value>true</value>
    </property>
<property>
        <name>dfs.permissions.enable</name>
        <value>false</value>
    </property>
    <property>
        <name>dfs.permissions</name>
        <value>false</value>
    </property>
</configuration>
</code>```

my mapred-site.xml:

<configuration>
 <property>
        <name>mapreduce.framework.name</name>
        <value>yarn</value>
 </property>
</configuration>
```

<p>my yarn-site.xml:</p>

<pre class="lang-xml prettyprint-override"><code><configuration>
    <property>
           <name>yarn.resourcemanager.ha.enabled</name>
           <value>true</value>
    </property>
    <property>
            <name>yarn.nodemanager.aux-services</name>
            <value>mapreduce_shuffle</value>
     </property>
     <property>
            <name>yarn.resourcemanager.hostname</name>
            <value>coruscant</value>
      </property>
</configuration>
</code>```

what have I done wrong?

答:
I ran into the same problem. After reading the source code of HAUtil.isHAEnabled() I found the solution:

HDFS high availabilty is only available when you have more than one namenode configured. The error message is still a little misleading, though.

Body:
I am establishing a single node hadoop cluster using zookeeper
my zookeeper cluster has three nodes which on the same machine with different ports.they are working fine.
my hadoop cluster has only one node.my hadoop and zookeepers are on the same machine.when using "hdfs zkfc -formatZK" they tells me:Exception in thread "main" org.apache.Hadoop.HadoopIllegalArgumentException: HA is not enabled for this namenode

my core-site.xml:

<configuration>
 <property>
      <name>fs.defaultFS</name>
      <value>hdfs://yavin</value>
 </property>
 <property>
      <name>hadoop.tmp.dir</name>
      <value>/usr/local/hadoop/hdfs/temp</value>
 </property>
 <property>
      <name>io.file.buffer.size</name>
      <value>4096</value>
 </property>
 <property>
      <name>ha.zookeeper.quorum</name>
      <value>coruscant:2181,coruscant:2182,coruscant:2183</value>
 </property>
 </configuration>

coruscant is mapping my ip address in hosts file. all my zookeepers are on coruscant using port 2181 2182 2183

my hdfs-site.xml:

<configuration>
    <property>
        <name>dfs.nameservices</name>
        <value>yavin</value>
    </property>
    <property>
       <name>dfs.ha.namenodes.yavin</name>
       <value>nn1</value>
    </property>
    <property>
       <name>dfs.namenode.rpc-address.yavin.nn1</name>
       <value>coruscant:9000</value>
    </property>
    <property>
        <name>dfs.namenode.http-address.yavin.nn1</name>
        <value>coruscant:50070</value>
    </property>
    <property>
        <name>dfs.namenode.servicerpc-address.yavin.nn1</name>
        <value>coruscant:53310</value>
    </property>
    <property>
         <name>dfs.namenode.shared.edits.dir</name>
         <value>qjournal://coruscant:8485;coruscant:8486;coruscant:8487/yavin</value>
    </property>
    <property>
          <name>dfs.journalnode.edits.dir</name>
          <value>/usr/local/hadoop/journal</value>
    </property>
    <property>
          <name>dfs.ha.automatic-failover.enabled</name>
          <value>true</value>
    </property>
    <property>
            <name>dfs.client.failover.proxy.provider.yavin</name>
            <value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
    </property>
    <property>
             <name>dfs.ha.fencing.methods</name>
             <value>sshfence</value>
    </property>
    <property>
            <name>dfs.ha.fencing.ssh.private-key-files</name>
            <value>/root/.ssh/id_rsa</value>
    </property>
    <property>
        <name>dfs.namenode.name.dir</name>
        <value>file:///usr/local/hadoop/hdfs/name</value>
    </property>
    <property>
        <name>dfs.datanode.data.dir</name>
        <value>file:///usr/local/hadoop/hdfs/data</value>
    </property>
    <property>
       <name>dfs.replication</name>
       <value>2</value>
    </property>                                                                     <property>
       <name>dfs.webhdfs.enabled</name>
       <value>true</value>
    </property>
<property>
        <name>dfs.permissions.enable</name>
        <value>false</value>
    </property>
    <property>
        <name>dfs.permissions</name>
        <value>false</value>
    </property>
</configuration>

my mapred-site.xml:

<configuration>
 <property>
        <name>mapreduce.framework.name</name>
        <value>yarn</value>
 </property>
</configuration>

my yarn-site.xml:

<configuration>
    <property>
           <name>yarn.resourcemanager.ha.enabled</name>
           <value>true</value>
    </property>
    <property>
            <name>yarn.nodemanager.aux-services</name>
            <value>mapreduce_shuffle</value>
     </property>
     <property>
            <name>yarn.resourcemanager.hostname</name>
            <value>coruscant</value>
      </property>
</configuration>

what have I done wrong?


问:
QR factorization from lapack subroutine dgeqrf not working in C
I want to find diagonal elements of R matrix obtained from QR-decomposition of A matrix as A=QR using lapack. I tried lapack dgeqrf subroutine but it is giving back the same matrix A i.e. input and output matrices are same. How to find R matrix and its diagonals ? I can't figure out what is going wrong with this code. I am programming in C.</p>

```<code>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void dgeqrf_(int *rows, int *cols, double *matA, int *LDA, double *TAU, double *WORK, int *LWORK, int *INFO);
int main()
{
    int rows=3;
    int cols=3;
    double *matA=malloc(sizeof(double)*rows*cols);

    matA[0]=10;
    matA[1]=20;
    matA[2]=10;
    matA[3]=40;
    matA[4]=20;
    matA[5]=50;
    matA[6]=70;
    matA[7]=30;
    matA[8]=20;

    for(int i=0; i<rows*cols; i++)
    {
        printf("%f ",matA[i]);
    }
    printf("\n");
    int LDA=rows;
    int INFO;
    double *WORK=malloc(sizeof(double)*2);
    int LWORK=-1;
    int rowcolmin=rows;
    if(rowcolmin>cols)
    {
        rowcolmin=cols;
    }
    double *TAU=malloc(sizeof(double)*rowcolmin);
    dgeqrf_(&rows, &cols, matA, &LDA, TAU, WORK, &LWORK, &INFO);
    for(int i=0; i<rows*cols; i++)
    {
        printf("%f ",matA[i]);
    }
    printf("\n");
    free(WORK);
    free(TAU);
    free(matA);
    return 0;
}
</code>```

答:
The matrix matA is not modified because LAPACK's dgeqrf() is called using a value of -1 for the argument LWORK. This correspond to a workspace query:

If LWORK = -1, then a workspace query is assumed; the routine
            only calculates the optimal size of the WORK array, returns
            this value as the first entry of the WORK array, and no error
            message related to LWORK is issued by XERBLA.

Indeed, the usual way to use dgeqrf() and many other routines from LAPACK is to call them twice: once for the workspace query and once for the actual computation of the result. For instance, the C interface to LAPACK wraps dgeqrf() in lapacke__dgeqrf(), which calls lapacke__dgeqrf_work() twice for this very reason.

Here is how your code could be modified:

```<code>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void dgeqrf_(int *rows, int *cols, double *matA, int *LDA, double *TAU, double *WORK, int *LWORK, int *INFO);
int main()
{
    int i;
    int rows=3;
    int cols=3;
    double *matA=malloc(sizeof(double)*rows*cols);

    matA[0]=1;
    matA[1]=2;
    matA[2]=4;
    matA[3]=1;
    matA[4]=3;
    matA[5]=9;
    matA[6]=1;
    matA[7]=4;
    matA[8]=16;

    for(i=0; i<rows*cols; i++)
    {
        printf("%f ",matA[i]);
    }
    printf("\n");
    int LDA=rows;
    int INFO;

    int rowcolmin=rows;
    if(rowcolmin>cols)
    {
        rowcolmin=cols;
    }

    double *TAU=malloc(sizeof(double)*rowcolmin);
    int LWORK=-1;
    // since the value of LWORK is -1, this is a workspace query.
    // it only return the optimum size of work in work[0].
    double lwork2;
    dgeqrf_(&rows, &cols, matA, &LDA, TAU, &lwork2, &LWORK, &INFO);
    // allocate work using the optimal size
    int lwork3=(int)lwork2;
    double *WORK=malloc(sizeof(double)*lwork3);
    // perform the QR factorization
    dgeqrf_(&rows, &cols, matA, &LDA, TAU, WORK, &lwork3, &INFO);
    if(INFO !=0){fprintf(stderr,"QR factorization failed, error code %d\n",INFO);exit(1);}

    for(i=0; i<rows*cols; i++)
    {
        printf("%f ",matA[i]);
    }
    printf("\n");

    // for instance, the determinant is...
    if(cols==rows){
        // det of R
        double det=1;
        for (i=0;i<cols;i++){
            det*=matA[i*cols+i];
        }
        // det of Q, Householder algorithm
        if(cols%2==0){
            det*=-1;
        }
        printf("det is %g\n",det);
    }
    free(WORK);
    free(TAU);
    free(matA);
    return 0;
}
</code>```

It is compiled by gcc main.c -o main -llapack -lblas -lm.

Given the question you asked, entitled compute determinant from LU decomposition in lapack , the computation of the determinant is added at the end of the code. The matrix matA is now a Vandermonde matrix, so as to easily check the correctness of the result.

Body:
I want to find diagonal elements of R matrix obtained from QR-decomposition of A matrix as A=QR using lapack. I tried lapack dgeqrf subroutine but it is giving back the same matrix A i.e. input and output matrices are same. How to find R matrix and its diagonals ? I can't figure out what is going wrong with this code. I am programming in C.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void dgeqrf_(int *rows, int *cols, double *matA, int *LDA, double *TAU, double *WORK, int *LWORK, int *INFO);
int main()
{
    int rows=3;
    int cols=3;
    double *matA=malloc(sizeof(double)*rows*cols);

    matA[0]=10;
    matA[1]=20;
    matA[2]=10;
    matA[3]=40;
    matA[4]=20;
    matA[5]=50;
    matA[6]=70;
    matA[7]=30;
    matA[8]=20;

    for(int i=0; i<rows*cols; i++)
    {
        printf("%f ",matA[i]);
    }
    printf("\n");
    int LDA=rows;
    int INFO;
    double *WORK=malloc(sizeof(double)*2);
    int LWORK=-1;
    int rowcolmin=rows;
    if(rowcolmin>cols)
    {
        rowcolmin=cols;
    }
    double *TAU=malloc(sizeof(double)*rowcolmin);
    dgeqrf_(&rows, &cols, matA, &LDA, TAU, WORK, &LWORK, &INFO);
    for(int i=0; i<rows*cols; i++)
    {
        printf("%f ",matA[i]);
    }
    printf("\n");
    free(WORK);
    free(TAU);
    free(matA);
    return 0;
}

Body:
The matrix matA is not modified because LAPACK's dgeqrf() is called using a value of -1 for the argument LWORK. This correspond to a workspace query:

If LWORK = -1, then a workspace query is assumed; the routine
            only calculates the optimal size of the WORK array, returns
            this value as the first entry of the WORK array, and no error
            message related to LWORK is issued by XERBLA.

Indeed, the usual way to use dgeqrf() and many other routines from LAPACK is to call them twice: once for the workspace query and once for the actual computation of the result. For instance, the C interface to LAPACK wraps dgeqrf() in lapacke__dgeqrf(), which calls lapacke__dgeqrf_work() twice for this very reason.

Here is how your code could be modified:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void dgeqrf_(int *rows, int *cols, double *matA, int *LDA, double *TAU, double *WORK, int *LWORK, int *INFO);
int main()
{
    int i;
    int rows=3;
    int cols=3;
    double *matA=malloc(sizeof(double)*rows*cols);

    matA[0]=1;
    matA[1]=2;
    matA[2]=4;
    matA[3]=1;
    matA[4]=3;
    matA[5]=9;
    matA[6]=1;
    matA[7]=4;
    matA[8]=16;

    for(i=0; i<rows*cols; i++)
    {
        printf("%f ",matA[i]);
    }
    printf("\n");
    int LDA=rows;
    int INFO;

    int rowcolmin=rows;
    if(rowcolmin>cols)
    {
        rowcolmin=cols;
    }

    double *TAU=malloc(sizeof(double)*rowcolmin);
    int LWORK=-1;
    // since the value of LWORK is -1, this is a workspace query.
    // it only return the optimum size of work in work[0].
    double lwork2;
    dgeqrf_(&rows, &cols, matA, &LDA, TAU, &lwork2, &LWORK, &INFO);
    // allocate work using the optimal size
    int lwork3=(int)lwork2;
    double *WORK=malloc(sizeof(double)*lwork3);
    // perform the QR factorization
    dgeqrf_(&rows, &cols, matA, &LDA, TAU, WORK, &lwork3, &INFO);
    if(INFO !=0){fprintf(stderr,"QR factorization failed, error code %d\n",INFO);exit(1);}

    for(i=0; i<rows*cols; i++)
    {
        printf("%f ",matA[i]);
    }
    printf("\n");

    // for instance, the determinant is...
    if(cols==rows){
        // det of R
        double det=1;
        for (i=0;i<cols;i++){
            det*=matA[i*cols+i];
        }
        // det of Q, Householder algorithm
        if(cols%2==0){
            det*=-1;
        }
        printf("det is %g\n",det);
    }
    free(WORK);
    free(TAU);
    free(matA);
    return 0;
}

It is compiled by gcc main.c -o main -llapack -lblas -lm.

Given the question you asked, entitled compute determinant from LU decomposition in lapack , the computation of the determinant is added at the end of the code. The matrix matA is now a Vandermonde matrix, so as to easily check the correctness of the result.


问:
Examples of using cereal serialization and boost::asio?
I'm trying to serialize objects/messages and send them as UDP packets between nodes. I'm currently looking at cereal for serialization and boost::asio for actual network programming. Are there any examples of using these two libraries together, even if it's pseudocode?</p>

答:
You can treat any example of Boost Serialization with Asio as the pseudo code example. Despite some differences, Cereal is similar enough to Boost Serialization for the samples to be relevant.

Straight forward: sending/receiving a struct in boost::asio

Backgrounds: Low bandwidth performance using boost::asio::ip::tcp::iostream

More choices, raw POD data: c++ Sending struct over network


问:
Convert the date time stamp to local epoch datatime
Assume this is my date time stamp list:

```<code>[datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]
</code>```

A lot of examples have been given for converting these values to epoch, but the values are in GMT.
How do we convert it to Epoch Local time?

To put it in simpler words. The general epoch conversion coverts the given date into epoch considering that the datetime given is in GMT. But the given date time is localtime!

Body:
Assume this is my date time stamp list:

[datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]

A lot of examples have been given for converting these values to epoch, but the values are in GMT.
How do we convert it to Epoch Local time?

To put it in simpler words. The general epoch conversion coverts the given date into epoch considering that the datetime given is in GMT. But the given date time is localtime!

Body:
You can use this:

l = [datetime.datetime(2017, 11, 17, 9, 33, 11), datetime.datetime(2017, 11, 17, 9, 33, 36), datetime.datetime(2017, 11, 17, 9, 33, 48)]

epo = [x.strftime('%s') for x in l]

print(epo)
# ['1510898591', '1510898616', '1510898628']


问:
RecyclerView is not showing all items in the list
I am using RecyclerView in my app. Every time I open my screen I can see only one item but when I debug it is coming every time to onBindViewHolder method.

Here is my adapter:

```<code>@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.tourist_details_info, parent, false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    try {
            holder.displayName.setText(list.get(position).toUpperCase());
    }catch (Exception e){
       AxeltaLogger.err("error>>>"+e);
    }
}
@Override
public int getItemCount() {
    return list.size();
}
</code>```

and this my RecyclerView:

```<code> RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
touristAdapter=new TouristInfoAdapter(list);
recyclerView.setAdapter(touristAdapter);
</code>```

答: in your layout tourist_details_info.xml make the parent height from match_parent to specific height (100dp or something) or use wrap_content as android:layout_height="match_parent"

Body:
I am using RecyclerView in my app. Every time I open my screen I can see only one item but when I debug it is coming every time to onBindViewHolder method.

Here is my adapter:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.tourist_details_info, parent, false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    try {
            holder.displayName.setText(list.get(position).toUpperCase());
    }catch (Exception e){
       AxeltaLogger.err("error>>>"+e);
    }
}
@Override
public int getItemCount() {
    return list.size();
}

and this my RecyclerView:

 RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
touristAdapter=new TouristInfoAdapter(list);
recyclerView.setAdapter(touristAdapter);


问:
How do I filter NSArray with NSPredicate
In my array there are different kind of values some might be a string or object or Key-Value type.

In this example array contains NSString, NSObject and NSDictionary type of values.

```<code>example : ContactName[0] "ABC"
          ContactName[1] = XYZ
          ContactName[2] = (
                             {
                                language = @"en"
                                value = "PQR"
                             },
                             {
                                language = @"de"
                                value = "QWERTY"
                             }
                          )
</code>```

So finally can anyone help me to filter such type of array's, using NSPredicate

I want to filter it as user type first keyword in UISearchBar.

Please help me I'm new to it.

答:
```<code>#pragma mark - Search delegate methods

- (void)filterContentForSearchText:(NSString*)searchText

{

    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",searchText];

    searchResult = [_kDropDownOption filteredArrayUsingPredicate:resultPredicate];

    [_kTableView reloadData];

}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{

    if (searchBar.text.length == 0) {
        searchEnabled = NO;
        [_kTableView reloadData];
    }
    else {
        searchEnabled = YES;
        [self filterContentForSearchText:searchBar.text];

        NSLog(@"%@",self->searchResult);
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];

    searchEnabled = YES;

    [self filterContentForSearchText:searchBar.text];

}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [searchBar setText:@""];
    searchEnabled = NO;
    [_kTableView reloadData];

}
</code>```

Body:
In my array there are different kind of values some might be a string or object or Key-Value type.

In this example array contains NSString, NSObject and NSDictionary type of values.

example : ContactName[0] "ABC"
          ContactName[1] = XYZ
          ContactName[2] = (
                             {
                                language = @"en"
                                value = "PQR"
                             },
                             {
                                language = @"de"
                                value = "QWERTY"
                             }
                          )

So finally can anyone help me to filter such type of array's, using NSPredicate

I want to filter it as user type first keyword in UISearchBar.

Please help me I'm new to it.


问:
SHA certificate firebase Debug/Release
My android app is using firebase realtime Database,
i've putted the app debug SHA certificate fingerprints , and when I test my app with debug mode it works and I get data from DB , now when I want to sign and release the app , " what i've done with my previous app : I delete the debug SHA certificate fingerprint from firebase project console and then I put the release SHA certificate fingerprint and the app is on the market now and it's OK"
but I want to know :

Q1)when I deleted the debug SHA certificate fingerprint with the release one , it will still work when I run my app in debug mode ?

Q2) should i put debug and release SHA certificate fingerprint in the firebase console ?

Q3) If i put debug and release SHA certificate fingerprint in the firebase console then download the new configuration file provided from firebase , my database connexion will still work either on release and debug mode ?

答:
You have to create two separate projects for Debug  and Release  in firebase console.

Put the respective SHA key in those project.

You have two different  google-services.json file.

Now you have to create two bulidType  in the app build.gradle file.
Ex.

```<code>buildType{
    release{
   //define your keys here
    }

    debug{
   //define your keys here

    }

}
</code>```

In projects src create two folders called debug and release

```<code>project-->src-->create folder debug and release
</code>```

put your google-services.json file in the respective folder

Gradle will automatically pick your account based on build type.

Title: SHA certificate firebase Debug/Release

Body:
You have to create two separate projects for Debug  and Release  in firebase console.

Put the respective SHA key in those project.

You have two different  google-services.json file.

Now you have to create two bulidType  in the app build.gradle file.
Ex.

buildType{
    release{
   //define your keys here
    }

    debug{
   //define your keys here

    }

}

In projects src create two folders called debug and release

project-->src-->create folder debug and release

put your google-services.json file in the respective folder

Gradle will automatically pick your account based on build type.


问:
Calling a Function defined inside another function in Javascript
I am calling a function on button click like this:

```<code><input type="button" onclick="outer();" value="ACTION">

function outer() {
    alert("hi");
}
</code>```

It works fine and I get an alert:

Now when I do like this:

```<code>function outer() {
    function inner() {
        alert("hi");
    }
}
</code>```

Why don't I get an alert?

Though inner function has a scope available in outer function.

答:
You can also try this.Here you are returning the function "inside" and invoking with the second set of parenthesis.

```<code>function outer() {
  return (function inside(){
    console.log("Inside inside function");
  });
}
outer()();
</code>```

Or

```<code>function outer2() {
    let inside = function inside(){
      console.log("Inside inside");
    };
    return inside;
  }
outer2()();
</code>```

Body:
I am calling a function on button click like this:

<input type="button" onclick="outer();" value="ACTION">

function outer() {
    alert("hi");
}

It works fine and I get an alert:

Now when I do like this:

function outer() {
    function inner() {
        alert("hi");
    }
}

Why don't I get an alert?

Though inner function has a scope available in outer function.

Body:
You can also try this.Here you are returning the function "inside" and invoking with the second set of parenthesis.

function outer() {
  return (function inside(){
    console.log("Inside inside function");
  });
}
outer()();

Or

function outer2() {
    let inside = function inside(){
      console.log("Inside inside");
    };
    return inside;
  }
outer2()();


问:
How to show default google maps Places icon in android
Hy I have been working on the google maps api in android and I used Google maps places API to show some places on the maps with markers. And these all thing working fine for me.

But if we look the native google maps app, it shows the places itself with the default google icons.

so here is the picture display for an idea

but in my app I am having plain google map. Can I have view as we have in our default google maps application ?? please help

答: It shows in simple map but it is depends on camera focus and this type of things availability near by your camera focus. check it another position and move it smoothly it will show.  </p>


问:
hive update lastAccessTime
I wanted to update  lastAccessTime on hive table ,After google in the web,I get a solution :

```<code>set hive.exec.pre.hooks = org.apache.hadoop.hive.ql.hooks.UpdateInputAccessTimeHook$PreExec;
</code>```

But If I have two database A & B  the hive sql:

```<code> set hive.exec.pre.hooks =
    org.apache.hadoop.hive.ql.hooks.UpdateInputAccessTimeHook$PreExec;
    use A;
    insert overwrite A.xxx
    select  c1,c2 from B.xxx;
</code>```

hive returned me

org.apache.hadoop.hive.ql.metadata.InvalidTableException(Table not
  found B.xxx

答:
To retrieve a table's 'LastAccessTime', run the following commands through the Hive shell, replacing [database_name] and [table_name] with the relevant values.

```<code>    use [database_name];
    show table extended like '[table_name]';
</code>```

This will return several metrics including the number of milliseconds (rather than the number of seconds) elapsed since Epoch. To format that number as a string representing the timestamp of that moment in the current system's time zone, remove the last three digits from the number and run it through the following command:

```<code>    select from_unixtime([last_access_time]);
</code>```

Title: hive update lastAccessTime

Body:
I wanted to update  lastAccessTime on hive table ,After google in the web,I get a solution :

set hive.exec.pre.hooks = org.apache.hadoop.hive.ql.hooks.UpdateInputAccessTimeHook$PreExec;

But If I have two database A & B  the hive sql:

 set hive.exec.pre.hooks =
    org.apache.hadoop.hive.ql.hooks.UpdateInputAccessTimeHook$PreExec;
    use A;
    insert overwrite A.xxx
    select  c1,c2 from B.xxx;

hive returned me

org.apache.hadoop.hive.ql.metadata.InvalidTableException(Table not
  found B.xxx

Body:
To retrieve a table's 'LastAccessTime', run the following commands through the Hive shell, replacing [database_name] and [table_name] with the relevant values.

    use [database_name];
    show table extended like '[table_name]';

This will return several metrics including the number of milliseconds (rather than the number of seconds) elapsed since Epoch. To format that number as a string representing the timestamp of that moment in the current system's time zone, remove the last three digits from the number and run it through the following command:

    select from_unixtime([last_access_time]);


问:
Javascript expando objects
What are expando objects in javascripts?

For what purpose we need this ? Any complete example will be appreciated

I found 1 article here Javascript: The red-headed stepchild of web development

答:
Everything except primitive types(string, number,boolean) are objects and support Key:values structure. properties(keys) can be accessed and set using the dot notation as well as the square brackets.</p>

```<code>var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // doesn't work, myProp2 is an undefined name.
myObj['myProp2'] = 'value2'; // works  , an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string
</code>```

Title: Javascript expando objects

Body:
Everything except primitive types(string, number,boolean) are objects and support Key:values structure. properties(keys) can be accessed and set using the dot notation as well as the square brackets.

var myObj = {};
myObj.myProp1 = 'value1'; //works, an expando property
myObj[myProp2] = 'value2'; // doesn't work, myProp2 is an undefined name.
myObj['myProp2'] = 'value2'; // works  , an expando property
myObj[2010]= 'value'; //note the key is number, still works, an expando property??
myObj.2010 = 'value'; // FAILS. to use dot notation, key must be a string


问:
Sum of even fibonacci numbers below 4 million - Python
I'm attempting the second Project Euler question in python and want to understand why my code doesn't work.

This code finds the sum of even Fibonacci numbers below 4 million

```<code>counter = 2
total = 0
while counter <= 4000000:
    if counter % 2 == 0:
        total+= counter
    counter+= (counter -1)
print total
</code>```

This code will output: 2

If I print the counter it outputs: 4194305

I'm assuming it's an issue with the if statement being executed as the while loop is functioning correctly and the counter is also incrementing correctly.

答:
Well I have tried this way:

```<code>fib_num = [0 ,1]
for i in range(2, 4*10**6):
    fib_num.append(fib_num[i-1] + fib_num[i-2])

def even_fib(fib_num):
    result = 0
    result = result + sum([even for even in range(0, fib_num) if even % 2 == 0])
print result
</code>```

Whats wrong with that? It is taking too long to respond for script and giving 'killed' error

Body:
I'm attempting the second Project Euler question in python and want to understand why my code doesn't work.

This code finds the sum of even Fibonacci numbers below 4 million

counter = 2
total = 0
while counter <= 4000000:
    if counter % 2 == 0:
        total+= counter
    counter+= (counter -1)
print total

This code will output: 2

If I print the counter it outputs: 4194305

I'm assuming it's an issue with the if statement being executed as the while loop is functioning correctly and the counter is also incrementing correctly.

Body:
Well I have tried this way:

fib_num = [0 ,1]
for i in range(2, 4*10**6):
    fib_num.append(fib_num[i-1] + fib_num[i-2])

def even_fib(fib_num):
    result = 0
    result = result + sum([even for even in range(0, fib_num) if even % 2 == 0])
print result

Whats wrong with that? It is taking too long to respond for script and giving 'killed' error


问:
Matlab bar: set colors with colormap(jet) as a function of bar heights
I have 4 different groups of multiple bars. I would like, for each group, to plot each bar with a color which is function of its height value (i.e the value of the concerned bar) with colormap(jet).

For the moment, I have done:

```<code>h=bar(xpoints(1:4),bpcombined(1:4,:),'grouped','BarWidth',0.5);
colorbar;
colormap(jet);
</code>```

and I get the following figure:

As you can see, for each bar, its color is not a function of the height : it is just a sequence of different colors (of jet colormap), the same for the 4 groups.

How can I get this dependency, I mean the highest bars would be red and the lowest blue following colormap (jet)?

Update 1

I tried the solution suggested by @masei but I get the following error on Matlab 2016b :

```<code>No appropriate method, property, or field 'CData' for class 'matlab.graphics.chart.primitive.Bar'.

Error in test_plot_bar_color (line 17)
    b.CData(k,:) = y_color(k,:);
</code>```

I don't how to circumvent this error.

@masei told me to use ‘FaceColor’ property but I don't know how to put it on this script.

Update 2

I tried to apply the suggestion of @marsei, i.e plot multiple times the sections of group of bar (and the other groups are set to Nan), like this:

```<code>  1 clear;
  2 % Data
  3 y = rand(10,4);
  4 % 2D array of nan
  5 y_nan = nan(size(y))
  6 % 1D array by default
  7 y_1d(1:numel(y)) = nan(numel(y),1);
  8
  9 %Plot
 10 figure('Color', 'w');
 11 title('Bar with height-dependant color');
 12 for k = 1:size(y,2)
 13     % Set default 1D array
 14     y_temp = y_1d;
 15     % Put k-th part of data
 16     y_temp((k-1)*size(y_nan,1)+1:k*size(y_nan,1)) = y(1:size(y_nan,1),k);
 17     % Reshape 1D into 2D for bar
 18     y_final = reshape(y_temp,size(y,2),size(y,1));
 19     % Plot bar
 20     bar_h = bar(y_final,'BarWidth',0.5);
 21     y_color = vals2colormap(y_final(k,:),'jet');
 22     %b.FaceColor = y_color(:,:);
 23     %y_color
 24     bar_child=get(bar_h,'Children');
 25     bar_child.FaceColor = y_color(:,:);
 26     %colormap(y_color);
 27     %set(bar_child,'CData',y_final);
 28     hold on;
 29 end
 30
</code>```

But I get the following error :

```<code>Field assignment to a non-structure array object.

Error in test_plot_bar_color (line 25)
    bar_child.FaceColor = y_color(:,:);
</code>```

What's wrong in my approach?

答:
EDIT - An example that uses sorted data (y = sort(rand(30,10),2) and separation_gap = 5)

You can use a regular bar property called CData to assign each bar a color. The colour is computed with the help of vals2colormap (web).

The initial data matrix has 10 rows, that gives 10 groups of bars in regular bar plot. At this point, changing the CData property for the first bar changes the color of all the first bar (for all groups). You can't dissociate the first bars.

The trick is then to flatten the matrix while inserting NaNs for group separation. Here, the initial data is 10x4 flatten in a 40 element vector, separated with a single Nan. With this, you have a full control over each individual bar (bars are not grouped anymore).

The following graph

is produced by

```<code>% data
y = rand(10,4);

% add NaNs (for separation) and flatten
separation_gap = 1; % 2 columns of NaN
y_nan = [y nan(size(y,1), separation_gap)]';
y_flat = [nan(separation_gap,1); y_nan(:)];

%convert values to colomap
y_color = vals2colormap(y_flat, 'jet');

%plot and cange color
figure('Color', 'w');
b = bar(y_flat);%,'grouped'
b.FaceColor = 'flat';
for k = 1:size(y_flat,1)
    b.CData(k,:) = y_color(k,:);
end

title('Bar with height-dependant color');
</code>```

Body:
I have 4 different groups of multiple bars. I would like, for each group, to plot each bar with a color which is function of its height value (i.e the value of the concerned bar) with colormap(jet).

For the moment, I have done:

h=bar(xpoints(1:4),bpcombined(1:4,:),'grouped','BarWidth',0.5);
colorbar;
colormap(jet);

and I get the following figure:

As you can see, for each bar, its color is not a function of the height : it is just a sequence of different colors (of jet colormap), the same for the 4 groups.

How can I get this dependency, I mean the highest bars would be red and the lowest blue following colormap (jet)?

Update 1

I tried the solution suggested by @masei but I get the following error on Matlab 2016b :

No appropriate method, property, or field 'CData' for class 'matlab.graphics.chart.primitive.Bar'.

Error in test_plot_bar_color (line 17)
    b.CData(k,:) = y_color(k,:);

I don't how to circumvent this error.

@masei told me to use ‘FaceColor’ property but I don't know how to put it on this script.

Update 2

I tried to apply the suggestion of @marsei, i.e plot multiple times the sections of group of bar (and the other groups are set to Nan), like this:

  1 clear;
  2 % Data
  3 y = rand(10,4);
  4 % 2D array of nan
  5 y_nan = nan(size(y))
  6 % 1D array by default
  7 y_1d(1:numel(y)) = nan(numel(y),1);
  8
  9 %Plot
 10 figure('Color', 'w');
 11 title('Bar with height-dependant color');
 12 for k = 1:size(y,2)
 13     % Set default 1D array
 14     y_temp = y_1d;
 15     % Put k-th part of data
 16     y_temp((k-1)*size(y_nan,1)+1:k*size(y_nan,1)) = y(1:size(y_nan,1),k);
 17     % Reshape 1D into 2D for bar
 18     y_final = reshape(y_temp,size(y,2),size(y,1));
 19     % Plot bar
 20     bar_h = bar(y_final,'BarWidth',0.5);
 21     y_color = vals2colormap(y_final(k,:),'jet');
 22     %b.FaceColor = y_color(:,:);
 23     %y_color
 24     bar_child=get(bar_h,'Children');
 25     bar_child.FaceColor = y_color(:,:);
 26     %colormap(y_color);
 27     %set(bar_child,'CData',y_final);
 28     hold on;
 29 end
 30

But I get the following error :

Field assignment to a non-structure array object.

Error in test_plot_bar_color (line 25)
    bar_child.FaceColor = y_color(:,:);

What's wrong in my approach?

Body:
EDIT - An example that uses sorted data (y = sort(rand(30,10),2) and separation_gap = 5)

You can use a regular bar property called CData to assign each bar a color. The colour is computed with the help of vals2colormap (web).

The initial data matrix has 10 rows, that gives 10 groups of bars in regular bar plot. At this point, changing the CData property for the first bar changes the color of all the first bar (for all groups). You can't dissociate the first bars.

The trick is then to flatten the matrix while inserting NaNs for group separation. Here, the initial data is 10x4 flatten in a 40 element vector, separated with a single Nan. With this, you have a full control over each individual bar (bars are not grouped anymore).

The following graph

is produced by

% data
y = rand(10,4);

% add NaNs (for separation) and flatten
separation_gap = 1; % 2 columns of NaN
y_nan = [y nan(size(y,1), separation_gap)]';
y_flat = [nan(separation_gap,1); y_nan(:)];

%convert values to colomap
y_color = vals2colormap(y_flat, 'jet');

%plot and cange color
figure('Color', 'w');
b = bar(y_flat);%,'grouped'
b.FaceColor = 'flat';
for k = 1:size(y_flat,1)
    b.CData(k,:) = y_color(k,:);
end

title('Bar with height-dependant color');


问:
Dynamically show/hide Header or Footer of Xamarin.Forms.ListView
Is there a way to dynamically show/hide the header of a ListView based on a condition at runtime.

```<code><ListView x:Name="ListViewChallenges" Header="{Binding .}">

    <ListView.FooterTemplate>
        <DataTemplate>
            <Label Text="No Elements found." IsVisible="{Binding FooterIsVisible}" />
        </DataTemplate>
    </ListView.FooterTemplate>

    <!-- ... -->

</ListView>
</code>```

In the BindingContext I have declared the FooterIsVisible property. When it is false, the footer should be invisible. However this is not working, the Footer is always consuming a certain space for the Label at the bottom of the ListView.

Is this somehow possible?

答:
You should use FooterTemplate and Footer properties. It works as ItemTemplate and ItemSource:

```<code><ListView Footer="{Binding IsFooterVisible}">
    <ListView.FooterTemplate>
        <DataTemplate>
            <!-- Footer content. Always visible -->
        </DataTemplate>
    <ListView.FooterTemplate>
</ListView>
</code>```

And bind to Footer property something nullable (object for example). Or you can use converter to convert: true -> new object() and false -> null

Also it is possible to create a subclass of ListView. My example (IsLoading property is what you searching for):

Xaml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ListView xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="Panor.Views.LoadableListView"
    x:Name="element"
    >
    <ListView.FooterTemplate>
        <DataTemplate>
            <ContentView>
                <ActivityIndicator IsRunning="true"
                    Margin="0, 5"
                    Color="{StaticResource mainColor}"
                    VerticalOptions="CenterAndExpand"
                    HorizontalOptions="CenterAndExpand"
                    >
                    <ActivityIndicator.Scale>
                        <OnPlatform x:TypeArguments="x:Double" iOS="2" Android="1" />
                    </ActivityIndicator.Scale>
                </ActivityIndicator>
            </ContentView>
        </DataTemplate>
    </ListView.FooterTemplate>
</ListView>
</code>```

Code-behind:

```<code>public partial class LoadableListView : ListView
{
    public LoadableListView()
    {
        InitializeComponent();

        this.ItemAppearing += OnItemAppearing;
    }

    public static readonly BindableProperty IsLoadingProperty = BindableProperty.Create(
        nameof(IsLoading),
        typeof(bool),
        typeof(LoadableListView),
        false,
        propertyChanged: (bindable, oldValue, newValue) =>
        {
            var element = (LoadableListView)bindable;

            element.Footer = (bool)newValue ? new object() : null;
        }
    );
    public bool IsLoading
    {
        set => SetValue(IsLoadingProperty, value);
        get => (bool)GetValue(IsLoadingProperty);
    }

    public static readonly BindableProperty ScrolledDownCommandProperty = BindableProperty.Create(
        nameof(ScrolledDownCommand),
        typeof(ICommand),
        typeof(LoadableListView)
    );
    public ICommand ScrolledDownCommand
    {
        set => SetValue(ScrolledDownCommandProperty, value);
        get => (ICommand)GetValue(ScrolledDownCommandProperty);
    }

    void OnItemAppearing(object sender, ItemVisibilityEventArgs e)
    {
        if (ItemsSource == null) return;
        if (ScrolledDownCommand == null) return;

        object last = null;

        if (ItemsSource is IList)
        {
            var length = (ItemsSource as IList).Count;
            last = (ItemsSource as IList)[length - 1];
        }
        else
        {
            foreach (var item in ItemsSource)
                last = item;
        }

        if (e.Item == last && ScrolledDownCommand.CanExecute(null))
            ScrolledDownCommand.Execute(null);

    }
</code>```

Consuming:

```<code> <views:LoadableListView ItemsSource="{Binding ItemSource}"
                RowHeight="120"
                SeparatorColor="#c7c8c9"
                IsLoading="{Binding IsMoreLoading}"
                ScrolledDownCommand="{Binding ScrolledDownCommand}"
                IsPullToRefreshEnabled="true"
                IsRefreshing="{Binding IsRefreshing}"
                RefreshCommand="{Binding RefreshCommand}"
                >
                <views:LoadableListView.ItemTemplate>
                    <DataTemplate>
                        <cells:MagazinesListCell Name="{Binding Name}"
                            Publisher="{Binding Publisher}"
                            Price="{Binding Price}"
                            Image="{Binding Converter={StaticResource UriToImageSourceConvertor}, Path=Image}"
                            Commands="{Binding Commands}"
                            />
                    </DataTemplate>
                </views:LoadableListView.ItemTemplate>
            </views:LoadableListView>
</code>```

Body:
Is there a way to dynamically show/hide the header of a ListView based on a condition at runtime.

<ListView x:Name="ListViewChallenges" Header="{Binding .}">

    <ListView.FooterTemplate>
        <DataTemplate>

        </DataTemplate>
    </ListView.FooterTemplate>

</ListView>

In the BindingContext I have declared the FooterIsVisible property. When it is false, the footer should be invisible. However this is not working, the Footer is always consuming a certain space for the Label at the bottom of the ListView.

Is this somehow possible?

Body:
You should use FooterTemplate and Footer properties. It works as ItemTemplate and ItemSource:

<ListView Footer="{Binding IsFooterVisible}">
    <ListView.FooterTemplate>
        <DataTemplate>
            <!-- Footer content. Always visible -->
        </DataTemplate>
    <ListView.FooterTemplate>
</ListView>

And bind to Footer property something nullable (object for example). Or you can use converter to convert: true -> new object() and false -> null

Also it is possible to create a subclass of ListView. My example (IsLoading property is what you searching for):

Xaml:

<?xml version="1.0" encoding="UTF-8"?>
<ListView xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="Panor.Views.LoadableListView"
    x:Name="element"
    >
    <ListView.FooterTemplate>
        <DataTemplate>
            <ContentView>
                <ActivityIndicator IsRunning="true"
                    Margin="0, 5"
                    Color="{StaticResource mainColor}"
                    VerticalOptions="CenterAndExpand"
                    HorizontalOptions="CenterAndExpand"
                    >
                    <ActivityIndicator.Scale>
                        <OnPlatform x:TypeArguments="x:Double" iOS="2" Android="1" />
                    </ActivityIndicator.Scale>
                </ActivityIndicator>
            </ContentView>
        </DataTemplate>
    </ListView.FooterTemplate>
</ListView>

Code-behind:

public partial class LoadableListView : ListView
{
    public LoadableListView()
    {
        InitializeComponent();

        this.ItemAppearing += OnItemAppearing;
    }

    public static readonly BindableProperty IsLoadingProperty = BindableProperty.Create(
        nameof(IsLoading),
        typeof(bool),
        typeof(LoadableListView),
        false,
        propertyChanged: (bindable, oldValue, newValue) =>
        {
            var element = (LoadableListView)bindable;

            element.Footer = (bool)newValue ? new object() : null;
        }
    );
    public bool IsLoading
    {
        set => SetValue(IsLoadingProperty, value);
        get => (bool)GetValue(IsLoadingProperty);
    }

    public static readonly BindableProperty ScrolledDownCommandProperty = BindableProperty.Create(
        nameof(ScrolledDownCommand),
        typeof(ICommand),
        typeof(LoadableListView)
    );
    public ICommand ScrolledDownCommand
    {
        set => SetValue(ScrolledDownCommandProperty, value);
        get => (ICommand)GetValue(ScrolledDownCommandProperty);
    }

    void OnItemAppearing(object sender, ItemVisibilityEventArgs e)
    {
        if (ItemsSource == null) return;
        if (ScrolledDownCommand == null) return;

        object last = null;

        if (ItemsSource is IList)
        {
            var length = (ItemsSource as IList).Count;
            last = (ItemsSource as IList)[length - 1];
        }
        else
        {
            foreach (var item in ItemsSource)
                last = item;
        }

        if (e.Item == last && ScrolledDownCommand.CanExecute(null))
            ScrolledDownCommand.Execute(null);

    }

Consuming:

 <views:LoadableListView ItemsSource="{Binding ItemSource}"
                RowHeight="120"
                SeparatorColor="#c7c8c9"
                IsLoading="{Binding IsMoreLoading}"
                ScrolledDownCommand="{Binding ScrolledDownCommand}"
                IsPullToRefreshEnabled="true"
                IsRefreshing="{Binding IsRefreshing}"
                RefreshCommand="{Binding RefreshCommand}"
                >
                <views:LoadableListView.ItemTemplate>
                    <DataTemplate>
                        <cells:MagazinesListCell Name="{Binding Name}"
                            Publisher="{Binding Publisher}"
                            Price="{Binding Price}"
                            Image="{Binding Converter={StaticResource UriToImageSourceConvertor}, Path=Image}"
                            Commands="{Binding Commands}"
                            />
                    </DataTemplate>
                </views:LoadableListView.ItemTemplate>
            </views:LoadableListView>


问:
JS - finding differene between 2 arrays of objects with unknown number of properties
I have 2 arrays of objects which contain same properties, but depending on situation they can have 1-50 properties. I need to get difference between those 2

Array 1:

```<code>[
  {
    "prop1": 1,
    "prop2": 2
  },
  {
    "prop1": 4,
    "prop2": 4
  },
  {
    "prop1": 3,
    "prop2": 7
  },
  {
    "prop1": 1,
    "prop2": 3
  }
]
</code>```

Array 2:

```<code>[
  {
    "prop1": 1,
    "prop2": 2
  },
  {
    "prop1": 4,
    "prop2": 4
  }
]
</code>```

I tried with underscore's difference function but it doesn't work well in this scenario. I was thinking of getting object keys, sorting it and hasnhing the objects.That I can compare but I need to get it back into original format. And since these arrays can have up to 5000 object it seems costly.

Is there an effecient solution?

Edit: I have seen the question Difference between two array of objects in JavaScript but that example has static number of properties on which he filters the arrays. That is not the case; I do not know names, nor quantity of properties.

答:
You could take some hash tables and get the keys first and then the values and check the hash of the other array and filter the result.

This proposal returns the symetriccal difference of the two arrays.

function getDifference(a, b) {
    function getKeyValue(object) {
        var keys = Object.keys(object).sort();
        return {
            key: keys.join('|'),
            value: keys.map(function (k) { return object[k]; }).join('|')
        };
    }

    function setHash(hash, kv) {
        hash[kv.key] = hash[kv.key] || {};
        hash[kv.key][kv.value] = true;
    }

    function isHash(hash, kv) {
        return hash[kv.key] && hash[kv.key][kv.value];
    }

    var hashA = Object.create(null),
        hashB = Object.create(null),
        result;

    b.forEach(function (o) {
        var kv = getKeyValue(o);
        setHash(hashB, kv);
    });

    return Array.prototype.concat(
        [],
        array1.filter(function (o) {
            var kv = getKeyValue(o);
            setHash(hashA, kv);
            return !isHash(hashB, kv);
        }),
        array2.filter(function (o) {
            var kv = getKeyValue(o);
            return !isHash(hashA, kv);
        })
    );
}

var array1 = [{ prop1: 1, prop2: 2 }, { prop1: 4, prop2: 4 }, { prop1: 3, prop2: 7 }, { prop1: 1, prop2: 3 }, { prop2: 3 }],
    array2 = [{ prop1: 1, prop2: 2 }, { prop1: 4, prop2: 4 }, { prop1: 4 }];

console.log(getDifference(array1, array2));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have 2 arrays of objects which contain same properties, but depending on situation they can have 1-50 properties. I need to get difference between those 2

Array 1:

[
  {
    "prop1": 1,
    "prop2": 2
  },
  {
    "prop1": 4,
    "prop2": 4
  },
  {
    "prop1": 3,
    "prop2": 7
  },
  {
    "prop1": 1,
    "prop2": 3
  }
]

Array 2:

[
  {
    "prop1": 1,
    "prop2": 2
  },
  {
    "prop1": 4,
    "prop2": 4
  }
]

I tried with underscore's difference function but it doesn't work well in this scenario. I was thinking of getting object keys, sorting it and hasnhing the objects.That I can compare but I need to get it back into original format. And since these arrays can have up to 5000 object it seems costly.

Is there an effecient solution?

Edit: I have seen the question Difference between two array of objects in JavaScript but that example has static number of properties on which he filters the arrays. That is not the case; I do not know names, nor quantity of properties.

Body:
You could take some hash tables and get the keys first and then the values and check the hash of the other array and filter the result.

This proposal returns the symetriccal difference of the two arrays.

function getDifference(a, b) {
    function getKeyValue(object) {
        var keys = Object.keys(object).sort();
        return {
            key: keys.join('|'),
            value: keys.map(function (k) { return object[k]; }).join('|')
        };
    }

    function setHash(hash, kv) {
        hash[kv.key] = hash[kv.key] || {};
        hash[kv.key][kv.value] = true;
    }

    function isHash(hash, kv) {
        return hash[kv.key] && hash[kv.key][kv.value];
    }

    var hashA = Object.create(null),
        hashB = Object.create(null),
        result;

    b.forEach(function (o) {
        var kv = getKeyValue(o);
        setHash(hashB, kv);
    });

    return Array.prototype.concat(
        [],
        array1.filter(function (o) {
            var kv = getKeyValue(o);
            setHash(hashA, kv);
            return !isHash(hashB, kv);
        }),
        array2.filter(function (o) {
            var kv = getKeyValue(o);
            return !isHash(hashA, kv);
        })
    );
}

var array1 = [{ prop1: 1, prop2: 2 }, { prop1: 4, prop2: 4 }, { prop1: 3, prop2: 7 }, { prop1: 1, prop2: 3 }, { prop2: 3 }],
    array2 = [{ prop1: 1, prop2: 2 }, { prop1: 4, prop2: 4 }, { prop1: 4 }];

console.log(getDifference(array1, array2));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
JUnitReport HTML - Unit Test Results Order
Does anyone know if it is possible to order the HTML page generated by the junitreport task in ant to order the test results by timestamp rather than alphabetically by Class name.

The report does show the timestamp but I can't find anyway to sort the results by it.  I would like the default to be sorting by timestamp.

Many thanks,
Stef

答: JUnitReport uses XSL stylesheets in order to transform the raw XML files into HTML files. You might change the stylesheets in order to generate custom HTML (and thus sort by timestamp). One your stylesheets work, use the styledir attribute (see http://ant.apache.org/manual/Tasks/junitreport.html) to tell ant to use your stylesheets rather than the default ones.</p>