C-style Arrays vs std::vector using std::vector::at, std::vector::operator[], and iterators

Question: I have an application where I have to move data from one array (input) to another array (output), using a third array with a list of destination indexes (map). In a simplified way, I want to do something like output[i] = input[ map[i] ].
I did the following test to try to estimate which will give me better performance between using C-style arrays and std::vector, and in the case of std::vector using different operators as well as iterators. I know that operator std::vector::at() has a performance penalty as it does boundary checking, what I wanted to estimate how much performance hit that would be in order to decide if it is worthy.
I wrote an example application where I move data using different structures and operators. I used gprof to profile it under Linux.
This is the application source code (test.cpp):
#include <iostream>
#include <vector>
#include <assert.h>
#include <limits.h>

// Input and output vector size
const std::size_t vector_size    = 4096;
// Size of the map vector. This value must be
// <= 'vector_size'
const std::size_t map_size      = 2000;
// Number of iteration for each algorithm
const std::size_t num_iterations = 1000000;

// Algorithms
void __attribute__ ((noinline)) map_c_array(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
        out[j] = in[map[j]];
}

void __attribute__ ((noinline)) map_vector_v1(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out.at(j++) = in.at(m);
}

void __attribute__ ((noinline)) map_vector_v2(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out.at(j) = in.at(map.at(j));
}

void __attribute__ ((noinline)) map_vector_v3(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out[j++] = in[m];
}

void __attribute__ ((noinline)) map_vector_v4(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out[j] = in[map[j]];
}

void __attribute__ ((noinline)) map_vector_v5(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (std::vector<std::size_t>::const_iterator mapIt { map.begin() }; mapIt != map.end(); ++mapIt)
        *outIt++ = *(inIt + *mapIt);
}

void __attribute__ ((noinline)) map_vector_v6(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (auto const& m : map)
        *outIt++ = *(inIt + m);
}

// Main program
int main(int argc, char *argv[])
{
    // Run the algorithm based on vectors
    for (std::size_t k {0}; k < 6; ++k)
    {
        // Input vector. It is of size = 'vector_size'
        std::vector<int> in(vector_size, 0);

        // Output vector. It is of size = 'vector_size'
        std::vector<int> out(vector_size, 0);

        // Mask Vector. I want to do out[i] = in[ map[i] ]
        // Its values are indexes of the 'in' vector, so they all need
        // to be less than or equal to 'vector_size'
        // It is of size = 'map_size'. To each value in this vector there will
        // be a corresponding value in the 'out' vector. So, 'map_size' need to
        // be less than or equal to 'vector_size'.
        std::vector<std::size_t> map(map_size, 0);

        // Fill input vector with random numbers
        for (std::size_t i {0}; i < vector_size; ++i)
            in.at(i) = static_cast<int>( static_cast<float>(rand())/RAND_MAX * INT_MIN );

        // Fill the map vector with random number, not greater that the
        // maximum size of the in and out vectors.
        for (std::size_t i {0}; i < map_size; ++i)
            map.at(i) = static_cast<std::size_t>( static_cast<float>(rand())/RAND_MAX * vector_size );

        // Copy the values using each algorithm
        switch (k)
        {
            case 0:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v1(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 1:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v2(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 2:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v3(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 3:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v4(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 4:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v5(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
            case 5:
                for (std::size_t i {0}; i < num_iterations; ++i )
                {
                    map_vector_v6(in, map, out);

                    // Verify that the values were copied correctly
                    for (std::size_t i {0}; i < map_size; ++i)
                      assert( out[i] == in[map[i]] );
                }
                break;
        }

    }

        // Finally, run the algorithm based on C arrays
    {
        // Input vector. It is of size = 'vector_size'
        int in[vector_size];

        // Output vector. It is of size = 'vector_size'
        int out[vector_size];

        // Mask Vector. I want to do out[i] = in[ map[i] ]
        // Its values are indexes of the 'in' vector, so they all need
        // to be less than or equal to 'vector_size'
        // It is of size = 'map_size'. To each value in this vector there will
        // be a corresponding value in the 'out' vector. So, 'map_size' need to
        // be less than or equal to 'vector_size'.
        std::size_t map[map_size];

        // Fill input vector with random numbers
        for (std::size_t i {0}; i < vector_size; ++i)
            in[i] = static_cast<int>( static_cast<float>(rand())/RAND_MAX * INT_MIN );

        // Fill the map vector with random number, not greater that the
        // maximum size of the in and out vectors.
        for (std::size_t i {0}; i < map_size; ++i)
            map[i] = static_cast<std::size_t>( static_cast<float>(rand())/RAND_MAX * vector_size );

        for (std::size_t i {0}; i < num_iterations; ++i)
        {
            map_c_array(in, map, out);

            // Verify that the values were copied correctly
            for (std::size_t i {0}; i < map_size; ++i)
              assert( out[i] == in[map[i]] );
        }

    }
}

(Note: I used the noinline attribute to avoid the compiler to inline my functions, as I want to see then in gprof).
I compiled it with:
g++ -o test test.cpp -Wall -g -O3 -pg

Then I got the profile with:
gprof test

And this is the result:
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
 35.42      3.29     3.29                             map_vector_v2(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 17.17      4.89     1.60                             map_vector_v1(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 11.34      5.94     1.05                             map_vector_v3(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 10.37      6.90     0.96                             map_vector_v5(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  9.72      7.81     0.90                             map_vector_v4(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  8.64      8.61     0.80                             map_c_array(int*, unsigned long*, int*)
  7.67      9.32     0.71                             map_vector_v6(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  0.00      9.32     0.00        1     0.00     0.00  _GLOBAL__sub_I__Z11map_c_arrayPiPmS_

 %         the percentage of the total running time of the
time       program used by this function.

cumulative a running sum of the number of seconds accounted
 seconds   for by this function and those listed above it.

 self      the number of seconds accounted for by this
seconds    function alone.  This is the major sort for this
           listing.

calls      the number of times this function was invoked, if
           this function is profiled, else blank.

 self      the average number of milliseconds spent in this
ms/call    function per call, if this function is profiled,
       else blank.

 total     the average number of milliseconds spent in this
ms/call    function and its descendents per call, if this
       function is profiled, else blank.

name       the name of the function.  This is the minor sort
           for this listing. The index shows the location of
       the function in the gprof listing. If the index is
       in parenthesis it shows where it would appear in
       the gprof listing if it were to be printed.

Copyright (C) 2012-2018 Free Software Foundation, Inc.

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.

             Call graph (explanation follows)

granularity: each sample hit covers 2 byte(s) for 0.11% of 9.32 seconds

index % time    self  children    called     name
                                                 <spontaneous>
[1]     35.3    3.29    0.00                 map_vector_v2(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [1]
-----------------------------------------------
                                                 <spontaneous>
[2]     17.1    1.60    0.00                 map_vector_v1(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [2]
-----------------------------------------------
                                                 <spontaneous>
[3]     11.3    1.05    0.00                 map_vector_v3(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [3]
-----------------------------------------------
                                                 <spontaneous>
[4]     10.3    0.96    0.00                 map_vector_v5(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [4]
-----------------------------------------------
                                                 <spontaneous>
[5]      9.7    0.90    0.00                 map_vector_v4(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [5]
-----------------------------------------------
                                                 <spontaneous>
[6]      8.6    0.80    0.00                 map_c_array(int*, unsigned long*, int*) [6]
-----------------------------------------------
                                                 <spontaneous>
[7]      7.6    0.71    0.00                 map_vector_v6(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [7]
-----------------------------------------------
                0.00    0.00       1/1           __libc_csu_init [21]
[15]     0.0    0.00    0.00       1         _GLOBAL__sub_I__Z11map_c_arrayPiPmS_ [15]
-----------------------------------------------

 This table describes the call tree of the program, and was sorted by
 the total amount of time spent in each function and its children.

 Each entry in this table consists of several lines.  The line with the
 index number at the left hand margin lists the current function.
 The lines above it list the functions that called this function,
 and the lines below it list the functions this one called.
 This line lists:
     index  A unique number given to each element of the table.
        Index numbers are sorted numerically.
        The index number is printed next to every function name so
        it is easier to look up where the function is in the table.

     % time This is the percentage of the `total' time that was spent
        in this function and its children.  Note that due to
        different viewpoints, functions excluded by options, etc,
        these numbers will NOT add up to 100%.

     self   This is the total amount of time spent in this function.

     children   This is the total amount of time propagated into this
        function by its children.

     called This is the number of times the function was called.
        If the function called itself recursively, the number
        only includes non-recursive calls, and is followed by
        a `+' and the number of recursive calls.

     name   The name of the current function.  The index number is
        printed after it.  If the function is a member of a
        cycle, the cycle number is printed between the
        function's name and the index number.

 For the function's parents, the fields have the following meanings:

     self   This is the amount of time that was propagated directly
        from the function into this parent.

     children   This is the amount of time that was propagated from
        the function's children into this parent.

     called This is the number of times this parent called the
        function `/' the total number of times the function
        was called.  Recursive calls to the function are not
        included in the number after the `/'.

     name   This is the name of the parent.  The parent's index
        number is printed after it.  If the parent is a
        member of a cycle, the cycle number is printed between
        the name and the index number.

 If the parents of the function cannot be determined, the word
 `<spontaneous>' is printed in the `name' field, and all the other
 fields are blank.

 For the function's children, the fields have the following meanings:

     self   This is the amount of time that was propagated directly
        from the child into the function.

     children   This is the amount of time that was propagated from the
        child's children to the function.

     called This is the number of times the function called
        this child `/' the total number of times the child
        was called.  Recursive calls by the child are not
        listed in the number after the `/'.

     name   This is the name of the child.  The child's index
        number is printed after it.  If the child is a
        member of a cycle, the cycle number is printed
        between the name and the index number.

 If there are any cycles (circles) in the call graph, there is an
 entry for the cycle-as-a-whole.  This entry shows who called the
 cycle (as parents) and the members of the cycle (as children.)
 The `+' recursive calls entry shows the number of function calls that
 were internal to the cycle, and the calls entry for each member shows,
 for that member, how many times it was called from other members of
 the cycle.

Copyright (C) 2012-2018 Free Software Foundation, Inc.

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.

Index by function name

  [15] _GLOBAL__sub_I__Z11map_c_arrayPiPmS_ (test.cpp) [1] map_vector_v2(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [4] map_vector_v5(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
   [6] map_c_array(int*, unsigned long*, int*) [3] map_vector_v3(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [7] map_vector_v6(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
   [2] map_vector_v1(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&) [5] map_vector_v4(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)

I saw:

A notable performance impact, around 60% slower, when using std::vector::at() respect to std::vector:operator[] (map_vector_v1 vs map_vector_v3).
It seems like using iterators is around 30% faster than using std::vector::operator[] (map_vector_v6 vs map_vector_v3).
I was a little surprise that map_vector_v6 was slightly faster that using C-style arrays (map_c_array).
I thought that map_vector_v5 and map_vector_v6 where equivalent, so I was surprise that map_vector_v6 was faster.

My initial idea was to use map_vector_v1. But now I think I will go with map_vector_v6 making sure that my map vector's values are not out of bounds.
I wanted to share this results in case it can help some else, or in case I'm doing something wrong which is affecting my results.
Note: I'm compiling and running this code in Ubuntu 18.04, with:
$ g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ gprof --version
GNU gprof (GNU Binutils for Ubuntu) 2.30
Based on BSD gprof, copyright 1983 Regents of the University of California.
This program is free software.  This program has absolutely no warranty.

EDIT:
Thank you for all your comments. I did some changes to my code, like generating new map and input vectors in each iteration, and do some operations in the output vector at the end of each iteration to avoid it to be optimized out.
I also added a second second C-style version which uses pointers, which turned out to be faster.
Here is the updated code.
#include <iostream>
#include <vector>
#include <assert.h>
#include <limits.h>
#include <math.h>

// Input and output vector size
const std::size_t vector_size    = 4096;
// Size of the map vector. This value must be
// <= 'vector_size'
const std::size_t map_size      = 2000;
// Number of iteration for each algorithm
const std::size_t num_iterations = 1000000;

// Algorithms
void __attribute__ ((noinline)) map_c_array(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
            out[j] = in[map[j]];
}

void __attribute__ ((noinline)) map_c_array_v2(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
            *out++ = *(in + *map++);
}

void __attribute__ ((noinline)) map_vector_v1(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out.at(j++) = in.at(m);
}

void __attribute__ ((noinline)) map_vector_v2(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out.at(j) = in.at(map.at(j));
}

void __attribute__ ((noinline)) map_vector_v3(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out[j++] = in[m];
}

void __attribute__ ((noinline)) map_vector_v4(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out[j] = in[map[j]];
}

void __attribute__ ((noinline)) map_vector_v5(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (std::vector<std::size_t>::const_iterator mapIt { map.begin() }; mapIt != map.end(); ++mapIt)
        *outIt++ = *(inIt + *mapIt);
}

void __attribute__ ((noinline)) map_vector_v6(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (auto const& m : map)
        *outIt++ = *(inIt + m);
}

// Main program
int main(int argc, char *argv[])
{
    // Run algorithms based on vectors
    for (std::size_t k {0}; k < 6; ++k)
    {
        // Run 'num_itertions' iteration for each algorithm
        for (std::size_t i {0}; i < num_iterations; ++i )
        {
            // Input vector. It is of size = 'vector_size'
            std::vector<int> in(vector_size, 0);

            // Output vector. It is of size = 'vector_size'
            std::vector<int> out(vector_size, 0);

            // Mask Vector. I want to do out[i] = in[ map[i] ]
            // Its values are indexes of the 'in' vector, so they all need
            // to be less than or equal to 'vector_size'
            // It is of size = 'map_size'. To each value in this vector there will
            // be a corresponding value in the 'out' vector. So, 'map_size' need to
            // be less than or equalt to 'vector_size'.
            std::vector<std::size_t> map(map_size, 0);

            // Fill input vector with random numbers
            for (std::size_t i {0}; i < vector_size; ++i)
                in.at(i) = static_cast<int>( static_cast<float>(rand())/RAND_MAX * INT_MIN );

            // Fill the map vector with random number, not greater that the
            // maximum size of the in and out vectors.
            for (std::size_t i {0}; i < map_size; ++i)
                map.at(i) = static_cast<std::size_t>( static_cast<float>(rand())/RAND_MAX * ( vector_size - 1 ) );

            // Copy the values using each algorithm
            switch (k)
            {
                case 0:
                    map_vector_v1(in, map, out);
                    break;
                case 1:
                    map_vector_v2(in, map, out);
                    break;
                case 2:
                    map_vector_v3(in, map, out);
                    break;
                case 3:
                    map_vector_v4(in, map, out);
                    break;
                case 4:
                    map_vector_v5(in, map, out);
                    break;
                case 5:
                    map_vector_v6(in, map, out);
                    break;
            }

            // Verify that the values were copied correctly
            for (std::size_t i {0}; i < map_size; ++i)
                assert( out[i] == in[map[i]] );

            // Do some operation in the data
            for (std::size_t i {0}; i < map_size; ++i)
                out[i] += rand();
        }

    }

    // Run algorithms based on C arrays
    {
        // Run the algorithm based on vectors
        for (std::size_t k {0}; k < 2; ++k)
        {
            for (std::size_t i {0}; i < num_iterations; ++i)
            {
                // Input vector. It is of size = 'vector_size'
                int in[vector_size];

                // Output vector. It is of size = 'vector_size'
                int out[vector_size];

                // Mask Vector. I want to do out[i] = in[ map[i] ]
                // Its values are indexes of the 'in' vector, so they all need
                // to be less than or equal to 'vector_size'
                // It is of size = 'map_size'. To each value in this vector there will
                // be a corresponding value in the 'out' vector. So, 'map_size' need to
                // be less than or equalt to 'vector_size'.
                std::size_t map[map_size];

                // Fill input vector with random numbers
                for (std::size_t i {0}; i < vector_size; ++i)
                    in[i] = static_cast<int>( static_cast<float>(rand())/RAND_MAX * INT_MIN );

                // Fill the map vector with random number, not greater that the
                // maximum size of the in and out vectors.
                for (std::size_t i {0}; i < map_size; ++i)
                    map[i] = static_cast<std::size_t>( static_cast<float>(rand())/RAND_MAX * ( vector_size - 1 ) );

                // Copy the values using each algorithm
                switch (k)
                {
                    case 0:
                        map_c_array(in, map, out);
                        break;
                    case 1:
                        map_c_array_v2(in, map, out);
                        break;
                }

                // Verify that the values were copied correctly
                for (std::size_t i {0}; i < map_size; ++i)
                    assert( out[i] == in[map[i]] );

                // Do some operation in the data
                for (std::size_t i {0}; i < map_size; ++i)
                    out[i] += rand();
            }
        }

    }
}

And this is the result I see now:
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
 30.55      3.88     3.88                             map_vector_v2(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 17.76      6.14     2.26                             map_vector_v1(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
 10.66      7.49     1.35                             map_c_array(int*, unsigned long*, int*)
  9.08      8.65     1.15                             map_vector_v5(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  8.92      9.78     1.13                             map_vector_v3(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  7.89     10.78     1.00                             map_vector_v4(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  7.89     11.79     1.00                             map_vector_v6(std::vector<int, std::allocator<int> > const&, std::vector<unsigned long, std::allocator<unsigned long> > const&, std::vector<int, std::allocator<int> >&)
  7.58     12.75     0.96                             map_c_array_v2(int*, unsigned long*, int*)
  0.00     12.75     0.00        1     0.00     0.00  _GLOBAL__sub_I__Z11map_c_arrayPiPmS_

Comment: A microbenchmark with Google benchmark seems to show that all (except the checked `at` versions) have equivalent performances: http://quick-bench.com/7NXQHXZadv-rFfRgC2lqzxQf_GU See if running the test again / in a different order leads to different results. First hint that your benchmark is not accurate enough is that `map_vector_v5` and `map_vector_v6` do literally compile down to the same assembly
Comment: Additionally you should be touching memory so that all the writes actually go through, otherwise the optimizer could compile away a lot of the actual work. Be careful what you benchmark. At the end of the day the optimizer works miracles.
Comment: @JesusVasquez: The CPU speed isn't locked, nor is memory cleared before the test, so the first chunk of code will usually be slower than the rest. Microbenchmarks are hard.
Comment: It's not a surprise when `std::vector::at()` is a bit slower than `std::vector::operator[]()` which in turn isn't slower than the C array `operator[]`. The main difference between `at()` and `[]` in `std::vector`: `at()` does a range check and may throw an exception in opposition to `[]` which doesn't. The implementation of `std::vector::operator[]()` is probably nothing else than a wrapper around something like the C array `operator[]` (with an additional `assert()` for range check which becomes effective only if `NDEBUG` is not defined.)
Comment: Regarding the microbenchmark I'm a little surprise that that `map_vector_v1` is slower that `map_vector_v2`, as the latter uses the operator `std::vector::at()` 3 times, instead of 2. I re-run the same test, but adding
`benchmark::DoNotOptimize` calls to avoid the vector to be optimized out, and I see a different result: http://quick-bench.com/MFQdK7x72lGLZKxnJtWDzqmRzhs. In this case both `map_vector_v1` and `map_vector_v2` are equivalent
which makes more sense to me. Although in my test I always see `map_vector_v2` being considerable slower.
Comment: I idly wonder at `std::transform(in.begin(), in.end(), std::back_inserter(out), [&](int v){return map[v];});`
Comment: Re: MooingDuck's point about memory init / page faults, and CPU warmup, [Idiomatic way of performance evaluation?](https://stackoverflow.com/q/60291987) covers has some links for more details about that.
Answer: Thank you all for your comments.
I just want to summarize my findings.
According to the measurements I took as describe above:

These 3 forms presented the fastest execution time in the group:

void map_c_array_v2(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
            *out++ = *(in + *map++);
}

void map_vector_v4(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out[j] = in[map[j]];
}

void map_vector_v6(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (auto const& m : map)
        *outIt++ = *(inIt + m);
}

They were followed by these 2 forms, which were ~10-15% slower. They use additional variables to control the loops:

void  map_vector_v3(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out[j++] = in[m];
}

void map_vector_v5(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::vector<int>::const_iterator inIt  { in.begin() };
    std::vector<int>::iterator       outIt { out.begin() };
    for (std::vector<std::size_t>::const_iterator mapIt { map.begin() }; mapIt != map.end(); ++mapIt)
        *outIt++ = *(inIt + *mapIt);
}

Then this form was about 35% slower. It is very similar to the faster map_vector_v4, with the difference that map_vector_v4 uses const references:

void map_c_array(int *in, std::size_t *map, int *out)
{
    for (std::size_t j {0}; j < map_size; j++)
            out[j] = in[map[j]];
}

The this form was more that 2x slower. This one uses the std::vector::at() operator which does additional boundary checking:

void map_vector_v1(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    std::size_t j {0};
    for (auto const& m : map)
        out.at(j++) = in.at(m);
}

And finally this was the slowest, almost 4x slower. This one also uses the std::vector::at() operator as in the previous case, but it uses more of them (3 times instead of 2 times)

void map_vector_v2(const std::vector<int> &in, const std::vector<std::size_t> &map, std::vector<int> &out)
{
    for (std::size_t j{0}; j < map_size; ++j)
        out.at(j) = in.at(map.at(j));
}


SwiftUI Force Portrait On All Except One View

Question: I have a SwiftUI project. For all but one of the views, I want to allow portrait and only portrait mode. For only one view, I want to allow both portrait and landscape. There are some resources on Swift but I couldn't find any on SwiftUI.
Did anyone find a way to accomplish this?
Comment: The current answers of this question is not working in IOS 16, and produces warning `BUG IN CLIENT OF UIKIT: Setting UIDevice.orientation is not supported. Please use UIWindowScene.requestGeometryUpdate(_:)` The solution can be find [iOS 16 Scene orientation issue](https://stackoverflow.com/questions/73649566/ios-16-scene-orientation-issue)
Answer: I had to do something similar to this. Here's our approach.
We set the project orientation to only support Portrait mode.
Then in your AppDelegate add an instance variable for orientation and conform to the supportedInterfaceOrientationsFor delegate method.
static var orientationLock = UIInterfaceOrientationMask.portrait

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return AppDelegate.orientationLock
}

Then when your about to present your landscape view perform the following actions:
AppDelegate.orientationLock = UIInterfaceOrientationMask.landscapeLeft
UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

And on dismissal,
AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

Hope this helps!
Comment: This is locking the device into landscape mode only, but OP requested allowing both portrait and landscape for the view. Is there a solution for allowing both portrait and landscape in this view?
Comment: Thank you so much! I got an error when trying to do
`UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft, forKey: "orientation")`
but I didn't need that part really. The first line was all I needed.
Comment: I'm getting an error: `*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__SwiftValue longLongValue]: unrecognized selector sent to instance 0x282de73c0'`  Any ideas?
Comment: In order to don't get the error, you have to put DispatchQueue.main.async in both the onAppear and onDisappear methods.
Comment: yep, it just works, thanks for this great solution. Bonus: it works on iOS 14, too. I know it should, but  while I'm staring in disbelief at my broken app (that worked perfectly well under iOS 13) on Xcode 12 and iOS 14 many of my certainties have been shattered... so at least this works.
Comment: what i need to do if i want landscapeLeft & landscapeRight?
Comment: Thanks for the great answer! Is there a way to **not animate** the rotation e.g. after the transition within a NavigationView, so that the destination View is already in the rotated state?
Comment: @adelmachris, did you manage to find a solution? I'm having the exact problem
Answer: A couple of tweaks to the answer above:
In AppDelegate as Jonathan's answer above:
static var orientationLock = UIInterfaceOrientationMask.portrait

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return AppDelegate.orientationLock
}

Then in the destinationView - the one that is landscape:
import SwiftUI

struct DestinationView: View {

    var body: some View {
        Group {

            Text("Hello")

        }.onAppear {
            AppDelegate.orientationLock = UIInterfaceOrientationMask.landscapeLeft
            UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
            UINavigationController.attemptRotationToDeviceOrientation()
        }
        .onDisappear {
            DispatchQueue.main.async {
                AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
                UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
                UINavigationController.attemptRotationToDeviceOrientation()
            }
        }
    }
}

Note the .rawValue in the UIDevice line which gets rid of the LongValue error. Also, in the .onDisappear I had to use DispatchQueue.main.async in order to avoid an error when returning back to previous view which is in portrait.
Comment: Such a great answer Zenman!  Simple, straightforward, and it "just works".  Kudos for figuring this out.  Shame on Apple for making this so difficult.
Comment: I used the same thing. Thanks a lot @Zenman C
Minor change from what I faced. I had to wrap the onAppear part in DispatchQueue.main.async as well.
Comment: what i need to do if i want landscapeLeft & landscapeRight?
Comment: For some reason this doesn't work the first few times I go into the view, after going in and out several times all of a sudden it starts to work, and then it keeps working. Very odd. I do add calls to main queue as well.
Comment: Turns out it works fine if I'm not running it from Xcode to device with debugger connected. In case someone else experience this issue. Try and disconnect phone and just run it on device.
Answer: If your app is using SwiftUI lifeCycle, the app is launched using a custom struct that conforms to the App protocol. Your app doesn't have AppDelegate which is needed to implement the above solutions.
To make your own AppDelegate try this code in your appnameApp.swift
@main
struct appnameApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {

    static var orientationLock = UIInterfaceOrientationMask.portrait

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // something to do
        return true
    }

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window:UIWindow?) -> UIInterfaceOrientationMask {
        return AppDelegate.orientationLock
    }
}

Source: https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app
Answer: Plus, you can go further and use Jonathan's code to create an extension for the View class and simply call this extension on the classes you would like to rotate.
extension View {
    func unlockRotation() -> some View {
        onAppear {
            AppDelegate.orientationLock = UIInterfaceOrientationMask.allButUpsideDown
            UIViewController.attemptRotationToDeviceOrientation()
        }
        .onDisappear {
            AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
            UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
            UIViewController.attemptRotationToDeviceOrientation()
        }
    }
}

Answer: use AppUtility from https://stackoverflow.com/a/41811798/10330141
in SwiftUI
create custom UIHostingController
 class OrientationHostingController : UIHostingController<AnyView> {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        AppUtility.lockOrientation(.portrait)

    }
 }

let rootView = OrientationHostingController(rootView: AnyView(SwiftUIView()))

Answer: To offer a slight change to Jonathan's great solution. This version answers folks above asking about how to use other orientations besides just "landscapeLeft".
First, Jonathan stated "We set the project orientation to only support Portrait mode." Don't do this if you want to allow other orientations. So for the project leave "Portrait", "Landscape Left" and "Landscape Right" checked along with "Upside Down" if you also wish this orientation.
Second, in the onAppear of the view you wish to ALLOW rotation, set the following:
AppDelegate.orientationLock = UIInterfaceOrientationMask.allButUpsideDown
The above replaces .landscapeLeft from the original example. Note, if you want to allow upside down, make it .all instead.
That's it. Everything else is as stated by Jonathan and others. The result is that the app will be portrait locked except for the views that you update with onAppear and the code above. For those the user will have access to all the orientations (or all but upside down).


How to find a key in a multiple-value HashMap?

Question: my task is to make a synonym dictionary using HashMaps and Sets.
I have the following code in my main method:
public static void main(String[] args) {

        addSynonym("casa", "imobil");
        addSynonym("casa", "cladire");
        addSynonym("casa", "locuinta");
        addSynonym("casa", "camin");
        addSynonym("casa", "domiciuliu");

        addSynonym("jucarie", "joc");
        addSynonym("jucarie", "marioneta");
        addSynonym("jucarie", "papusa");
        addSynonym("jucarie", "pantin");

        addSynonym("om", "barbat");
        addSynonym("om", "persoana");

        afisarearray(getSynonyms("camin"));
    }

One Method to insert the synonyms and the keys:
static Map<String, ArrayList<String>> synonymTable = new HashMap<String, ArrayList<String>>();

    public static void addSynonym(String word, String synonym) {
        ArrayList<String> checklist = synonymTable.get(word);
        if (checklist == null) {
            ArrayList<String> temporarylist = new ArrayList<String>();
            temporarylist.add(synonym);

            synonymTable.put(word, temporarylist);
        } else {
            synonymTable.get(word).add(synonym);
        }
    }

One Method to display an ArrayList:
    public static void afisarearray(ArrayList<String> list) {
        if (list != null) {
            for (String s : list) {
                System.out.println(s + "\n");
            }
        } else {
            System.out.println("Empty list");
        }
    };

I want to find all the synonyms of a word for example the word "camin". And I wrote the following Method to do it, but it's not working, it is returning an empty set of keys:
public static ArrayList<String> getSynonyms(String word) {
        if (word == "") {
            System.out.println("No word to serach for ");
            return null;
        } else {

            Set<String> keySet = new HashSet<String>();

            for (Map.Entry<String, ArrayList<String>> entry : synonymTable.entrySet()) {
                if (entry.getValue().equals(word)) {
                    keySet.add(entry.getKey());
                }
            }

            if (keySet.isEmpty()) {
                System.out.println("No keys found");
                return null;
            } else {

                ArrayList<String> newlist = new ArrayList<String>();

                for (String s : keySet) {
                    newlist.addAll(synonymTable.get(s));
                }
                return newlist;
            }
        }
    }

The problem is  inside this if:
if (entry.getValue().equals(word))

is a comparison between an ArrayList and a string.
I don't know how to correct it.
Answer: Try this, I also cleaned up your code a bit for readability
public static List<String> getSynonyms(String word) {
    if (word == null || word.trim().isEmpty()) {
        System.out.println("No word to serach for ");
        return null;
    }

    Set<String> keySet = new HashSet<String>();

    for (Map.Entry<String, List<String>> entry : synonymTable.entrySet()) {
        if (entry.getValue().contains(word)) {
            keySet.add(entry.getKey());
        }
    }

    if (keySet.isEmpty()) {
        System.out.println("No keys found");
        return null;
    }

    //de-dupe and sort
    Collection<String> terms = new TreeSet<>();

    for (String s : keySet) {
        terms.addAll(synonymTable.get(s));
    }

    return new ArrayList<>(terms);
}


Fret buzz present only at specific situations - how to explain?

Question: I hear a strange fret buzz on my classical guitar, but only at a very specific situation. If I do both of the following, I hear the buzz:

Hold 5th string at 8th fret (note F), but not play it
Pluck the 3rd string on 9th fret (note E)

In this situation, the 5th string buzzes. The buzz is not very annoying, but is consistent (happens all the time). I did the following experiments with it:

Tried another guitar - the buzz doesn't happen
Played the E on the first string - the buzz becomes very weak, almost disappears
Played other notes on the third string - the buzz doesn't happen
Held other positions on the 5th string - the buzz doesn't happen
Tried various orientations of the guitar - the buzz disappears in a few situations (e.g. the guitar is flat on a soft surface)
Tuned the 3rd string up/down a little - the buzz disappears
Tuned the 5th string up/down a little - the buzz disappears

So I have the following questions about it:

Does the 5th string graze the 9th fret, or can it be any other fret?
How can one explain this physically? Can I say anything more specific than "there is a spooky resonance somewhere"?
Is there a good chance I can get rid of this by filing down the problematic fret?
Comment: I had a similar highly contextual buzz on a steel string. A luthier recognised and sorted it instantly for not much money. No idea what it was, but that's why he builds guitars and I don't. I'd never try to fix a symptom unless I was absolutely certain that it was also the root cause.
Answer: WIth that fingering, have you tried plucking the 5th string on the nut side of your fretted point? You will find that the vibrating string between the nut and 7th fret gives the same note you are plucking on the 3rd string.
Normally the nut side of each string will resonate a little if damped (which is why for tapping passages, many musicians use a nut damper like a cloth or similar), but it sounds like your 7th fret is perhaps a little worn down so the string is buzzing against one if the lower frets.
Definitely do not try filing down a fret to try and fix the problem. If you haven't done it before you will make it worse. Take it to your local guitar shop and get them to sort the frets out.


What is the exact difference between Prediction and Extrapolation?

Question: Apologies if the question is too trivial but what exactly sets these two apart?
Let's say that I have a set of data for a hundred points (the independent variable may not be uniformly spaced) as:
{{1, 7}, {2, 8},...,{100, 5}}
Now, I can apply any of the extrapolation techniques (Newton's, Lagrange's or even Curve Fitting for that matter) and get a y = f(x). Now if I put in any x, in or out from my original data set, I can get the corresponding y. This way I predicted a y value which wasn't originally in my data set.
How is Prediction different from this?
Comment: Does this answer your question? [What is the difference between estimation and prediction?](https://stats.stackexchange.com/questions/17773/what-is-the-difference-between-estimation-and-prediction)
Comment: @Carl Thank you for the flag: identifying duplicates takes effort and is always useful.  But that thread would be a duplicate only if extrapolation and estimation were the same thing, but they are not.
Answer: Extrapolation is estimation of dependent values outside the range covered by the (independent) data the model has been fit to: https://en.wikipedia.org/wiki/Extrapolation. It's not the same as interpolation, which is estimation between original data points. Prediction usually refers to future events, but in your context you could say (regarding the estimates) prediction is a hypernym of fitted values + interpolation + extrapolation.
Comment: I understand the difference between extra/interpolation but that's not my question. Can you elaborate more upon Extrapolation vs Prediction? Your current answer (last statement) isn't satisfactory enough.
Comment: To add to what @Alexis said, in spatial statistics interpolation and extrapolation are *both* considered to be prediction.  They are often distinguished by whether the support of the prediction (the x-values) lies within the convex hull of the data or not, respectively.  In one dimension that distinction comes down to whether the prediction is made for an x value within the data range or beyond it (in either direction).
Comment: There is no "vs". Extrapolation is prediction outside of the ranged covered by data, interpolation is prediction inside this range.
Comment: Basically. Although prediction refers to, well, prediction of future observations (which is important for estimation of uncertainties) whereas that's not necessarily the case for extrapolation and interpolation.
Comment: It is not clear to me that all predictive models extrapolate. E.g., time series analysis models based on well-informed and empirically backed data-generating processes, and dynamic empirical modeling methods, such as simplex projection, would seem to be interpolation-based, not extrapolation based.
Comment: So `prediction` is just a term for saying `extrapolation & interpolation`. In other words, every prediction is either an extrapolation or an interpolation?
Comment: @whuber Yes, one can call just about any statistical procedure a prediction, and that is misleading because it is often irrelevant or even wrong. The mean value of uniformly random integers from 1 to 6 is 3.5, which is not closed for integers, so 3.5 is a wrong prediction. A least error prediction from OLS in y predicts an equation that is wrong for bivariate data, but it offers a least error of "predicting" y given x. More accurately, it is an observed least error mapping of x to y.  One can call any probability a "prediction," but more accurately it is a post hoc observation.
Comment: @Carl You misread my comments and misuse the terms.  I have explicitly distinguished estimation from prediction.  Guessing the value of a random variable is not merely a matter of estimating a probability related to its distribution.  For details, please [read our thread on this topic](https://stats.stackexchange.com/questions/17773).
Comment: @whuber In your answer, that you refer to above, you state, "a predictor usually has larger uncertainty than a related estimator" I do not agree. OLS in y has less error of prediction of y given x and a higher R$^2$ than a bivariate estimating equation, which has better accuracy if the data is indeed bivariate. A bivariate estimating equation is not a least error predictor, the thing "predicted" is the bivariate equation, and is useful, for example, in clinical laboratories to replace test A with test B. It seems to me you are misusing terms by lumping different things into the same terms.
Comment: @Carl I invite you to look up these terms in any reputable textbook.
Comment: @whuber OK, This is more or less what I am using: From https://stats.oecd.org/glossary/detail.asp?ID=3792  "Definition:
In general, prediction is the process of determining the magnitude of statistical variates at some future point of time. In statistical contexts the word may also occur in slightly different meanings; e.g. in a regression equation expressing a dependent variate y in terms of dependent x's, the value given for y by specified values of x's is called the "predicted" value even when no temporal element is involved." What are you using?
Comment: @Carl I avoid the econometric literature like that link, which employs some terminology narrowly (everything seems to revolve around time series), and rely on classic statistics texts like Hahn & Meeker, *Statistical Intervals* section 1.2, Wasserman's *All of Statistics* (especially exercise 13.10), or *Kendall's Advanced Theory of Statistics,* Volume 2, Fifth Edition, sections 28.9 - 28.12. I first learned of the distinctions between estimation and prediction in the spatial statistics literature, where that concept is fundamental and the "future" isn't around to confuse people.
Comment: @whuber I think you have a point but I feel like I am shadow-boxing. This is really another question even more nitty-gritty than what the OP asked here, and this text is not really helping anyone. Therefore, let us move this to a discussion on it own merit. https://stats.stackexchange.com/questions/599212/what-exactly-does-prediction-mean-in-best-statistical-terms-and-when-is-it-inapp
Answer: The explanation is excellent, however, the casual association of the term prediction to future events may have been too subtle. In other words, I don't know that the implied other part of that explanation was derived. Prediction = future event, estimation = not necessarily future, i.e. fitted value, can be inferential (established population).
Comment: In statistics, "prediction" does not necessarily involve any concept of time.  It means to guess the value of a random variable.  See https://stats.stackexchange.com/questions/17773.  In contrast, "estimation" means to guess the value of a parameter (usually considered non-random).
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stats.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://stats.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/336063)


how to fetch parts of url in javascript

Question: I have a url like this: http://localhost/something/de/
The last one is the language code de for German. I want to fetch it using javascript. The link may also become like this: http://localhost/something/de/node/artist/117/author/98, in that case how do I fetch the language part.
Actually I want to set up placeholder using javascript, I got the help for placeholder but I dont get how to fetch the language part from url.
Answer: You can do this in jQuery, just get the url and then split as required.
<code>$(document).ready(function() {
    var $url = window.location.pathname;
});
</code>

how to fetch parts of url in javascript


Show that $Tr(A)=(-1)^{n-1} a_{n-1}$

Question: Let $A$ be an $n \times n$ matrix with characteristic polynomial:
$$\phi_A(t)=(-1)^n t^n + a_{n-1} t^{n-1} + \cdot \cdot \cdot +a_1 t + a_0$$
Show that $Tr(A)=(-1)^n a_{n-1}$
I think I have seen similar problems like this one solved here but they are not focused on the trace of $A$ but on other properties of the characteristic polynomial of $A$
My attempt:
By the Cayley-Hamilton Theorem we have: $\phi_A(A)=0$, so:
$$(-1)^n A^n + a_{n-1} A^{n-1} + \cdot \cdot \cdot +a_1 A + a_0 I = 0$$
If we get the trace of both sides of the last expression and use the linearity of the trace then:
$$(-1)^n Tr(A^n) + a_{n-1} Tr(A^{n-1}) + \cdot \cdot \cdot +a_1 Tr(A) + n a_0 = 0$$
I'm not sure how to proceed next. Could someone give me a hint?
Comment: Cf. [this question](https://math.stackexchange.com/questions/1616930/trace-and-the-coefficients-of-the-characteristic-polynomial-of-a-matrix)
Comment: The trace is the sum of the eigenvalues which are the roots of the characteristic polynomial, so by standard results for roots of polynomials the trace is equal to the coefficient of $t^{n-1}$ (after normalising the leading term).
Comment: @kipf Are you sure? There are matrices that have no eigenvalues, so the trace can't be the sum of them
Comment: Every $n \times n$ matrix has a characteristic polynomial of degree $n$, so by the fundamental theorem of algebra must have at least one distinct root in $\mathbb C$. Every square matrix has at least one eigenvalue in $\mathbb C$.
Answer: Triangularize your matrix in a field extension $\mathbb{L}$, you will easily find that $\text{tr} = (-1)^n a_{n-1}$ since neither of the characteristic polynomial and the trace depend on the field extension.
Answer: I suppose that the characteristic polynomial of $A$ is defined to be the determinant of $A - tI$, where $t$ is the indeterminate. I suppose that the trace of $A$ is defined to be the sum of the diagonal entries of $A$.
I do not know how you define the determinant of a square matrix. However, I will give a solution that is independent of the definitions.

Before solving your question, I need a formula, which you might have seen.
Let $A$ be an $n \times n$ matrix. Suppose that the $(i, j)$-entry of $A$ is $[A]_{i,j}$. Suppose that column $j$ of the $n \times n$ identity matrix $I$ is $e_j$. Suppose that column $j$ of $A$ is $\alpha_j$ (which means that $A = [\alpha_1, \alpha_2, \dots, \alpha_n]$.) One can write
$$
\alpha_{k}
= [A]_{1,k} e_{1} + [A]_{2,k} e_{2}
+ \dots + [A]_{n,k} e_{n}
= \sum_{i_k = 1}^{n} {[A]_{i_k,k} e_{i_k}}.
$$
Hence, by the multilinear property,
$$
\begin{align*}
    \det {(A)}
    = {} &
    \det {[\alpha_1, \alpha_2, \dots, \alpha_n]}
    \\
    = {} &
    \det {\left[ \sum_{i_1 = 1}^{n} {[A]_{i_1,1} e_{i_1}, \alpha_2, \dots, \alpha_n} \right]}
    \\
    = {} &
    \sum_{i_1 = 1}^{n} {[A]_{i_1,1}\,
    \det {[ e_{i_1}, \alpha_2, \dots, \alpha_n ]}}
    \\
    = {} &
    \sum_{i_1 = 1}^{n} {[A]_{i_1,1}\,
    \det {\left[ e_{i_1}, \sum_{i_2 = 1}^{n} [A]_{i_2,2} e_{i_2}, \dots, \alpha_n \right]}}
    \\
    = {} &
    \sum_{i_1 = 1}^{n} {
    \sum_{i_2 = 1}^{n} {[A]_{i_1,1} [A]_{i_2,2}\,
    \det {[ e_{i_1}, e_{i_2}, \dots, \alpha_n ]}}}
    \\
    = {} &
    \dots \dots \dots \dots
    \dots \dots \dots \dots
    \dots \dots \dots \dots
    \dots \dots \dots \dots
    \\
    = {} &
    \sum_{i_1 = 1}^{n} {
    \sum_{i_2 = 1}^{n} {
    \dots
    \sum_{i_n = 1}^{n} {
    [A]_{i_1,1} [A]_{i_2,2} \dots [A]_{i_n,n} \det {[e_{i_1}, e_{i_2}, \dots, e_{i_n}]}}}}.
\end{align*}
$$
Because of the alternating property, one can write
$$
\boxed{
\det {(A)}
= \sum_{\substack{
1 \leq i_1, i_2, \dots, i_n \leq n \\
        i_1, i_2, \dots, i_n\,\text{are distinct}
    }}
{[A]_{i_1,1} [A]_{i_2,2} \dots [A]_{i_n,n} \det {[e_{i_1}, e_{i_2}, \dots, e_{i_n}]} }.
}
$$

Okay. I am going to solve your question.
The characteristic polynomial of $A$ is
$$
\det {(A - tI)}
= \sum_{\substack{
1 \leq i_1, i_2, \dots, i_n \leq n \\
        i_1, i_2, \dots, i_n\,\text{are distinct}
    }}
{[A - tI]_{i_1,1} [A - tI]_{i_2,2} \dots [A - tI]_{i_n,n}
\det {[e_{i_1}, e_{i_2}, \dots, e_{i_n}]} }.
$$
Your question amounts to finding the coefficient of $t^{n-1}$ (of the expansion). You are invited to prove, that among the $n!$ (unexpanded) terms, there is exactly one term which contains $t^{n-1}$, which is
$$
\begin{align*}
& [A - tI]_{1,1} [A - tI]_{2,2} \dots [A - tI]_{n,n}
\det {[e_{1}, e_{2}, \dots, e_{n}]} \\
= {} &
([A]_{1,1} - t)
([A]_{2,2} - t)
\dots
([A]_{n,n} - t) \cdot 1.
\end{align*}
$$
Hence the coefficient of $t^{n-1}$ is
$$
(-1)^{n-1} ([A]_{1,1} + [A]_{2,2} + \dots + [A]_{n,n}).
$$

Show that $Tr(A)=(-1)^{n-1} a_{n-1}$


Returning values to JavaScript when calling an Objective-C function

Question: I've been using WebViewJavascriptBridge to bridge Objective-C and JavaScript in an iOS application. It works great but it lacks support for returning values to the calling JavaScript code from the called native Objective-C function.
I'm pretty sure that Cordova (PhoneGap) does that in some way with callbacks but I've been having a hard time trying to understand how the underlying mechanics work.
Is there anyone who's had the same problem and that managed to find a solution?
Answer: Now, I've never used WebViewJavascriptBridge, but I have done this in objective-c using a simple delegate, so maybe this will help you:
MyScript.js
// requestFromObjc
// functionName (required):
//      the name of the function to pass along to objc
// returnedResult (not used by caller):
//      the result given by objc to be passed along
// callback (not used by caller):
//      sent by objc, name of the function to execute
function requestFromObjc(functionName, objcResult, callback)
{
    if (!objcResult)
    {
        window.location = "myapp://objcRequest?function=" + functionName + "&callback=" + arguments.callee.name + "&callbackFunc=" + arguments.callee.caller.name;
    }
    else
    {
        window[callback](objcResult);
    }
}

function buttonClick(objcResult)
{
    if (!objcResult)
    {
        // ask for the color from objc
        requestFromObjc("buttonColor&someParam=1");
    }
    else
    {
        // do something with result (in this case, set the background color of my div)
        var div = document.getElementById("someDiv");

        div.style.background = objcResult;
    }
}

MyPage.html

            This is my div! Do not make fun of it, though.

        <button onClick="buttonClick(undefined)">
            Click Me!
        </button>

ViewController.m
-(NSString *) javaScriptResultForRequest:(NSDictionary *) params
{
    if ([params[@"function"] isEqualToString:@"buttonColor"])
    {
        NSArray *colors = @[ @"red", @"yellow", @"blue", @"green", @"purple" ];
        return colors[arc4random_uniform(colors.count)];
    }
    else
    {
        return @"undefined";
    }
}

-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] scheme] isEqualToString:@"myapp"])
    {
        // parse the URL here
        NSURL *URL = [request URL];

        if ([URL.host isEqualToString:@"objcRequest"])
        {
            NSMutableDictionary *queryParams = [NSMutableDictionary dictionary];
            NSArray *split = [URL.query componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&="]];

            for (int i = 0; i < split.count; i += 2)
            {
                queryParams[split[i]] = split[i + 1];
            }

            NSString *result = [self javaScriptResultForRequest:queryParams];
            NSString *jsRequest = [NSString stringWithFormat:@"%@(\"%@\", \"%@\", \"%@\")", queryParams[@"callback"], queryParams[@"function"], result, queryParams[@"callbackFunc"]];

            // now we send this to the target
            [self.webView stringByEvaluatingJavaScriptFromString:jsRequest];
            return NO;
        }
    }

    return YES;
}

Obviously this is much slower than trying to do the equivalent function in pure JS, because of all the loops it has to jump through. However, if there is something you need to use in your JS code that's in your ObjC code already, this may be for you.
Answer: If you mean, "return" in the sense that your JS caller will see the results as returned from the call, I don't know how to do it.  I suspect it would take a level of thread manipulation not available in JS.  Instead, you can recode your JS side logic to create a result handler function.   In pseudo code:
res = CallObjC(args);
work with res...

Becomes
CallObjC(args, function(res) { work with res...});

Admittedly a bit awkward but get used to it - it is a very common pattern.  Internally, the JS bridge code creates a mapping of the request to the callback function.  When the ObjC code has the result, it uses WebView's stringByEvaluatingJavaScriptFromString to call the JS bridge code that locates and invokes the callback.
@Richard - Be a bit careful with the solution you posted.  Setting window.location to invoke shouldStartLoadWithRequest can result in both lost functionality in the webview and also lost messages to ObjectiveC.  Current practice is to use an iframe and have some kind of message queue that can buffer up messages.
Comment: How would you write this with two arguments? When I run this function, I get an error for too many arguments.
Comment: Should probably create a new question with your code and exactly when and where the error occurs.
Answer: WebViewJavascriptBridgehave no maintain for a long time.
Maybe you should change to use this library.
SDBridgeOC
 self.bridge.consolePipeBlock = ^(id  _Nonnull water) {
        NSLog(@"Next line is javascript console.log------>>>>");
        NSLog(@"%@",water);
    };

This can easy to get javascript console.log.
Also have Swift language Version.
SDBridgeSwift
bridge.consolePipeClosure = { water in
         guard let jsConsoleLog = water else {
             print("Javascript console.log give native is nil!")
              return
         }
         print("Next line is Javascript console.log----->>>>>>>")
         print(jsConsoleLog)
      }

Also have h5 demo for your partner.


Transfer from RAID-1 to RAID-0 -- easy as cloning?

Question: I have a RAID-1 of 1TB drives using on-board RAID. I have 2 new 240GB SSDs I want to place in RAID-0. This is Windows Server 2012.
I know with disk cloning/transferring that it is important going from small to bigger sized disks. Do I need to drop all my free space to it's own partition then copy/clone the partition with the contents on it?
Can I just use cloning software to clone from the RAID-1 to RAID-0?
Yes, I understand RAID-0 is not ideal or safe. I just would like to the performance gain and I keep backups on several NAS devices and other locations.
Answer: If the cloning software operates at a filesystem level, then yes it is just that easy. You could also use some sort of dircopy type program (I'm more familiar with linux, myself) - basically, anything that simply copies recursively from the old RAID-1 to the new RAID-0 will work.
Answer: The answer on this one is, "it depends". It depends on the software doing the restore back to the new array. Some software has the option to allow restore to a smaller partition, such as Acronis. Some automatically will fail if the source partition is greater than the new destination, even if the actual used space is well within the limits of the new destination.
Run a defrag beforehand to attempt to cleanup the partition as much as possible.


Are temporary profiles copied from the "Default" profile?

Question: I am in a situation where I know users will be logging in with temporary profiles while we decommission a server.
I would like to make a small change that gets applied to newly created temporary profiles, mainly just adding a file to the app data folder.
When a temporary profile is created, is it just a copy of the "Default" profile folder? If so, can I simply add the file I need to the default profile folder, and have new temporary profiles get a copy of that file?
Comment: What happens when you try that?
Comment: Are you asking because you think I should have tried before asking the question? I haven't tried it yet, as I was worried that futzing with the default system profile might have some negative repercussions. Just wanted to confirm the process Windows goes through when creating temporary profiles, and if this is a safe thing to do first.
Comment: Do it in the lab.  And yes, I am implying that you should test and then come back to us if you still have a question.
Comment: Unfortunately we do not have a lab environment. I could setup a quick test on a Hyper-V VM on my PC, but not sure how people feel about unlicensed VMs like that?
Comment: For quick checks you can use the trial versions. Permanent lab setups need to be licensed normally.
Answer:
When a temporary profile is created, is it just a copy of the
  "Default" profile folder? If so, can I simply add the file I need to
  the default profile folder, and have new temporary profiles get a copy
  of that file?

Yes.  Tested and verified on Win 7 SP1.
For future work I'd strongly encourage setting up a test environment.  even if you're short on budget you should be able to set up usable test environments using free hypervisors and Windows evaluation period.
Comment: Ok many thanks. Have deployed my file to the Default profile, so tomorrow should yield the results I was hoping for. Appreciate the advice on test setups. Wasn't sure if the evaluation period could be used for this purpose, especially if I have to reinstall repeatedly after the period expires.


How should regularization parameters scale with data size?

Question: I am choosing parameter vectors $\beta$ and $\nu$ to minimize an expression of the form:
$$-\log{L(Y;X\beta,\nu)}+\frac{1}{2}\lambda {(\beta - \beta_0 )}^{\top} {(\beta - \beta_0 )}$$
where $\lambda$ is a regularization parameter, $\beta_0$ is a fixed constant, $L(Y;X\beta,\nu)$ is the likelihood of the observation vector $Y$ given $X\beta$ and $\nu$.(The actual likelihood is messy. However, it is the case that $\mathbb{E}Y=X\beta$.)
I have to solve many problems of this form. While it is computationally feasible to choose $\lambda$ by K-fold cross validation on an example problem, it is not computationally feasible to re-optimize $\lambda$ for every different $X$.
How should I scale $\lambda$ as the dimensions $n\times p$ of $X$ vary?
Does it matter that in my particular application I am optimizing subject to the constraints that $\beta\ge 0$ and $\beta^\top 1_p = 1$ (where also $\beta_0^\top 1_p = 1$)?

An answer to this question (partly clarified below) suggests that for linear regression, it may be optimal to have $\lambda=O_p(p)$ (on the order of $p$, in probability) as $p\rightarrow \infty$. If I've understood correctly, is it reasonable to assume this generalizes to non-Gaussian likelihoods?
Answer: I'm sorry to have given you the wrong impression. The optimal value of $\lambda$ obtained through cross-validation increases roughly with $\frac{p}{n}$. In the example of the linked question, the change is so large that you can expect $\lambda_\text{CV}$ to decrease. However, the rough part was perhaps understated in my answer there. The optimal penalty depends on the number of observations ($n$), the number of parameters ($p$) and the actual values of the outcome ($y_i$). There is no scaling that I am aware of that takes all three of these into account appropriately (could make for an interesting paper one exists).
Consider the results of a simple simulation of $1 \leq \frac{p}{n} \leq 100$ in R below:
<code>set.seed(1234)
MC <- 1000
l_CV <- numeric(MC)
ns   <- numeric(MC)
ps   <- numeric(MC)
for(i in 1:MC){
  n       <- round(runif(1, 3, 100))
  ns[i]   <- n
  p       <- round(n * runif(1, 1, 100))
  ps[i]   <- p
  X       <- matrix(rnorm(n * p), nrow = n, ncol = p)
  y       <- X %*% rnorm(p) + rnorm(n)
  l_CV[i] <- cv.glmnet(scale(X), y, alpha = 0)$lambda.min
  cat("\n", i, ": n =", n, "p =", p, "l =", l_CV[i])
}
plot(l_CV ~ I(ps / ns))
plot(l_CV ~ I(ps / ns), log = "y")
</code>

There is a clear trend towards an overall increase in $\lambda_\text{CV}$, but the variance is large and grows with the ratio. Even if with a logarithmic $y$-axis, only a rough relationship can be discerned. Perhaps I'm missing something obvious, but there even appears to be a bifurcation.
There are alternative methods to cross-validation though, such as: approximate generalized CV, L-curve, and the discrepancy principle. You may find that an implementation exists (or perhaps you can write one yourself) that reduces that computational load beyond the problematic amount you experienced with exact cross-validation.
Comment: According to the glmnet documentation, R already effectively scales $\lambda$ by $n$, since their minimand contains $\frac{1}{n}$ times the log-likelihood or RSS. So this exercise may not line up with my original question. (This is why I was cautious about what minimand you had in mind originally!)
Comment: Golub, G.; Heath, M.; Wahba, G. (1979). "Generalized cross-validation as a method for choosing a good ridge parameter" give various analytic $O_p$ type results on quantities closely related to $\lambda_{CV}$, which is what led me to expect that there ought to be a result for $\lambda_{CV}$.
Comment: Obviously any result would only hold for $n\rightarrow \infty$ and $p\rightarrow \infty$, and it would only hold in probability.
Comment: I guess were something like this true it would also require $\frac{p}{n}\rightarrow \infty$ too.


Drupal 7 - views blocks not displaying page field content

Question: I have a page where a view is creating a block which loads a field.
Other blocks loaded into the region are showing up just fine but that particular one will not show.  It is not because the field is empty or otherwise, I can creae labels and tables and empty conditions etc that do not get picked up at all
Is there something that has to be done to template files or otherwise to enable blocks created by views?
Comment: does ur block use a contextual filter?
Answer: A block created by view shows up as any other view, unless you have permission control for the block at views level or at block level.
Permission at views

Permission at block

Visibility settings - By various ways block visibility can be controlled, ensure you have appropriate configurations for this.

Region Settings - Ensure you are putting the block in the region of right theme you are expecting the block to see.

Few things to debug.

Login with super admin(user id 1) see if you can see the block, if yes it will ensure you have permission issues.


NodeJS listening on HTTP and HTTPS for one single domain name

Question: I use express and a server cloud on AWS (Amazon Web Server) and a DNS "mydomain.com".
Question: how can I avoid my users to have to writing in the Browser-URL: http://mydomain.com:4000 and https://mydomain.com:3000
This is my code:
sudo node app.js
var app = express();
var server = http.createServer(app).listen(4000, function() {
        console.log('Express HTTP server listening on port ' + app.get('port'));
});
var server = https.createServer(credentials, app).listen(3000, function() {
        console.log('Express HTTPS server listening on port 3000');
});

// redirect all http requests to https
app.use(function(req, res, next) {
  if(!req.secure) {
    return res.redirect(['https://mydomain.com', req.url].join(''));
  }
  next();
});

I want my user to be able to write my domain name using http and https with no port numbers. I already have a SSL certificate and everything is working fine, but I haven't been able remove the port-numbers and use both: https and http.
Any idea? please :)
I use MEAN stack (Mongo, Express, Angular, )
Comment: Aside from the non-default port issue that is the subject of my answer, you have a problem in your code where you're creating 2 server objects but assigning both of the to the one variable.  If you want to be able to access both servers in your code you'll need 2 different variables.
Comment: I don't understand your answer, can you please give me a code example? please
Comment: @AndrewCooper, my app is really extensive and if I use two apps I will have to duplicate all my code, but how can I use two server objects and two apps without duplicate my code?
Answer: The only way to do that is to use the default ports for the protocols.  That is, Port 80 for HTTP and Port 443 for HTTPS.
If you don't use the default protocol ports then the only way for the browser (or whatever client the users are using) to determine which port to connect to is for the user to specify it in the URL.
Edit - To address your comment above about different server objects
In the code in your question you create an HTTP server and then use the variable server to hold a reference to the object.  You then create an HTTPS server and assign it to the same variable.  If you use the server variable later in your code then you'll be dealing with the HTTPS server object, but will have no way to reference the HTTP server object.
To fix this, just use two different variables to hold the object references.
var httpServer = http.createServer ....
var httpsServer = https.createServer ....

Comment: As sson as I use the default ports: 80 and 443, then I get this error: "listen EADDRINUSE".
Comment: Try `netstat -punta | grep 80`
Comment: ... or `lsof -i -P | grep 80`
Comment: Thanks @Andrew. When I do `netstat -punta | grep 80` then I get: `tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN - `. What does that mean? should I change the config of the EC2 server?
Comment: It means something is listening on port 80.  You'll need to work out what it is.  Does `lsof -i -P` help?
Comment: As sson as I use the default ports: 80 and 443, then I get this error: "listen EADDRINUSE". is there any option with iptables?
Comment: Sure.  You could have iptables redirect incoming connections to port 443 to port 3000, but then why would you not just listen on port 443 in the first place?
Comment: Sounds like something might already be listening on one/both of those ports.
Comment: No, nothing is listening on port 80 and 443, I just double check with lsof -i | grep 443 and lsof -i | grep 80
Comment: THIS ANSWER IS REALLY USELESS AS THE PORT 80 AND 443 IS ALWAYS RESERVE FOR THE OPERATIVE SYSTEM.
Comment: @lito - Which operating system?  Those ports are not reserved in any general purpose operating system that I know of.  If they were there'd be no way to stand up a standard web server.  If they really are reserved in the OS you're using then there's no way to do want you want without putting a separate proxy machine in front of your server to do the port translation - or maybe some iptables rules that intercept the traffic at the IP layer.


Is it possible to migrate 2003 domain to 2019 (Windows Server)?

Question: I have an old Server 2003 domain, and need to install a new server and move all to it. As far as I tried, there i no way to add a new domain controller to 2003 level domain (2008 or higher, only).
The new 2019 server added without issue to old domain, but as it seems there will be no transfer of users and roles to new server.
There is only about 20 users, so I can recreate them, but I am not sure about user's profiles on their local workstations.
My current idea is to:

disjoin the new server from domain
recreate a new old domain
unjoin users from one domain to the new one

Presumption is that if I use the same username that the old local profile will be pulled in that case?
Any suggestions welcome, I have to start solving this issue his week.
Answer: The easiest method is to use a in-between OS and do a first step migration, 2003 -> 2008R2, and after to 2019.
Don't forget when you buy a operating system you have downright right, so yes it's possible to execute what you are looking for with what you have in hands.
nb; Your method is a good plan if it's a small domain/shop without Exchange, SQL or  any advanced setup as you will break all your security sid by dooing so.
Comment: @mrmut Yes, and the only pre-req step you will have to do in the 2008R2 to be ready for 2019 is to migrate the FRS to DFS for the SYSVOL volume. It's kinda easy to do, but just to mention it
Comment: As an update, I did it doing this step update and it worked fine.
Comment: I think the solution you suggest is best, with intermediary OS. I presume I would need first to migrate the 2003 DC domain role to 2008, raise functionality level to 2008 level, turn off old server, then add 2019 server and migrate DC to it and raise domain functionality level 2016 (max), and then turn off 2008 VM?
Comment: Thanks. I would probably come to that myself later when I would got stuck. My current thinking was more in line of creating a new domain in parallel. I have a small number of users, the file server is a dumb NAS, and no resources other than DNS and user/domain management are located on 2003. So the idea is to transfer user by user, and migrate the user interface. That way I won't carry junk from old 2003 installation over, and would have a clean state (I was not who built a system in the first place, and it is generally poorly done.).
Comment: @mrmut It's your call, but the first option will make it transparant to the user, you will never touch their computers, while the second you will have to do profile migration and such.
Comment: Thanks. I will give this a serious thought.


why the for loop not giving factorial?

Question: I am using for-loop to get factorial of a number but the code is not working. Can anyone fix the error using for loop?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main() {
    /*35.   Making a program to give factorial */
    int factorial = 1;
    int i = 1;
    int num;

    printf("Enter the number whose factorial needed");
    scanf_s("%d", &num);

    for (i = 1; i <= num; i--) {
        factorial *= i;
        printf("%d\n", factorial);
    }
    _getch();
    return 0;
}

Comment: Note that you can probably only calculate 12! before you run into overflows.
Comment: change `for (i=1;i <= num;i--)` to `for (i=1;i <= num;i++)`. and take the printf statement outside the loop. also `#include ` should be `#include `
Comment: thanks it was really helpfull....
Answer: Change i-- to i++ in the for loop
Answer: I believe the reason why this is happening is because you have the following
for(int i =1;i <num; i--) when you really want i++;
Answer: Your for loop is not correct, increment the counter instead of decrement
for (i=1;i <= num;i++) {
//-----------------^

why the for loop not giving factorial?


vsftp not able to login from localhost

Question: I have setup vsftpd on a centos-7. There are simple and straight forward tutorials for that. However, not only from outside of the server, even from the localhost, I am not able to login via ftp.
[root@localhost ~]# cat /etc/vsftpd/ftpusers
# Users that are not allowed to login via ftp
root
mahmood
bin
daemon
adm
lp
sync
shutdown
halt
mail
news
uucp
operator
games
nobody
[root@localhost ~]# ftp mahmood@localhost
ftp: mahmood@localhost: Name or service not known
ftp> quit

[root@localhost ~]# ftp localhost
Trying ::1...
Connected to localhost (::1).
220 (vsFTPd 3.0.2)
Name (localhost:root): root
530 Permission denied.
Login failed.
ftp> quit
221 Goodbye.

Any idea about that?
Comment: If you want to log on as user mahmood then `mahmood@localhost` is probably not a valid syntax for your FTP client, check `man ftp` how to specify the username on the commandline
Answer: To be clear, it looks like you can connect to the FTP server, you just can't login. There's a significant difference.
That looks like correct behaviour. Remember that the ftpusers file lists the accounts which are not allowed to login to the FTP server (as it says in the comment at the top).
Either take the account that you want to use out of that file or use another account.

vsftp not able to login from localhost


group of order 80 is solvable

Question: How can we prove that group of order 80 is solvable without using Burnside's theorem (https://en.wikipedia.org/wiki/Burnside_theorem) ?
Answer: Since $80=2^4\cdot5$, any group of this order has either a unique Sylow $5$-subgroup or a unique Sylow $2$-subgroup (why? Count elements), so either way it has a normal Sylow subgroup, and either it has a quotient of order $2^4$ , which is a $2$-group and this solvable, or a quotient of order $5$ which is abelian and trivially solvable, so the whole group will be solvable.
Comment: i have problem with counting elements. If number of sylow 5-subgroups is 6 then there is (5-1)x6=24 elements with order 5 will come and there should be total of 80. How is possible to other 80-24=56 elements come from sylow 2-subgroups?
Comment: @Johndresden See [here for counting](https://www.quora.com/Is-there-a-proof-showing-that-any-group-with-an-order-less-than-60-is-solvable). They have explained better than I can do.
Comment: @Johndresden The number of 5-Sylow subgroup is a number s.t. it's 1 modulo $5$ and also it divides $80$. So it's either 1 or 16. If it's sixteen then we have $4\cdot 16 = 64$ different elements of order $5$. This leaves us $16$ elements for the $2$-Sylow subgroup, which can create exactly one subgroup of order 16

group of order 80 is solvable


Aplicações Back-end com o node.js

Question: Já vi algumas palestras sobre o Node.js, sua capacidade, usabilidade, mercado, etc... Porém todas essas informações ficaram muito "embaralhadas" para mim, e sempre tive um pensamento um tanto vago acerca dele.
O que sei, me corrijam se estiver errado, é que ele funciona como um server, bem semelhante ao Apache, porém feito com javascript, que roda com javascript.
Minha principal dúvida é como funciona o trabalho com aplicações Back-end com essa ferramenta. O que exatamente posso criar? Como posso criar? Onde posso criar? E como funciona a sua interação com servidores como o Wamp?
Em vários exemplos vejo códigos como este:
var http = require('http');
http.createServer(function(req,res) {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Olá mundo!');
}).listen(3000);
console.log('Servidor iniciado em localhost:3000. Ctrl+C para encerrar…');

Um Olá mundo! em node. O quão dinâmico e interativo isso pode ser?
Obs.: Back-end não é comigo, tanto que estou com dúvidas se o título da pergunta é redundante...rsrs. Então o quão mais didáticos poderem ser com essa temática, agradeço! :)
Answer:
Disclaimer*: : Acho que esta pergunta está no limite do off-topic mas como Node.js parece ser pouco usado aqui no Sopt respondo caso seja util para outros.

*:como é que se diz "disclaimer" em português?
Para mim a maior vantagem é ter JavaScript nos dois lados cliente/servidor. Assim posso usar a mesma biblioteca, objetos iguais e ter controlo melhor sobre o código.
As grandes vantagens que tenho ouvido falar no Node são o processamento assíncrono, que é muito potente pelo que tenho trabalhado.
O servidor no Node funciona só por sí. Pode ser vantajoso ter o Nginx a correr também como gerenciador de tráfego e a servir conteúdo estático da cache. Há um video interessante sobre essa possibilidade aqui (em Inglês)
Uando com o Nginx o setup pode ser assim:
upstream project {
        server localhost:3000;
}

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /usr/share/nginx/html;
        index index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                proxy_pass http://project;
        }
}

O primeiro site que está em produção com que trabalhei foi o site atual do MooTools. Algumas partes interessantes do site e que são bons exemplos para a tua pergunta:
Integração com twitter, compilação do código da framework online e envio imediato de ficheiros para o cliente, um sistema de routes muito eficiente atravéz da API da framework Express, outro exemplo onde compilamos a documentação toda da biblioteca (cerca de 500 páginas) com leitura e compilação asyncrona/paralela de ficheiros e depois fica em cache à espera de ser solicitada, e volta a recompilar em caso de mudança de ficheiros na diretoria, etc.
Node.js é uma plataforma, um interpretador de código, que possibilita usar aplicações escritas em JavaScript n lado do servidor. Na plataforma do Node pode fazer-se basicamente o mesmo que em outras plataformas, com complexidade, capacidade de processamento. O Node funciona com MySQL, MongoDB, SQLite etc etc.
Um exemplo de aplicação simples:
Existe uma framework muito usada que corre em cima do Node chamada Express. Essa framework tem um gerador de padrão de aplicação bem útil. Com alguns comandos a aplicação está a correr:
Correndo dois comandos gera-se uma aplicação:
$ npm install express-generator -g
$ express myapp

   create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.css
   create : myapp/views
   create : myapp/views/index.jade
   create : myapp/views/layout.jade
   create : myapp/views/error.jade
   create : myapp/bin
   create : myapp/bin/www

O Node.js usa o package.json que é um ficheiro JSON onde as dependências da aplicação estão guardadas, com referência a qual versão do pacote/modulo deve ser usado. Para instalar tudo de uma só vez basta fazer:
$ cd myapp
$ npm install

E para correr a aplicação é só correr:
$ npm start

Nota que npm start é o commando por norma para começar uma aplicação, mas isto implica que tal esteja defenido no package.json. Se não, ie alternativamente, pode usar-se node nomedaaplicacao e a aplicação está a correr na porta 3000, que é a porta por defeito. Abrindo o browser com o url: http://localhost:3000/ a app está a correr.
A estrutura dessa diretoria será:
.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.jade
    ├── index.jade
    └── layout.jade

Ou seja: bem simples.
Para usar outras bibliotecas basta instalar:
$ npm install --save # --save é para guardar no package.json a informação da dependência

e depois dentro do código:
var mysql = require('mysql');

Há ainda dois fatore muito interessantes. Pré-compiladores de HTML e CSS, nomeadamente os que eu uso mais frequentemente: Jade e Stylus. Estes merecem ser explicados à parte, mas são uma ferramenta essencial para a organização do código e o processo de desenvolvimento.
Comment: @SamirBraga o Node é um servidor HTTP, ele não instala mais nada como o MySQL, Nginx, etc. É possivel escolher a porta que ele "escuta" mas o resto do que chamamos "servidor" num termo geral o Node não instala.
Comment: Hoje vi várias coisas acerca do node. Pude perceber a coerência de sua resposta @Sergio. Quero me aprofundar mais nisso... :)
Comment: Sergio, uma dúvida, o `localhost` é o que estalamos com o `wamp`, por exemplo, ou ele instala? Por exemplo, caso eu não tenha um server instalado, ou seja, não possuo localhost, ao seguir esses passos, o node.js cria um?

Aplicações Back-end com o node.js


difference between linear, semilinear and quasilinear PDE's

Question: I know a PDE is linear when the dependent variable $u$ and its derivatives appear only to the first power.  So, $u_t + u_x +5u = 1$ would be linear.
However, I do not quite understand the other two.
My professor described

"semilinear" PDE's as PDE's whose highest order terms are linear, and

"quasilinear" PDE's as PDE's whose highest order terms appear only as individual terms multiplied by lower order terms.

No examples were provided; only equivalent statements involving sums and multiindices were shown, which I do not think I could decipher by tomorrow.
Can someone provide some examples of "semilinear" and "quasilinear" PDE's?
Comment: Another good reference book is from the book of Zachmanoglou"introduction to PDE with applications"
Comment: You can find a formal definition in 'Partial Differential Equations': Second Edition written by Evans. It is on the second page of chapter 1.
Answer: I think this will help you to understand the PDE $:$
Linear PDE: $a(x,y)u_x+b(x,y)u_y+c(x,y)u=f(x,y)$
Semi-linear PDE: $a(x,y)u_x+b(x,y)u_y=f(x,y,u)$
Quasi-linear PDE: $a(x,y,u)u_x+b(x,y,u)u_y=f(x,y,u)$
Comment: could you please give a similar explanation for the case of second order pde ?
Comment: @MatheMagic thanks for your answer.I have one query.You consider first order PDEs in your answer,can I know how coefficients will change if it is of second order means suppose in case of quasi-linear $u_{xx}$ is present then coefficient will remain a(x,y,u) or will get modify?
Answer: Using Einstein convention for summation and omitting dependence on $x$ of $u$ and its derivatives,

linear: $a^{ij}(x)D_{ij}u+b^i(x)D_iu+c(x)u+d(x)=0$
semi-linear: $a^{ij}(x)D_{ij}u+b(x,u,Du)=0$
quasi-linear: $a^{ij}(x,u,Du)D_{ij}u+b(x,u,Du)=0$.
Answer: I hope these examples will help you.
Semilinear/Almost Linear PDE:
1) $a(x,y)u_x+b(x,y)u_y+c(x,y,u)=0$
2) $U_{tt}-U_{xx}+U^3=0$
Quasi Linear PDE:
1) $a(x,y,u)u_x+b(x,y,u)u_y-c(x,y,u)=0$
2) $U_x+UV_y=0$
3) $U_{tt}-UU_{xx}+U^3=0$
4) $U_{tt}-UU_{xx}+U=0$
5) Navier Stokes equation is also Quasi Linear Equation
Comment: (Just because the question has a lot of views) I am fairly sure that Navier Stokes is considered as being semilinear (see e.g. the definition in Evan's book, second page of the first chapter).
Answer: Linear. The degree for the unknown function is one through out. And no functions of the Unknown function.
Semilinear. The derivatives are linear but the unknown function is not likear.
Quasilinear. Derivatives of the order are not linear. Once the whole eqn is not linear then it becomes non linear.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Is there a word to differentiate a measure in each hand?

Question: Say I have a piano partition, with 1 measure/bar. How can I call the right hand staff measure and the left hand staff measure ? Is there a word to make the distinction between the two hands measure together and each one individually ?
I'm not being pedantic here :p I need to know for a personal project and I'd prefer having the right term than just "right hand measure".
Answer: Upper stave/Lower stave.  Treble stave/Bass stave.
Comment: Yes, indeed you may call them upper stave and lower stave. Treble stave and bass stave will often do, but won't do where the two staves use the same clef.


DOM changes not executing immediately

Question: So I have a hidden element, I want to show it and then trigger an alert right after.
I tried using jquery:
$('#myElement').show();
alert('test');

I also tried using just regular javascript:
document.getElementById('myElement').setStyle('display: block');
alert('test');

However in both cases I see that when I run this, the alert appears, my element is still not visible, and then once I close the alert then the element begins to show.
Why is the alert being run before the DOM is updated? Do I have any way to force a DOM update or do i need to add a manual timeout after I show the element?
I have tried playing around with $.then() and $.done() but neither seems to work.
Comment: Do **not** use `alert()` for debugging. You get into exactly this kind of situation where the solution isn't "how do I make the update before `alert`" but to just use `console.log` or even an actual debugger. `alert` blocks the UI thread, so the event loop will not finish, thus you don't get the updated page representation.
Comment: Okay. I don't know the whole story, but let me guess: do you wait until the page is ready (jQuery event) or some other event that guaranties that the page is loaded. If not than this could be an issue.
Comment: Potential duplicate of https://stackoverflow.com/questions/30188845/jquery-hide-and-show-not-immediately-run-when-reversed-later-in-the-function
Answer: Browser repaints triggered by JS run on the main JavaScript event loop.
The DOM is updating, but the rendering of it isn't done until JS isn't busy with something else.
The alert() is blocking, so all JS on the main event loop is paused until it is dismissed.
You could wait for an animation frame before running your alert.
document.getElementById('myElement').setStyle('display: block');
requestAnimationFrame(() => alert('test');)

Comment: I always forget `requestAnimationFrame()` :)
Answer: This is because alert() is a modal operation which blocks the UI thread of the browser from updating. In the code above, when you call alert() the DOM is still in the process of being updated, but has not yet finished being redrawn, yet the thread has been blocked from completing until the user dismisses the alert().
You have three solutions. Firstly you could put the alert() in a timeout to delay it:
$('#myElement').show();
setTimeout(function(){
  alert('test');
}, 20); // 20ms should be a long enough delay even on the slowest machines

Secondly, you could use a library to display non-modal alerts within the DOM itself, ie. Notify.
Lastly, assuming your purpose is just for testing/debuggin, you can use console.log() as it does not a modal operation:
$('#myElement').show();
console.log('test');

To see the console, press F12 in your browser. Note that this method, along with console.dir(), should always be used for debugging, not alert().
Answer: If you're using jQuery, then you can add an callback after show() is executed.
Link for document: http://api.jquery.com/show/
$('#myElement').show(400, function() {
   alert('test')
})

Comment: Downvote isn't mine, but note that this is not the same logic as the OP originally had. By providing a duration to `show()` you're creating an animation (a fade effect by default).

DOM changes not executing immediately