问:
Recursive linq results returning duplicates
This question builds off of one I asked last week: Recursive linq to get infinite children.  The answer given in that post produced what I needed; a distinct list of Locations and their children based on a parent.  We needed to use our own model for Locations, so we created one, and since then, I've been getting duplicate results.  Our model is very basic:

```<code>class LocationModel
{
    public int LocationID { get; set; }
    public int ParentLocationID { get; set; }
    public string LocationName { get; set;}
}
</code>```

If you compare it to the entity created by EF, I just cut out all the fields we don't need/use (see link above).  So I modified my linq statements to use this new model instead:

```<code>DBEntities db = new DBEntities();

public IEnumerable<LocationModel> GetAllChildLocations(int parentId)
{
    var locations = (from l in db.Locations
                        where l.ParentLocationID == parentId ||
                        l.LocationID == parentId
                        select new LocationModel()
                        {
                            LocationID = l.LocationID,
                            ParentLocationID = l.ParentLocationID,
                            LocationName = l.LocationName
                        }).ToList();

    var children = locations.AsEnumerable()
                            .Union(db.Locations.AsEnumerable()
                            .Where(x => x.ParentLocationID == parentId)
                            .SelectMany(y => GetAllChildLocations(y.LocationID)))
                            .ToList();
    return children.OrderBy(l => l.LocationName);
}
</code>```

When I run it, either in Visual Studio or in LinqPad, I now get duplicates.  Here's the original code that does not produce duplicates:

```<code>public IEnumerable<Location> GetAllChildLocations(int parentId)
{
    var locations = (from l in db.Locations
                        where l.ParentLocationID == parentId ||
                        l.LocationID == parentId
                        select l).ToList();

    var child = locations.AsEnumerable()
                        .Union(db.Locations.AsEnumerable()
                        .Where(x => x.ParentLocationID == parentId)
                        .SelectMany(y => GetAllChildLocations(y.LocationID)))
                        .ToList();
    return child;
}
</code>```

Why is it producing duplicates when I use my own model vs. the generated one from EF?  Does it have to do with the auto-generating fields that the EF model has and mine doesn't?

答:
Why is it producing duplicates when I use my own model vs. the generated one from EF?

Because you are using Enumerable.Union method which by default uses reference equality. EF DbContext change tracker keeps internally (tracks) the already loaded entity object instances with the same PK (even if you retrieve them via separate database queries), hence the reference equality works. Which cannot be said for the new LocationModel instances created by the query select operators.

One way to resolve it is to implement GetHashCode and Equals in your LocationModel class. But in general I don't like the implementation of the recursive children retrieval and the usage of Union - there must be a better way, but this is outside the scope of this question (but for the linked).

The root of the evil for me is the following condition

```<code>where l.ParentLocationID == parentId || l.LocationID == parentId
</code>```

which selects both the item and its children, leading to duplicates in the result set, which then are supposed to be eliminated by the Union method. The good implementation will not generate duplicates at all.

Body:
This question builds off of one I asked last week: Recursive linq to get infinite children.  The answer given in that post produced what I needed; a distinct list of Locations and their children based on a parent.  We needed to use our own model for Locations, so we created one, and since then, I've been getting duplicate results.  Our model is very basic:

class LocationModel
{
    public int LocationID { get; set; }
    public int ParentLocationID { get; set; }
    public string LocationName { get; set;}
}

If you compare it to the entity created by EF, I just cut out all the fields we don't need/use (see link above).  So I modified my linq statements to use this new model instead:

DBEntities db = new DBEntities();

public IEnumerable<LocationModel> GetAllChildLocations(int parentId)
{
    var locations = (from l in db.Locations
                        where l.ParentLocationID == parentId ||
                        l.LocationID == parentId
                        select new LocationModel()
                        {
                            LocationID = l.LocationID,
                            ParentLocationID = l.ParentLocationID,
                            LocationName = l.LocationName
                        }).ToList();

    var children = locations.AsEnumerable()
                            .Union(db.Locations.AsEnumerable()
                            .Where(x => x.ParentLocationID == parentId)
                            .SelectMany(y => GetAllChildLocations(y.LocationID)))
                            .ToList();
    return children.OrderBy(l => l.LocationName);
}

When I run it, either in Visual Studio or in LinqPad, I now get duplicates.  Here's the original code that does not produce duplicates:

public IEnumerable<Location> GetAllChildLocations(int parentId)
{
    var locations = (from l in db.Locations
                        where l.ParentLocationID == parentId ||
                        l.LocationID == parentId
                        select l).ToList();

    var child = locations.AsEnumerable()
                        .Union(db.Locations.AsEnumerable()
                        .Where(x => x.ParentLocationID == parentId)
                        .SelectMany(y => GetAllChildLocations(y.LocationID)))
                        .ToList();
    return child;
}

Why is it producing duplicates when I use my own model vs. the generated one from EF?  Does it have to do with the auto-generating fields that the EF model has and mine doesn't?

Body:
Why is it producing duplicates when I use my own model vs. the generated one from EF?

Because you are using Enumerable.Union method which by default uses reference equality. EF DbContext change tracker keeps internally (tracks) the already loaded entity object instances with the same PK (even if you retrieve them via separate database queries), hence the reference equality works. Which cannot be said for the new LocationModel instances created by the query select operators.

One way to resolve it is to implement GetHashCode and Equals in your LocationModel class. But in general I don't like the implementation of the recursive children retrieval and the usage of Union - there must be a better way, but this is outside the scope of this question (but for the linked).

The root of the evil for me is the following condition

where l.ParentLocationID == parentId || l.LocationID == parentId

which selects both the item and its children, leading to duplicates in the result set, which then are supposed to be eliminated by the Union method. The good implementation will not generate duplicates at all.


来源: stackexchange

问:
How to get values on JSON result
I have one url that give the output below in JSON:

```<code>{
    "categorias": [
        {
            "id_categoria": 1,
            "nom_categoria": "Graduação"
        },
        {
            "id_categoria": 2,
            "nom_categoria": "Pós-Graduação"
        },
        {
            "id_categoria": 3,
            "nom_categoria": "Disciplinas"
        }
    ]
}
</code>```

How I can extract only the values "Graduação","Pós-Graduação","Disciplinas" using Jquery?

答:
use map function

```<code>var categoriesName = yourJsonResponse.categorias.map(function(category) {
    return category.nom_categoria;
});
</code>```

if it is a string (not an object), you will need to parse it first. You can do it by using JSON.parse() function

ContentLicense: CC BY-SA 3.0

Title: How to get values on JSON result

Body:
I have one url that give the output below in JSON:

{
    "categorias": [
        {
            "id_categoria": 1,
            "nom_categoria": "Graduação"
        },
        {
            "id_categoria": 2,
            "nom_categoria": "Pós-Graduação"
        },
        {
            "id_categoria": 3,
            "nom_categoria": "Disciplinas"
        }
    ]
}

How I can extract only the values "Graduação","Pós-Graduação","Disciplinas" using Jquery?

Body:
use map function

var categoriesName = yourJsonResponse.categorias.map(function(category) {
    return category.nom_categoria;
});

if it is a string (not an object), you will need to parse it first. You can do it by using JSON.parse() function


问:
Redundant Keys in MySQL
Currently working on a MySQL database which has key declarations such as

```<code>KEY 'id' (id),
KEY 'username' (username),
KEY 'user_id' (username, id)
</code>```

Does this affect how our data works in anyway? Would eliminating this improve our database's efficiency? I concluded they were redundant but I am curious if the person who came before me created these for any reason.

答:
There's a good write up about this in the MySQL documentation:

MySQL allows its users to create several indexes that might be the
  same (duplicate indexes) or partially similar (redundant indexes) in
  its structure. Although duplicate indexes have no advantages, there
  are some cases where redundant indexes might be helpful. However, both
  have disadvantages. Duplicate and redundant indexes slow down update
  and insert operations. As a result it is usually a good idea to find
  and remove them.

Title: Redundant Keys in MySQL

Body:
Currently working on a MySQL database which has key declarations such as

KEY 'id' (id),
KEY 'username' (username),
KEY 'user_id' (username, id)

Does this affect how our data works in anyway? Would eliminating this improve our database's efficiency? I concluded they were redundant but I am curious if the person who came before me created these for any reason.


问:
Change the font color of weekend dates in jquery datepicker
Is it possible to change the font color of dates that fall on the weekends in jquery calendar? I try to use the class ui-datepicker-week-end but it only change the font color of Sun and Sat. What I want is to also change the color of days that falls on sun and sat.</p>

答:
You need a bit more specificity in your selector, since ui-datepicker-week-end is on the , but there's an  with ui-state-default inside, like this:

```<code>.ui-datepicker-week-end, .ui-datepicker-week-end a.ui-state-default {color:red;}
</code>```

You can test it here.  If you're curious, the markup for day cell is like this:

```<code><td class="ui-datepicker-week-end">
  <a class="ui-state-default" href="#">DAY NUMBER</a>
</td>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You need a bit more specificity in your selector, since ui-datepicker-week-end is on the <td>, but there's an <a> with ui-state-default inside, like this:

.ui-datepicker-week-end, .ui-datepicker-week-end a.ui-state-default {color:red;}

You can test it here.  If you're curious, the markup for day cell is like this:

<td class="ui-datepicker-week-end">
  <a class="ui-state-default" href="#">DAY NUMBER</a>
</td>


问:
Need to parse the output of linux command
I have the output of the linux command as below:

```<code>/auto/qalogs/branch_team_5.7/drt/hash_list/bk20170401/audit-gc.rb:11:{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>10800, :skipcheckconnection=>1, :minlimitver=>"5.3.0.0"}
/auto/qalogs/branch_team_5.7/drt/hash_list/bk20170401/encryption-audit-gc-part1.rb:11:#{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>10800, :skipcheckconnection=>1, :minlimitver=>"5.3.0.0"}
Binary file /auto/qalogs/branch_team_5.7/ert/hash_list/.encryption-audit-gc.rb.swp matches
/auto/qalogs/branch_team_5.7/ert/hash_list/encryption-audit-gc.rb:11:{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>7200, :skipcheckconnection=>1, :minlimitver=>"5.3.0.0"}
</code>```

I need to only filter this hash file :

```<code>{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>7200, :skipcheckconnection=>1, :minlimitver=>"5.3.0.0"}
</code>```

and write to another file.

I tried the followng:

```<code>out=subprocess.getoutput('grep -rwn
/auto/qalogs/branch_team_5.7/ert/hash_list/ -e '+alist[0]+'')
print ("output of grep  is", out)
pattern=re.compile(r'(/auto/qalogs/branch_team_5.7/ert/hash_list/.*.rb:\d)
(\:)(\{.*\})',out)
print (pattern.groupobject(0))
</code>```

I get this exception.How to do it?

答:
This should be a simple re problem.

```<code>import re

command = 'grep -rwn /auto/qalogs/branch_team_5.7/ert/hash_list/ -e ' + alist[0] + ''
filter  = '/auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb'

log = subprocess.subprocess.getoutput(command)

with open('output.txt', 'w+') as f:
    for message in log:
        if re.search(filter, message):
            f.write(result)
</code>```

Unfortunetly, I don't have more sample data to really vet it!

Body:
I have the output of the linux command as below:

/auto/qalogs/branch_team_5.7/drt/hash_list/bk20170401/audit-gc.rb:11:{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>10800, :skipcheckconnection=>1, :minlimitver=>"5.3.0.0"}
/auto/qalogs/branch_team_5.7/drt/hash_list/bk20170401/encryption-audit-gc-part1.rb:11:#{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>10800, :skipcheckconnection=>1, :minlimitver=>"5.3.0.0"}
Binary file /auto/qalogs/branch_team_5.7/ert/hash_list/.encryption-audit-gc.rb.swp matches
/auto/qalogs/branch_team_5.7/ert/hash_list/encryption-audit-gc.rb:11:{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>7200, :skipcheckconnection=>1, :minlimitver=>"5.3.0.0"}

I need to only filter this hash file :

{:component=>"Encryption", :params=>"-f /auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb log_level=debug", :script=>"encryption/destroy.rb", :timeout=>7200, :skipcheckconnection=>1, :minlimitver=>"5.3.0.0"}

and write to another file.

I tried the followng:

out=subprocess.getoutput('grep -rwn
/auto/qalogs/branch_team_5.7/ert/hash_list/ -e '+alist[0]+'')
print ("output of grep  is", out)
pattern=re.compile(r'(/auto/qalogs/branch_team_5.7/ert/hash_list/.*.rb:\d)
(\:)(\{.*\})',out)
print (pattern.groupobject(0))

I get this exception.How to do it?

Body:
This should be a simple re problem.

import re

command = 'grep -rwn /auto/qalogs/branch_team_5.7/ert/hash_list/ -e ' + alist[0] + ''
filter  = '/auto/qalogs/branch_team/drt/hash_list/enc_options_rkm_ekm.rb'

log = subprocess.subprocess.getoutput(command)

with open('output.txt', 'w+') as f:
    for message in log:
        if re.search(filter, message):
            f.write(result)

Unfortunetly, I don't have more sample data to really vet it!


问:
Remove rows with the same value across all columns
Suppose I have a data frame (df) that looks like below:

```<code>options(stringsAsFactors = F)

cars <- c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6", "Car7", "Car8", "Car9")
test1 <- c(0,0,3,1,4,2,1,3,0)
test2 <- c(0,0,2,1,0,2,2,5,0)
test3 <- c(1,0,5,1,2,2,6,7,0)
test4 <- c(2,NA,2,1,2,2,1,1,0)
test5 <- c(0,0,1,1,0,2,1,3,0)
test6 <- c(1,0,1,1,1,2,3,4,0)
test7 <- c(3,0,2,1,0,2,1,1,0)

df <- data.frame(cars,test1,test2,test3,test4,test5,test6,test7)

#df
   cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#2 Car2     0     0     0    NA     0     0     0
#3 Car3     3     2     5     2     1     1     2
#4 Car4     1     1     1     1     1     1     1
#5 Car5     4     0     2     2     0     1     0
#6 Car6     2     2     2     2     2     2     2
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1
#9 Car9     0     0     0     0     0     0     0
</code>```

I want to remove any rows that have the same value throughout the entire row (in the example above, I would like to keep rows 1, 3, 5, 7, 8 and remove the rest).

I've figured out how to remove all rows that have zeros

```<code> df$sum <- rowSums(df[,c(2:8)], na.rm = T )
 df.all0 <- df[which(df$sum == 0),]
</code>```

However, this doesn't necessarily work for all the other rows.  Unlike other questions, this question asks to look for duplicates across the entire row, not just specific columns.

Any help would be greatly appreciated!

答:
Here is an option with rowSums; the logic is to check if there is any value in the row that is different (NA doesn't count) from one of the columns that you are interested in:

```<code>df[rowSums(df[-1] != df[[2]], na.rm = TRUE) != 0,]

#  cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#3 Car3     3     2     5     2     1     1     2
#5 Car5     4     0     2     2     0     1     0
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1
</code>```

Body:
Suppose I have a data frame (df) that looks like below:

options(stringsAsFactors = F)

cars <- c("Car1", "Car2", "Car3", "Car4", "Car5", "Car6", "Car7", "Car8", "Car9")
test1 <- c(0,0,3,1,4,2,1,3,0)
test2 <- c(0,0,2,1,0,2,2,5,0)
test3 <- c(1,0,5,1,2,2,6,7,0)
test4 <- c(2,NA,2,1,2,2,1,1,0)
test5 <- c(0,0,1,1,0,2,1,3,0)
test6 <- c(1,0,1,1,1,2,3,4,0)
test7 <- c(3,0,2,1,0,2,1,1,0)

df <- data.frame(cars,test1,test2,test3,test4,test5,test6,test7)

#df
   cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#2 Car2     0     0     0    NA     0     0     0
#3 Car3     3     2     5     2     1     1     2
#4 Car4     1     1     1     1     1     1     1
#5 Car5     4     0     2     2     0     1     0
#6 Car6     2     2     2     2     2     2     2
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1
#9 Car9     0     0     0     0     0     0     0

I want to remove any rows that have the same value throughout the entire row (in the example above, I would like to keep rows 1, 3, 5, 7, 8 and remove the rest).

I've figured out how to remove all rows that have zeros

 df$sum <- rowSums(df[,c(2:8)], na.rm = T )
 df.all0 <- df[which(df$sum == 0),]

However, this doesn't necessarily work for all the other rows.  Unlike other questions, this question asks to look for duplicates across the entire row, not just specific columns.

Any help would be greatly appreciated!

Body:
Here is an option with rowSums; the logic is to check if there is any value in the row that is different (NA doesn't count) from one of the columns that you are interested in:

df[rowSums(df[-1] != df[[2]], na.rm = TRUE) != 0,]

#  cars test1 test2 test3 test4 test5 test6 test7
#1 Car1     0     0     1     2     0     1     3
#3 Car3     3     2     5     2     1     1     2
#5 Car5     4     0     2     2     0     1     0
#7 Car7     1     2     6     1     1     3     1
#8 Car8     3     5     7     1     3     4     1


问:
Backpropagation algorithm in neural network
I have some troubles implementing backpropagation in neural network. This implementation is using ideas from slides of Andrew Ng's course on machine learning from Coursera (here is the link https://www.coursera.org/course/ml). I think that I have understood the algorithm, but there is some subtle error in the code.

I'm using a network with 1 input layer, 1 hidden layer and 1 output layer. They have 2 + 1, 2 + 1, 1 neurons respectively (+1 is for bias).
When I tried to implement logical AND and logical OR everything worked great, and network learned to give correct values. But then I tried to implement XNOR (a XNOR b = NOT (a XOR b)).

I used 4 examples:

0 0 1

0 1 0

1 0 0

1 1 1

But suddenly, on this function gradient doesn't go anywhere. In the beginning I initialize weights with random small numbers (from -0.01 to 0.01). The output is near 0.5. Then I am doing gradient descent. Output is still always near 0.5 on any input.

I want to know how to fix this problem.

Here's the code:

```<code>#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

// contains matrix and Vector classes.
// Vector is just like std::valarray, but is compatible with my matrix.
#include "matrix.hpp"

size_t L;
std::vector< Vector<double> > layers;
std::vector< matrix<double> > theta;

struct Example
{
    Vector<double> x;
    Vector<double> y;
};

using TrainingSet = std::vector<Example>;

TrainingSet examples;

double g(double x)
{
    return 1 / (1 + exp(-x));
}

void forwardPropagate(Vector<double> x)
{
    for ( size_t i = 1; i < layers[0].size(); ++i )
        layers[0][i] = x[i - 1];

    for ( size_t i = 0; i < L - 1; ++i )
    {
        auto z = theta[i] * layers[i];
        for ( size_t j = 1; j < layers[i + 1].size(); ++j )
            layers[i + 1][j] = g(z[j - 1]);
    }
}

void backwardPropagate(Vector<double> y, std::vector< matrix<double> >& delta)
{
    auto err = layers.back().slice(1) - y;

    for ( int i = L - 2; i >= 0; --i )
    {
        delta[i] += asMatrix(err) * asMatrix(layers[i]).transpose();

        auto gdz = layers[i] * (Vector<double>(layers[i].size(), 1.0) - layers[i]);
        auto tmp = theta[i].transpose() * err * gdz;
        err = tmp.slice(1);
    }
}

double costFunction(const TrainingSet& examples)
{
    double result = 0.0;

    for ( const auto& example : examples )
    {
        std::cout << layers.back()[1] << '\n';

        forwardPropagate(example.x);
        for ( size_t k = 1; k < layers.back().size(); ++k )
        {
            auto h = layers.back()[k];
            auto y = example.y[k - 1];
            result += y * log(h) + (1 - y) * log(1 - h);
        }
    }

    return (-result) / examples.size();
}

void computeGradient(std::vector< matrix<double> >& delta, const TrainingSet& examples)
{
    for ( auto& m : delta )
        m.fillWith(0);

    for ( auto example : examples )
    {
        forwardPropagate(example.x);
        backwardPropagate(example.y, delta);
    }

    for ( auto& m : delta )
        m /= examples.size();
}

void gradientDescentStep(const std::vector< matrix<double> >& gradient)
{
    const double alpha = 0.01;

    for ( size_t i = 0; i < L - 1; ++i )
        theta[i] -= alpha / examples.size() * gradient[i];
}

double gradientDescent(const TrainingSet& examples)
{
    const double eps = 0.0000001;

    double prev, cur;
    cur = costFunction(examples);

    size_t iterations = 0;
    const size_t max_iterations = 200000000;

    std::vector< matrix<double> > delta;
    delta.reserve(L - 1);
    for ( size_t i = 0; i < L - 1; ++i )
        delta.emplace_back(theta[i].rows(), theta[i].cols());

    do
    {
        prev = cur;
        computeGradient(delta, examples);
        gradientDescentStep(delta);
        cur = costFunction(examples);

    } while ( fabs(cur - prev) >= eps && iterations++ < max_iterations );

    std::cout << "Made " << iterations << " iterations\n";

    return cur;
}

int main()
{
    std::ifstream fin("input.txt");
    std::istream& in = fin;

    std::cout.sync_with_stdio(false);

    in >> L;
    std::vector<size_t> architecture(L);

    for ( size_t i = 0; i < L; ++i )
        in >> architecture[i];

    layers.reserve(L);
    for ( size_t i = 0; i < L; ++i )
    {
        layers.emplace_back(1 + architecture[i]);
        layers.back()[0] = 1;
    }

    const double eps = 0.01;

    theta.reserve(L - 1);
    for ( size_t i = 0; i < L - 1; ++i )
    {
        theta.emplace_back(layers[i + 1].size() - 1, layers[i].size());
        theta[i].randomInitialize(eps);
    }

    size_t number_of_examples;
    in >> number_of_examples;

    examples.reserve(number_of_examples);
    for ( size_t i = 0; i < number_of_examples; ++i )
    {
        auto x = Vector<double>(architecture.front());
        auto y = Vector<double>(architecture.back());

        for ( size_t j = 0; j < architecture.front(); ++j )
            in >> x[j];

        for ( size_t j = 0; j < architecture.back(); ++j )
            in >> y[j];

        examples.emplace_back(Example{x, y});
    }

    for ( auto example : examples )
    {
        forwardPropagate(example.x);
        std::cout << layers.back()[1] << '\n';
    }

    for ( size_t i = 0; i < theta.size(); ++i )
        std::cout << "θ[" << i << "] = " << theta[i];

    gradientDescent(examples);

    for ( size_t i = 0; i < theta.size(); ++i )
        std::cout << "θ[" << i << "] = " << theta[i];

    std::cout << "\n\n\n";

    for ( auto example : examples )
    {
        forwardPropagate(example.x);
        std::cout << layers.back()[1] << '\n';
    }

    return 0;
}
</code>```

答:
Generally for random initialization weights are in the range of ~[-3, 3]. The initial greater amounts of error (by having a larger weights) helps "jump" the weights into converging to the proper areas. Yes the XOR problem has local minima but your network should easily be able to converge to the proper answer with only a few hidden nodes.

You shouldn't "need" to take steps out of local minima, it should easily converge to the correct optima. XOR problem with the network structure being [2,2,1] has such a small amount of weights that you could essentially "random initialization" your weights to the correct optima relatively quickly. (Because the search space is small)

note / edit  if your network only has 2 hidden nodes there is a good change it will get stuck at local minima. a network even the size of ~[2,7,1] should be able to converge without the random steps.

Body:
I have some troubles implementing backpropagation in neural network. This implementation is using ideas from slides of Andrew Ng's course on machine learning from Coursera (here is the link https://www.coursera.org/course/ml). I think that I have understood the algorithm, but there is some subtle error in the code.

I'm using a network with 1 input layer, 1 hidden layer and 1 output layer. They have 2 + 1, 2 + 1, 1 neurons respectively (+1 is for bias).
When I tried to implement logical AND and logical OR everything worked great, and network learned to give correct values. But then I tried to implement XNOR (a XNOR b = NOT (a XOR b)).

I used 4 examples:

0 0 1

0 1 0

1 0 0

1 1 1

But suddenly, on this function gradient doesn't go anywhere. In the beginning I initialize weights with random small numbers (from -0.01 to 0.01). The output is near 0.5. Then I am doing gradient descent. Output is still always near 0.5 on any input.

I want to know how to fix this problem.

Here's the code:

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

// contains matrix and Vector classes.
// Vector is just like std::valarray, but is compatible with my matrix.
#include "matrix.hpp"

size_t L;
std::vector< Vector<double> > layers;
std::vector< matrix<double> > theta;

struct Example
{
    Vector<double> x;
    Vector<double> y;
};

using TrainingSet = std::vector<Example>;

TrainingSet examples;

double g(double x)
{
    return 1 / (1 + exp(-x));
}

void forwardPropagate(Vector<double> x)
{
    for ( size_t i = 1; i < layers[0].size(); ++i )
        layers[0][i] = x[i - 1];

    for ( size_t i = 0; i < L - 1; ++i )
    {
        auto z = theta[i] * layers[i];
        for ( size_t j = 1; j < layers[i + 1].size(); ++j )
            layers[i + 1][j] = g(z[j - 1]);
    }
}

void backwardPropagate(Vector<double> y, std::vector< matrix<double> >& delta)
{
    auto err = layers.back().slice(1) - y;

    for ( int i = L - 2; i >= 0; --i )
    {
        delta[i] += asMatrix(err) * asMatrix(layers[i]).transpose();

        auto gdz = layers[i] * (Vector<double>(layers[i].size(), 1.0) - layers[i]);
        auto tmp = theta[i].transpose() * err * gdz;
        err = tmp.slice(1);
    }
}

double costFunction(const TrainingSet& examples)
{
    double result = 0.0;

    for ( const auto& example : examples )
    {
        std::cout << layers.back()[1] << '\n';

        forwardPropagate(example.x);
        for ( size_t k = 1; k < layers.back().size(); ++k )
        {
            auto h = layers.back()[k];
            auto y = example.y[k - 1];
            result += y * log(h) + (1 - y) * log(1 - h);
        }
    }

    return (-result) / examples.size();
}

void computeGradient(std::vector< matrix<double> >& delta, const TrainingSet& examples)
{
    for ( auto& m : delta )
        m.fillWith(0);

    for ( auto example : examples )
    {
        forwardPropagate(example.x);
        backwardPropagate(example.y, delta);
    }

    for ( auto& m : delta )
        m /= examples.size();
}

void gradientDescentStep(const std::vector< matrix<double> >& gradient)
{
    const double alpha = 0.01;

    for ( size_t i = 0; i < L - 1; ++i )
        theta[i] -= alpha / examples.size() * gradient[i];
}

double gradientDescent(const TrainingSet& examples)
{
    const double eps = 0.0000001;

    double prev, cur;
    cur = costFunction(examples);

    size_t iterations = 0;
    const size_t max_iterations = 200000000;

    std::vector< matrix<double> > delta;
    delta.reserve(L - 1);
    for ( size_t i = 0; i < L - 1; ++i )
        delta.emplace_back(theta[i].rows(), theta[i].cols());

    do
    {
        prev = cur;
        computeGradient(delta, examples);
        gradientDescentStep(delta);
        cur = costFunction(examples);

    } while ( fabs(cur - prev) >= eps && iterations++ < max_iterations );

    std::cout << "Made " << iterations << " iterations\n";

    return cur;
}

int main()
{
    std::ifstream fin("input.txt");
    std::istream& in = fin;

    std::cout.sync_with_stdio(false);

    in >> L;
    std::vector<size_t> architecture(L);

    for ( size_t i = 0; i < L; ++i )
        in >> architecture[i];

    layers.reserve(L);
    for ( size_t i = 0; i < L; ++i )
    {
        layers.emplace_back(1 + architecture[i]);
        layers.back()[0] = 1;
    }

    const double eps = 0.01;

    theta.reserve(L - 1);
    for ( size_t i = 0; i < L - 1; ++i )
    {
        theta.emplace_back(layers[i + 1].size() - 1, layers[i].size());
        theta[i].randomInitialize(eps);
    }

    size_t number_of_examples;
    in >> number_of_examples;

    examples.reserve(number_of_examples);
    for ( size_t i = 0; i < number_of_examples; ++i )
    {
        auto x = Vector<double>(architecture.front());
        auto y = Vector<double>(architecture.back());

        for ( size_t j = 0; j < architecture.front(); ++j )
            in >> x[j];

        for ( size_t j = 0; j < architecture.back(); ++j )
            in >> y[j];

        examples.emplace_back(Example{x, y});
    }

    for ( auto example : examples )
    {
        forwardPropagate(example.x);
        std::cout << layers.back()[1] << '\n';
    }

    for ( size_t i = 0; i < theta.size(); ++i )
        std::cout << "θ[" << i << "] = " << theta[i];

    gradientDescent(examples);

    for ( size_t i = 0; i < theta.size(); ++i )
        std::cout << "θ[" << i << "] = " << theta[i];

    std::cout << "\n\n\n";

    for ( auto example : examples )
    {
        forwardPropagate(example.x);
        std::cout << layers.back()[1] << '\n';
    }

    return 0;
}


问:
Getting the text out of a multi-line CEdit control?
There has to be a better way to get the text from a multi-line CEdit control rather than using GetLineCount() then looping through all the lines and a appending the GetLine(i) to the end of an accumulator string. Is there a better way than this?

答: Use CWindow::GetWindowText() and CWindow::GetWindowTextLength()


问:
Excel VBA Looping a continuous copy/paste with delay
I already have code below which successfully copy and pastes one row on Sheet1 to the next open row on Sheet2.  The data on this row is imported from an external application and updates constantly, thereby creating a history writer.  I have attempted several methods to loop this action with a delay and have failed.

GOAL: Loop this code with .25 second delay with the option to exit the loop with a button click or key-press.  The delay is more important than the exit condition as I can just Esc if need be.

```<code>Private Sub START_Click()

    Application.ScreenUpdating = False
    Dim copySheet As Worksheet
    Dim pasteSheet As Worksheet

    Set copySheet = Worksheets("Sheet1")
    Set pasteSheet = Worksheets("Sheet2")

    copySheet.Range("A23:L23").Copy
    pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub
</code>```

答:
Use the Start_Click event to run another procedure, with a module-level variable that flags whether user has requested to Stop the procedure. You'll need to use WinAPI Sleep function with a 250ms delay because Application.OnTime (which is commonly used to schedule a procedure to run at a future time) will not work with fractions of seconds. You will not be able to really "interact" with Excel while this procedure is running:

```<code>Option Explicit
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Dim bRunContinuously As Boolean
Private Sub START_Click()
    bRunContinuously = True
    While bRunContinuously
        Call Do_Stuff
        Sleep 250
        DoEvents
    Wend
End Sub
Private Sub STOP_Click()
    bRunContinuously = False
    Debug.Print "Stopped!"
End Sub

Sub Do_Stuff()
    Dim dest As Range
    Application.ScreenUpdating = False
    Dim copySheet As Worksheet
    Dim pasteSheet As Worksheet

    Set copySheet = Worksheets("Sheet1")
    Set pasteSheet = Worksheets("Sheet2")
    Set dest =  pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
    With copySheet.Range("A23:L23")
       dest.Resize(.Rows.Count, .Columns.Count).Value = .Value
    End With
    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub
</code>```

Body:
I already have code below which successfully copy and pastes one row on Sheet1 to the next open row on Sheet2.  The data on this row is imported from an external application and updates constantly, thereby creating a history writer.  I have attempted several methods to loop this action with a delay and have failed.

GOAL: Loop this code with .25 second delay with the option to exit the loop with a button click or key-press.  The delay is more important than the exit condition as I can just Esc if need be.

Private Sub START_Click()

    Application.ScreenUpdating = False
    Dim copySheet As Worksheet
    Dim pasteSheet As Worksheet

    Set copySheet = Worksheets("Sheet1")
    Set pasteSheet = Worksheets("Sheet2")

    copySheet.Range("A23:L23").Copy
    pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub

Body:
Use the Start_Click event to run another procedure, with a module-level variable that flags whether user has requested to Stop the procedure. You'll need to use WinAPI Sleep function with a 250ms delay because Application.OnTime (which is commonly used to schedule a procedure to run at a future time) will not work with fractions of seconds. You will not be able to really "interact" with Excel while this procedure is running:

Option Explicit
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Dim bRunContinuously As Boolean
Private Sub START_Click()
    bRunContinuously = True
    While bRunContinuously
        Call Do_Stuff
        Sleep 250
        DoEvents
    Wend
End Sub
Private Sub STOP_Click()
    bRunContinuously = False
    Debug.Print "Stopped!"
End Sub

Sub Do_Stuff()
    Dim dest As Range
    Application.ScreenUpdating = False
    Dim copySheet As Worksheet
    Dim pasteSheet As Worksheet

    Set copySheet = Worksheets("Sheet1")
    Set pasteSheet = Worksheets("Sheet2")
    Set dest =  pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
    With copySheet.Range("A23:L23")
       dest.Resize(.Rows.Count, .Columns.Count).Value = .Value
    End With
    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub


问:
What is difference between monolithic and micro kernel?
Could anyone please explain with examples difference between monolithic and micro kernel? Also other classifications of the kernel?</p>

答:
In the spectrum of kernel designs the two extreme
points are monolithic kernels and microkernels.

The (classical) Linux
kernel for instance is a monolithic kernel (and so is every commercial OS
to date as well - though they might claim otherwise);

In that its code is a
single C file giving rise to a single process that implements all of the above
services.

To exemplify the encapsulation of the Linux kernel we remark that
the Linux kernel does not even have access to any of the standard C libraries.
Indeed the Linux kernel cannot use rudimentary C library functions such as
printf. Instead it implements its own printing function (called prints).

This seclusion of the Linux kernel and self-containment provide Linux kernel
with its main advantage: the kernel resides in a single address space1
enabling
all features to communicate in the fastest way possible without resorting to
any type of message passing.
In particular, a monolithic kernel implements all of the device drivers
of the system.

This however is the main drawback of a monolithic kernel:
introduction of any new unsupported hardware requires a rewrite of the
kernel (in the relevant parts), recompilation of it, and re-installing the entire
OS.
More importantly, if any device driver crashes the entire kernel suffers
as a result.
This un-modular approach to hardware additions and hardware crashes
is the main argument for supporting the other extreme design approach
for kernels. A microkernel is in a sense a minimalistic kernel that houses
only the very basic of OS services (like process management and file system
management). In a microkernel the device drivers lie outside of the kernel
allowing for addition and removal of device drivers while the OS is running
and require no alternations of the kernel.


问:
How the interface builder has been designed for the following type of application with splitviewcontroller?
I am posting a link.  Can anybody please tell me that how the interface builder has been designed for this type of application?

http://itunes.apple.com/us/app/iorder-for-ipad/id385298425?mt=8

On this link, please look for the fourth image in the "Ipad Screenshots" section. The image on which a splitviewcontroller is taken and on the detailViewController the details of "Green Valley Inc." are displayed.

答:
Looks like a clear splitviewController to me, so add one of those, programmaticly or via IB.
or whatever program u use.
Also it is the 5th screenshot ^_-
But, that's a standard splitView, hope that gets u going!
Download standard MultipleViews or so from developer.apple.com, which will set u on the way</p>

ContentLicense: CC BY-SA 4.0


问:
Getting currency data using OAuth2 with the private key API
My developer is not sure how he would use OAuth2 in order to access currency data from PHP script using the Yahoo private key API and the Yahoo Query language (YQL).

He doesn't find a complete documentation to do so on in the Yahoo developer account. If somebody has any experience with that, could you provide a documentation or an example code how to use OAuth2 with the private key Yahoo API?

Thank You

答:
Yahoo's OAuth2 guide is located here: Yahoo OAuth 2.0 Guide

The "Explicit Grant Flow" and "Implicit Grant Flow" sections (depending on your needs) specify the sequence of steps needed to get an access token.  The "Making API Requests" section provides detail on how to include the access token in API requests to Yahoo's web services.

Hope this helps.

-Igor


问:
Assigning word from text file to array
```<code>person1 bob
person2 george
person3 tom
</code>```

This is a project on VB. I am attempting to read off a text file such as the above and assign the second word on each line to an array. For example, array(1) would be "bob", array(2) would have "george", and array(3) would have "tom". I am currently having trouble with assigning to arrays as my current output for array(1) is:

```<code>bob
george
tom
</code>```

My current attempt is:

```<code>Dim FileName As String = "*snip*"
Dim FileReader As StreamReader = File.OpenText(FileName)
Dim FileLine As String = FileReader.ReadLine()
For x = 1 To 18
    Dim players() As String = FileLine.Split(New Char() {" "c})
    FileLine = FileReader.ReadLine()
    Console.WriteLine(players(1))
    count = count + 1
Next
</code>```

I'm a total noob, please treat me well.

答:
Regex is admittedly an advanced concept, so you may want to hold off on learning it until you gain more experience, but, just so you're aware of it, it can be a powerful option when you need to do string parsing, replacements, and validation.  Here's an example of how this could be done with Regex:

```<code>Dim result() As String = Regex.
    Matches(File.ReadAllText(FileName), "^\s*\w+\s+(\w+)\s*$", RegexOptions.Multiline).
    Cast(Of Match).Select(Function(match) match.Groups(1).Value).ToArray()
</code>```

The real power, here, is the extra validation being performed.  Only lines that exactly match the regex pattern will be processed.  Also, by specifying a pattern, it's easier to adjust or improve it in the future.  Here's an explanation of the pattern (^\s*\w+\s+(\w+)\s*$):

^ - Only strings that start at the beginning of a line will match

\s* - Any number of whitespace characters at the beginning of the line will be allowed

\s - This is a special character class which matches any whitespace character

* - The character class will match zero or more characters in a row

\w+ - Matching strings must then contain a word

\w - A special character class which matches any word character

+ - The character class will match one or more characters in a row

\s+ - The first word must be followed by one or more whitespace characters

(\w+) - There must be a second word.  The parentheses create a capturing group.  In this case, capturing group signifies the portion of the match that we want to grab (i.e. we don't care about the rest of the matching line, just the second word).

\s* - The second word may be followed by any number of whitespace characters

$ - Signifies the end of the line.  By putting this in the pattern, it makes it so matches must fill an entire line.  In other words, only lines containing exactly two words will be processed.

Regex is a common tool that you'll see in many languages, software development tools and IDEs (e.g. Visual Studio search/replace, SSMS search/replace, Notepad++, grep), so it's worth the time to get to know it once you feel ready to take the plunge.

Regarding your original question, however, everyone answering seems to have avoided actually helping you to understand how to populate an array.  The real answer is, it's not that simple because arrays are inherently fixed length.  You can technically "resize" them in VB (using ReDim), but it's inefficient, old-school, and ugly.  If you need to add an unknown number of items to an array, one at a time, it's best to use a List(Of T) object.  For instance:

```<code>Dim result As New List(Of String)()
Dim line As String = Nothing
Do
    line = reader.ReadLine()
    If line IsNot Nothing Then
        Dim fields() As String = line.Split({" "c})
        result.Add(fields(1))
    End If
Loop While line IsNot Nothing
</code>```

If you then need to convert the list to a fixed-length array, you can do this:

```<code>Dim arr() As String = result.ToArray()
</code>```

If, however, you definitely know the exact number of items you have, it's possible (though still generally discouraged) to set the size of the array ahead of time and then fill each item in a loop:

```<code>Dim result(18) As String
For x = 0 To 17
    Dim fields() As String = line.Split({" "c})
    result(x) = fields(1)
    line = reader.ReadLine()
Next
</code>```

I say it's discouraged because it's more brittle, harder to read, and it's unnecessary, even when factoring performance.  If you know the size, and performance is a problem, you could still use a List and just specify the size in the constructor to pre-allocate the memory:

```<code>Dim result As New List(Of String)(18)
</code>```

However, as you've seen, when it's possible to write your code in a more declarative style, using LINQ, it's generally preferred by most people over any of these imperative styles.

Title: Assigning word from text file to array

Body:
person1 bob
person2 george
person3 tom

This is a project on VB. I am attempting to read off a text file such as the above and assign the second word on each line to an array. For example, array(1) would be "bob", array(2) would have "george", and array(3) would have "tom". I am currently having trouble with assigning to arrays as my current output for array(1) is:

bob
george
tom

My current attempt is:

Dim FileName As String = "*snip*"
Dim FileReader As StreamReader = File.OpenText(FileName)
Dim FileLine As String = FileReader.ReadLine()
For x = 1 To 18
    Dim players() As String = FileLine.Split(New Char() {" "c})
    FileLine = FileReader.ReadLine()
    Console.WriteLine(players(1))
    count = count + 1
Next

I'm a total noob, please treat me well.

Body:
Regex is admittedly an advanced concept, so you may want to hold off on learning it until you gain more experience, but, just so you're aware of it, it can be a powerful option when you need to do string parsing, replacements, and validation.  Here's an example of how this could be done with Regex:

Dim result() As String = Regex.
    Matches(File.ReadAllText(FileName), "^\s*\w+\s+(\w+)\s*$", RegexOptions.Multiline).
    Cast(Of Match).Select(Function(match) match.Groups(1).Value).ToArray()

The real power, here, is the extra validation being performed.  Only lines that exactly match the regex pattern will be processed.  Also, by specifying a pattern, it's easier to adjust or improve it in the future.  Here's an explanation of the pattern (^\s*\w+\s+(\w+)\s*$):

^ - Only strings that start at the beginning of a line will match

\s* - Any number of whitespace characters at the beginning of the line will be allowed

\s - This is a special character class which matches any whitespace character

* - The character class will match zero or more characters in a row

\w+ - Matching strings must then contain a word

\w - A special character class which matches any word character

+ - The character class will match one or more characters in a row

\s+ - The first word must be followed by one or more whitespace characters

(\w+) - There must be a second word.  The parentheses create a capturing group.  In this case, capturing group signifies the portion of the match that we want to grab (i.e. we don't care about the rest of the matching line, just the second word).

\s* - The second word may be followed by any number of whitespace characters

$ - Signifies the end of the line.  By putting this in the pattern, it makes it so matches must fill an entire line.  In other words, only lines containing exactly two words will be processed.

Regex is a common tool that you'll see in many languages, software development tools and IDEs (e.g. Visual Studio search/replace, SSMS search/replace, Notepad++, grep), so it's worth the time to get to know it once you feel ready to take the plunge.

Regarding your original question, however, everyone answering seems to have avoided actually helping you to understand how to populate an array.  The real answer is, it's not that simple because arrays are inherently fixed length.  You can technically "resize" them in VB (using ReDim), but it's inefficient, old-school, and ugly.  If you need to add an unknown number of items to an array, one at a time, it's best to use a List(Of T) object.  For instance:

Dim result As New List(Of String)()
Dim line As String = Nothing
Do
    line = reader.ReadLine()
    If line IsNot Nothing Then
        Dim fields() As String = line.Split({" "c})
        result.Add(fields(1))
    End If
Loop While line IsNot Nothing

If you then need to convert the list to a fixed-length array, you can do this:

Dim arr() As String = result.ToArray()

If, however, you definitely know the exact number of items you have, it's possible (though still generally discouraged) to set the size of the array ahead of time and then fill each item in a loop:

Dim result(18) As String
For x = 0 To 17
    Dim fields() As String = line.Split({" "c})
    result(x) = fields(1)
    line = reader.ReadLine()
Next

I say it's discouraged because it's more brittle, harder to read, and it's unnecessary, even when factoring performance.  If you know the size, and performance is a problem, you could still use a List and just specify the size in the constructor to pre-allocate the memory:

Dim result As New List(Of String)(18)

However, as you've seen, when it's possible to write your code in a more declarative style, using LINQ, it's generally preferred by most people over any of these imperative styles.


问:
Load Config JSON File In Angular 2
I want to load Constant File in Angular 2(which is a Normal TypeScript File) having WebAPI EndPoints.
In Angular1.x. we used to have constants for the same.
How in Angular 2 I can Implement the Same?

I have created the .ts file.My main concern lies in how to load the file beforehand every Other class File loads.

.ts file :

```<code>export class testAPI {
     getAPI = "myUrl";
}
</code>```

In service file I am using the same by doing Normal Import:

```<code>constructor(private http: Http) {

      //console.log(this.test);
      console.log(this.testing.getAPI);
      //this.test.load();
    }
</code>```

I am getting the Console as Undefined.(Must be because my Service class is loading before API Class).

Thanks in Advance.

答:
It is possible to import JSON in TypeScript. You need to add typings:

typings.d.ts:

```<code>declare module "*.json" {
  const value: any;
  export default value;
}
</code>```

And then import like this:

```<code>import config from "../config/config.json";
</code>```

config.json:

```<code>{
  "api_url": "http://localhost/dev"
}
</code>```

Title: Load Config JSON File In Angular 2

Body:
I want to load Constant File in Angular 2(which is a Normal TypeScript File) having WebAPI EndPoints.
In Angular1.x. we used to have constants for the same.
How in Angular 2 I can Implement the Same?

I have created the .ts file.My main concern lies in how to load the file beforehand every Other class File loads.

.ts file :

export class testAPI {
     getAPI = "myUrl";
}

In service file I am using the same by doing Normal Import:

constructor(private http: Http) {

      //console.log(this.test);
      console.log(this.testing.getAPI);
      //this.test.load();
    }

I am getting the Console as Undefined.(Must be because my Service class is loading before API Class).

Thanks in Advance.

Body:
It is possible to import JSON in TypeScript. You need to add typings:

typings.d.ts:

declare module "*.json" {
  const value: any;
  export default value;
}

And then import like this:

import config from "../config/config.json";

config.json:

{
  "api_url": "http://localhost/dev"
}


问:
Getting Chrome to accept self-signed localhost certificate
I have created a self-signed SSL certificate for the localhost CN. Firefox accepts this certificate after initially complaining about it, as expected. Chrome and IE, however, refuse to accept it, even after adding the certificate to the system certificate store under Trusted Roots. Even though the certificate is listed as correctly installed when I click "View certificate information" in Chrome's HTTPS popup, it still insists the certificate cannot be trusted.

What am I supposed to do to get Chrome to accept the certificate and stop complaining about it?

答:
WINDOWS JUN/2017 Windows Server 2012

I followed @Brad Parks answer. On Windows you should import rootCA.pem in Trusted Root Certificates Authorities store.

I did the following steps:

```<code>openssl genrsa -out rootCA.key 4096
openssl req -x509 -new -nodes -key rootCA.key -newkey rsa:4096 -sha256 -days 1024 -out rootCA.pem
openssl req -new -newkey rsa:4096 -sha256 -nodes -keyout device.key -out device.csr
openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days 2000 -sha256 -extfile v3.ext
</code>```

Where v3.ext is:

```<code>authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
IP.1 = 192.168.0.2
IP.2 = 127.0.0.1
</code>```

Then, in my case I have a self hosted web app, so I need to bind certificate with IP address and port, certificate should be on MY store with private key information, so I exported to pfx format.

```<code>openssl pkcs12 -export -out device.pfx -inkey device.key -in device.crt
</code>```

With mmc console (File/Add or Remove Snap-ins/Certificates/Add/Computert Account/LocalComputer/OK) I imported pfx file in Personal store.

Later I used this command to bind certificate (you could also use HttpConfig tool):

```<code>netsh http add sslcert ipport=0.0.0.0:12345 certhash=b02de34cfe609bf14efd5c2b9be72a6cb6d6fe54 appid={BAD76723-BF4D-497F-A8FE-F0E28D3052F4}
</code>```

certhash=Certificate Thumprint

appid=GUID (your choice)

First I tried to import the certificate "device.crt" on Trusted Root Certificates Authorities in different ways but I'm still getting same error:

But I realized that I should import certificate of root authority not certificate for domain. So I used mmc console (File/Add or Remove Snap-ins/Certificates/Add/Computert Account/LocalComputer/OK) I imported rootCA.pem in Trusted Root Certificates Authorities store.

Restart Chrome and et voilà it works.

With localhost:

Or with IP address:

The only thing I could not achieve is that, it has obsolete cipher (red square on picture). Help is appreciated on this point.

With makecert it is not possible add SAN information.
With New-SelfSignedCertificate (Powershell) you could add SAN information, it also works.

Body:
WINDOWS JUN/2017 Windows Server 2012

I followed @Brad Parks answer. On Windows you should import rootCA.pem in Trusted Root Certificates Authorities store.

I did the following steps:

openssl genrsa -out rootCA.key 4096
openssl req -x509 -new -nodes -key rootCA.key -newkey rsa:4096 -sha256 -days 1024 -out rootCA.pem
openssl req -new -newkey rsa:4096 -sha256 -nodes -keyout device.key -out device.csr
openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days 2000 -sha256 -extfile v3.ext

Where v3.ext is:

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
IP.1 = 192.168.0.2
IP.2 = 127.0.0.1

Then, in my case I have a self hosted web app, so I need to bind certificate with IP address and port, certificate should be on MY store with private key information, so I exported to pfx format.

openssl pkcs12 -export -out device.pfx -inkey device.key -in device.crt

With mmc console (File/Add or Remove Snap-ins/Certificates/Add/Computert Account/LocalComputer/OK) I imported pfx file in Personal store.

Later I used this command to bind certificate (you could also use HttpConfig tool):

netsh http add sslcert ipport=0.0.0.0:12345 certhash=b02de34cfe609bf14efd5c2b9be72a6cb6d6fe54 appid={BAD76723-BF4D-497F-A8FE-F0E28D3052F4}

certhash=Certificate Thumprint

appid=GUID (your choice)

First I tried to import the certificate "device.crt" on Trusted Root Certificates Authorities in different ways but I'm still getting same error:

But I realized that I should import certificate of root authority not certificate for domain. So I used mmc console (File/Add or Remove Snap-ins/Certificates/Add/Computert Account/LocalComputer/OK) I imported rootCA.pem in Trusted Root Certificates Authorities store.

Restart Chrome and et voilà it works.

With localhost:

Or with IP address:

The only thing I could not achieve is that, it has obsolete cipher (red square on picture). Help is appreciated on this point.

With makecert it is not possible add SAN information.
With New-SelfSignedCertificate (Powershell) you could add SAN information, it also works.


问:
How to highlight occurrences of a search term in text in Visual Studio?
How do I make all occurrences of a phrase (search term) in a file to be highlighted in the VS code editor?</p>

答: I copied and pasted the source code into Word 2007. This has highlight all option called 'Reading Highlight'. This keeps the highlighting on even when you search for another term.</p>

OwnerDisplayName: Aleksey Kudryavtsev

LastEditorDisplayName: tvanfosson


问:
Restricting input length and characters for Entry field in Xamarin.Forms
How can I restrict the length and characters entered in an Entry control in Xamarin.Forms.  Do I need to create a custom control?  Is there a way I can derive from Entry (or another control) so I can apply the necessary per-platform input limitations.

An example would be a numeric field that is restricted to a maximum of 3 characters, digits only.

Setting the Keyboard property of an Entry control to Keyboard.Numeric only sets the keyboard for iOS.  It does not restrict the actual text entry - i.e. I can still enter non-digit characters.  Nor do I see a way to limit the length of entry.

答:
Define a new Custom Entry with the required properties:

```<code>public class CustomEntry : Entry
{
    public int MaxLength { get; set; }
    public bool IsNumeric { get; set; }
    public int MinValue { get; set; }
    public int MaxValue { get; set; }

    public CustomEntry()
    {

        // Initialize properties.
        IsNumeric = false;
        MaxLength = int.MaxValue;
        MinValue = int.MinValue;
        MaxValue = int.MaxValue;

        // Set the events.
        base.TextChanged += OnTextChanged;
    }

   public void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        Entry entry = sender as Entry;

        // If empty, set it to empty string.
        if (string.IsNullOrWhiteSpace(e.NewTextValue))
        {
            entry.Text = string.Empty;
            return;
        }

        // Check if it is numeric.
        if (IsNumeric)
        {
            int value;
            var isValid = int.TryParse(e.NewTextValue, out value);

            if (!isValid)
            {
                entry.Text = e.OldTextValue;
                return;
            }

            // Check the min/max values.
            if (value > MaxValue || value < MinValue)
            {
                entry.Text = e.OldTextValue;
            }
        }

        // If not numeric, check the length.
        if (e.NewTextValue.Length > MaxLength)
            entry.Text = e.OldTextValue;
    }
}
</code>```

And to use it in XAML:

```<code>   <controls:CustomEntry Text="{Binding months}" Keyboard="Numeric" IsNumeric="true" MaxLength="2" MinValue="1" MaxValue="12"/>
</code>```

NOTE: instead of removing the last character which is the case in most answers, it is safer to set the text to the old text, since the user might copy/past more than a character into the textbox.

Body:
Define a new Custom Entry with the required properties:

public class CustomEntry : Entry
{
    public int MaxLength { get; set; }
    public bool IsNumeric { get; set; }
    public int MinValue { get; set; }
    public int MaxValue { get; set; }

    public CustomEntry()
    {

        // Initialize properties.
        IsNumeric = false;
        MaxLength = int.MaxValue;
        MinValue = int.MinValue;
        MaxValue = int.MaxValue;

        // Set the events.
        base.TextChanged += OnTextChanged;
    }

   public void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        Entry entry = sender as Entry;

        // If empty, set it to empty string.
        if (string.IsNullOrWhiteSpace(e.NewTextValue))
        {
            entry.Text = string.Empty;
            return;
        }

        // Check if it is numeric.
        if (IsNumeric)
        {
            int value;
            var isValid = int.TryParse(e.NewTextValue, out value);

            if (!isValid)
            {
                entry.Text = e.OldTextValue;
                return;
            }

            // Check the min/max values.
            if (value > MaxValue || value < MinValue)
            {
                entry.Text = e.OldTextValue;
            }
        }

        // If not numeric, check the length.
        if (e.NewTextValue.Length > MaxLength)
            entry.Text = e.OldTextValue;
    }
}

And to use it in XAML:

   <controls:CustomEntry Text="{Binding months}" Keyboard="Numeric" IsNumeric="true" MaxLength="2" MinValue="1" MaxValue="12"/>

NOTE: instead of removing the last character which is the case in most answers, it is safer to set the text to the old text, since the user might copy/past more than a character into the textbox.


答:
Use Array#map and fat arrow functions.

let categorias = [
        {
            "id_categoria": 1,
            "nom_categoria": "Graduação"
        },
        {
            "id_categoria": 2,
            "nom_categoria": "Pós-Graduação"
        },
        {
            "id_categoria": 3,
            "nom_categoria": "Disciplinas"
        }
    ];

    let res = categorias.map(x=>x["nom_categoria"]);
    console.log(res);```

Title: How to get values on JSON result

Body:
I have one url that give the output below in JSON:

{
    "categorias": [
        {
            "id_categoria": 1,
            "nom_categoria": "Graduação"
        },
        {
            "id_categoria": 2,
            "nom_categoria": "Pós-Graduação"
        },
        {
            "id_categoria": 3,
            "nom_categoria": "Disciplinas"
        }
    ]
}

How I can extract only the values "Graduação","Pós-Graduação","Disciplinas" using Jquery?


问:
Set background image with transparent color and also make the height of the image adapt to the content
```<code>.about {
  width: 100%;
  height: 300px;
  background-color: rgba(0,0,0,0.55);
}
</code>```

I am trying to set a black color with 55% transparency to the image.
Also I need the height of the image to be as long as the content.
The content will be on some columns but at tablet and mobile resolution all the columns will go one under another so the content won't fit on the image.

Also I need the tranparency to affect only the image and not the text.

What is the best way to acheive this?

Here is my Fiddle: fiddle

答:
```<code>.about {
  width: 100%;
  height: 100%;
  position:relative;
}
.about:after{
   content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background:url('http://i.imgur.com/tENv1w4.jpg') no-repeat center center;
    width: 100%;
    height: 100%;
    opacity : 0.55;
    z-index: -1;
}

.text {
  color: #fff;
  font-size: 22px;
  text-align: center;
}
</code>```

Check this fiddle for your solution.

https://jsfiddle.net/n5qfa/89/

Body:
.about {
  width: 100%;
  height: 300px;
  background-color: rgba(0,0,0,0.55);
}

I am trying to set a black color with 55% transparency to the image.
Also I need the height of the image to be as long as the content.
The content will be on some columns but at tablet and mobile resolution all the columns will go one under another so the content won't fit on the image.

Also I need the tranparency to affect only the image and not the text.

What is the best way to acheive this?

Here is my Fiddle: fiddle

Body:
.about {
  width: 100%;
  height: 100%;
  position:relative;
}
.about:after{
   content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background:url('http://i.imgur.com/tENv1w4.jpg') no-repeat center center;
    width: 100%;
    height: 100%;
    opacity : 0.55;
    z-index: -1;
}

.text {
  color: #fff;
  font-size: 22px;
  text-align: center;
}

Check this fiddle for your solution.

https://jsfiddle.net/n5qfa/89/


问:
Custom grid with images - responsive issues
i've created a custom module in joomla to display a gallery in the homepage of the website i'm currently working at: http://www.francescaleso.com/it/

The problem is that my media queries work fine only for desktop or small mobile devices in portrait mode only.

For ipads and mobiles in landscape mode, it messes up everything.

Here's the code, which you can also check with F12 tools:

```<code>/* the container of the whole gallery, for desktop */
.home-container {
    padding-top: 5%;
    margin-bottom: -2%;
}

@media screen and (max-device-width: 990px) {
    .home-container {
        display: none;
}
}

/* the container of the whole gallery, for mobile devices */
.home-container-mobile {
    padding-top: 0%;
    margin-bottom: -2%;
    margin-top: -10%;
}

@media screen and (min-device-width: 990px) {
    .home-container-mobile {
        display: none;
}
}

/* the container of a single row of items in the gallery */

.grid-container {
    display: table;
    margin: 0 auto;
}

@media screen and (max-device-width: 990px) {
    .grid-container {
    width: 100%;
}
}

/* the gallery single item */

.grid {
    float: left;
    position: relative;
    border-radius: 50%;
    margin: 10px;
}

@media screen and (max-device-width: 990px) {
    .grid {
    width: 43%;
    float: left !important;
    position: relative;
    border-radius: 50%;
    margin: 10px;
}
}

/* the gallery single item image */

.grid img {
    border-radius: 50%;
    transition: .4s -webkit-filter linear;
}

.grid:hover img {
  filter: url(filters.svg#grayscale);
     /* Firefox 3.5+ */
  filter: gray;
  /* IE6-9 */
  -webkit-filter: grayscale(1);
}

/* the gallery single item description */

.desc {
    /* display: block; */
    /* position: absolute; */
    left: 26%;
    width: 87%;
    height: 100%;
    top: 0%;
    left: 0%;
    border-radius: 50%;
}

.desc span {
width: 100%;
    height: 100%;
    text-align: center;
    margin-top: 37%;
    position: absolute;
    left: 0;
    bottom: 0%;
    font-size: 16px;
    opacity: 0;
    -webkit-transition: opacity .8s ease 50ms;
    transition: opacity .8s ease 50ms;
    -webkit-transition: background-color ease-in-out 200ms;
    transition: background-color .3s ease-in-out 200ms;
    color: #fff !important;
    border-radius: 50%;
}

@media screen and (max-device-width: 767px) {
    .desc span {
        opacity: 1;
        /* background: rgba(178,189,167,0.7) */
        /* first gradient darker - background: radial-gradient(rgba(72,67,67,0.644444) 20%, rgba(72,67,67,0.37) 77%) !important; */
        background: radial-gradient(rgba(72,67,67,0.444444) 20%, rgba(72,67,67,0.37) 34%) !important
}
}

@media only screen and
(min-device-width: 767px)
(max-device-width: 1025px){
    .desc span {
        width: 68% !important;
        opacity: 1;
        /* background: rgba(178,189,167,0.7) */
        /* first gradient darker - background: radial-gradient(rgba(72,67,67,0.644444) 20%, rgba(72,67,67,0.37) 77%) !important; */
        background: radial-gradient(rgba(72,67,67,0.444444) 20%, rgba(72,67,67,0.37) 34%) !important;
}
}

.grid:hover .desc span {
  opacity: 1;
    /* background: rgba(168,202,217,0.6); */
    /* background: rgba(186, 212, 106, 0.6); */
    /* background: rgba(201, 220, 135, 0.6); */
    /* background: rgba(197, 225, 165, 0.6); */
    /* background: rgba(230, 238, 156, 0.6); */
    background: rgba( 178, 189, 167, 0.7);
}
</code>```

As you can see, in such "intermediate" mobile views, the whole structure gets screwed up: i would like to have 2 columns of items for mobile phones (which i have achieved), and 4 for the other views, like the desktop version.

How can i achieve that?

Is there any other method to get the description div to cover the whole image area without setting a defined width and a height? That seems to be the thing that doesn't work properly...

Thank you for your attention, this really is a great community!

答:
There two ways you can achieve what you want

First: define media query for all standard screen sizes like

```<code>/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}
</code>```

or you can any css mobile first frame work like Bootstrap, Foundation 3, Foundation etc
just need to add css and use grid layout to achieve clean and standard layout easily.

Body:
i've created a custom module in joomla to display a gallery in the homepage of the website i'm currently working at: http://www.francescaleso.com/it/

The problem is that my media queries work fine only for desktop or small mobile devices in portrait mode only.

For ipads and mobiles in landscape mode, it messes up everything.

Here's the code, which you can also check with F12 tools:

/* the container of the whole gallery, for desktop */
.home-container {
    padding-top: 5%;
    margin-bottom: -2%;
}

@media screen and (max-device-width: 990px) {
    .home-container {
        display: none;
}
}

/* the container of the whole gallery, for mobile devices */
.home-container-mobile {
    padding-top: 0%;
    margin-bottom: -2%;
    margin-top: -10%;
}

@media screen and (min-device-width: 990px) {
    .home-container-mobile {
        display: none;
}
}

/* the container of a single row of items in the gallery */

.grid-container {
    display: table;
    margin: 0 auto;
}

@media screen and (max-device-width: 990px) {
    .grid-container {
    width: 100%;
}
}

/* the gallery single item */

.grid {
    float: left;
    position: relative;
    border-radius: 50%;
    margin: 10px;
}

@media screen and (max-device-width: 990px) {
    .grid {
    width: 43%;
    float: left !important;
    position: relative;
    border-radius: 50%;
    margin: 10px;
}
}

/* the gallery single item image */

.grid img {
    border-radius: 50%;
    transition: .4s -webkit-filter linear;
}

.grid:hover img {
  filter: url(filters.svg#grayscale);
     /* Firefox 3.5+ */
  filter: gray;
  /* IE6-9 */
  -webkit-filter: grayscale(1);
}

/* the gallery single item description */

.desc {
    /* display: block; */
    /* position: absolute; */
    left: 26%;
    width: 87%;
    height: 100%;
    top: 0%;
    left: 0%;
    border-radius: 50%;
}

.desc span {
width: 100%;
    height: 100%;
    text-align: center;
    margin-top: 37%;
    position: absolute;
    left: 0;
    bottom: 0%;
    font-size: 16px;
    opacity: 0;
    -webkit-transition: opacity .8s ease 50ms;
    transition: opacity .8s ease 50ms;
    -webkit-transition: background-color ease-in-out 200ms;
    transition: background-color .3s ease-in-out 200ms;
    color: #fff !important;
    border-radius: 50%;
}

@media screen and (max-device-width: 767px) {
    .desc span {
        opacity: 1;
        /* background: rgba(178,189,167,0.7) */
        /* first gradient darker - background: radial-gradient(rgba(72,67,67,0.644444) 20%, rgba(72,67,67,0.37) 77%) !important; */
        background: radial-gradient(rgba(72,67,67,0.444444) 20%, rgba(72,67,67,0.37) 34%) !important
}
}

@media only screen and
(min-device-width: 767px)
(max-device-width: 1025px){
    .desc span {
        width: 68% !important;
        opacity: 1;
        /* background: rgba(178,189,167,0.7) */
        /* first gradient darker - background: radial-gradient(rgba(72,67,67,0.644444) 20%, rgba(72,67,67,0.37) 77%) !important; */
        background: radial-gradient(rgba(72,67,67,0.444444) 20%, rgba(72,67,67,0.37) 34%) !important;
}
}

.grid:hover .desc span {
  opacity: 1;
    /* background: rgba(168,202,217,0.6); */
    /* background: rgba(186, 212, 106, 0.6); */
    /* background: rgba(201, 220, 135, 0.6); */
    /* background: rgba(197, 225, 165, 0.6); */
    /* background: rgba(230, 238, 156, 0.6); */
    background: rgba( 178, 189, 167, 0.7);
}

As you can see, in such "intermediate" mobile views, the whole structure gets screwed up: i would like to have 2 columns of items for mobile phones (which i have achieved), and 4 for the other views, like the desktop version.

How can i achieve that?

Is there any other method to get the description div to cover the whole image area without setting a defined width and a height? That seems to be the thing that doesn't work properly...

Thank you for your attention, this really is a great community!

Body:
There two ways you can achieve what you want

First: define media query for all standard screen sizes like

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

or you can any css mobile first frame work like Bootstrap, Foundation 3, Foundation etc
just need to add css and use grid layout to achieve clean and standard layout easily.


问:
Trigger events that are loaded via AJAX
The issue: when retrieving data from an Ajax request that contains components to be used in jQuery calls. The jQuery isn't working.

Solution: as answered by  Bikash Waiba the reason this happens is because the jQuery functionality needs to know the page has loaded.

答:
Echoing html from a php function is absolutely ok the problem arises if you echo the block dynamically after page load via ajax in such case you can do something like this</p>

```<code>$(document).on("click",'#likeClick',function(e){
     var id = $('#likeClick').data('value');
   $.ajax({
     url: '../resources/handlers/like.php',
     type: 'POST',
     data: {id: id},
     cache:false,
     success: function(data) {
       $('#likeNumber').html(data);
     }
   });
});
</code>```

Title: Trigger events that are loaded via AJAX

Body:
Echoing html from a php function is absolutely ok the problem arises if you echo the block dynamically after page load via ajax in such case you can do something like this

$(document).on("click",'#likeClick',function(e){
     var id = $('#likeClick').data('value');
   $.ajax({
     url: '../resources/handlers/like.php',
     type: 'POST',
     data: {id: id},
     cache:false,
     success: function(data) {
       $('#likeNumber').html(data);
     }
   });
});


问:
SQL error in laravel
I am trying to change a field in my users table to a varchar of 200.  Currently it is 60 and not long enough.  I tried using ->change() but because the table has an enum I get an error Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.
As a result I am trying to change the column using a raw sql statement.
Here is the line I am trying to use.

```<code>DB::statement('ALTER TABLE users CHANGE COLUMN subrole VARCHAR(200)');
</code>```

When I try this I get an error

```<code>[Illuminate\Database\QueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the
  right syntax to use near 'VARCHAR(200)' at line 1 (SQL: ALTER TABLE users CHANGE COLUMN subrole VARCHAR(200))
</code>```

What do I need to change?  I am trying to change the column of subrole to size varchar 200.

答:
could be you need  MODIFY</p>

```<code> DB::statement('ALTER TABLE users MODIFY COLUMN subrole VARCHAR(200)');
</code>```

Title: SQL error in laravel

Body:
I am trying to change a field in my users table to a varchar of 200.  Currently it is 60 and not long enough.  I tried using ->change() but because the table has an enum I get an error Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.
As a result I am trying to change the column using a raw sql statement.
Here is the line I am trying to use.

DB::statement('ALTER TABLE users CHANGE COLUMN subrole VARCHAR(200)');

When I try this I get an error

[Illuminate\Database\QueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the
  right syntax to use near 'VARCHAR(200)' at line 1 (SQL: ALTER TABLE users CHANGE COLUMN subrole VARCHAR(200))

What do I need to change?  I am trying to change the column of subrole to size varchar 200.

Body:
could be you need  MODIFY

 DB::statement('ALTER TABLE users MODIFY COLUMN subrole VARCHAR(200)');


问:
Form Post 2 places altering field names in second submit
Here is the code that I am using. It submits fine the way it is to the two places I need it to. What I need to accomplish is this:

Submit the form as is to the first post location. That's obviously no problem, lol. Here's the rub.... I would like to amend the form field names that is submitted to the second post location.

Example: Field name is: "Administrator". When posting to the second post location place something like: "Some_Text_Administrator"

Is this even possible? Thanks in advance to this fine community!!

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
      <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
      <title>Register</title>
      <link rel="STYLESHEET" type="text/css" href="style.css">
      <script type='text/javascript' src='gen_validatorv31.js'></script>
</head>
<body onload='hideResultDiv();'>

<div id='allcontainer'>
<div id='formcontainer'>
<!-- Form Code Start -->
<form id='contactus' action='' method='post' class="xxxx" name="xxxx">

<fieldset >
<legend>Title Here</legend>

<tr>
      <td>
<font size=2 face=arial color=#333333>
              <b>Account Administrator</b>
            </font>
</td>
<td>
<input type=text size=40 name=Administrator>
</td>
</tr>

<tr>
      <td>
<font size=2 face=arial color=#333333>
              <b>Administrator Email</b>
            </font>
</td>
<td>
<input type=text size=40 name=email>
</td>
</tr>

<tr>
      <td>
<font size=2 face=arial color=#333333>
              <b>State</b>
            </font>
</td>
<td>
<select name=State_Location1>
<option></option>
<option>AL</option>
<option>AK</option>
<option>AZ</option>
<option>AR</option>
<option>CA</option>
<option>CO</option>
<option>CT</option>
<option>DC</option>
<option>DE</option>
<option>FL</option>
<option>GA</option>
<option>HI</option>
<option>ID</option>
<option>IL</option>
<option>IN</option>
<option>IA</option>
<option>KS</option>
<option>KY</option>
<option>LA</option>
<option>ME</option>
<option>MD</option>
<option>MA</option>
<option>MI</option>
<option>MN</option>
<option>MS</option>
<option>MO</option>
<option>MT</option>
<option>NE</option>
<option>NV</option>
<option>NH</option>
<option>NJ</option>
<option>NM</option>
<option>NY</option>
<option>NC</option>
<option>ND</option>
<option>OH</option>
<option>OK</option>
<option>OR</option>
<option>PA</option>
<option>RI</option>
<option>SC</option>
<option>SD</option>
<option>TN</option>
<option>TX</option>
<option>UT</option>
<option>VT</option>
<option>VA</option>
<option>WA</option>
<option>WV</option>
<option>WI</option>
<option>WY</option>
</select>
</td>
</tr>

<tr>
      <td>
<font size=2 face=arial color=#333333>
              <b>Zip Code</b>
            </font>
</td>
<td>
<input type=text size=20 name=Zip_Code_Location1>
</td>
</tr>

<tr>
      <td>
<font size=2 face=arial color=#333333>
              Category 1
            </font>
</td>
<td>
<select name=Category1>
<option></option>
<option>Cat 1</option>
<option>Cat 2</option>
<option>Cat 3</option>
</select>
</td>
</tr>
</table>

<div class='container'>
    <input type='button' name='Submit' value='Submit' onclick='javascript: return SubmitForm()' />
</div>

</fieldset>
</form>

<script type='text/javascript'>
// <![CDATA[

    var frmvalidator  = new Validator("contactus");
    frmvalidator.EnableOnPageErrorDisplay();
    frmvalidator.EnableMsgsTogether();
    frmvalidator.addValidation("name","req","Please provide your name");

    frmvalidator.addValidation("email","req","Please provide your email address");

    frmvalidator.addValidation("email","email","Please provide a valid email address");

    frmvalidator.addValidation("message","maxlen=2048","The message is too long!(more than 2KB!)");
// ]]>
</script>

<script type='text/javascript'>

function SubmitForm()
{
    if(document.forms['contactus'].onsubmit())
    {
        showResultDiv();
        document.forms['contactus'].action='xxxx1';
        document.forms['contactus'].target='frame_result1';
        document.forms['contactus'].submit();

        document.forms['contactus'].action='xxxx2';
        document.forms['contactus'].target='frame_result2';
        document.forms['contactus'].submit();
    }
    return true;
}

function showResultDiv()
{
    var result_div = document.getElementById('resultcontainer');
    result_div.style.display="";
}

function hideResultDiv()
{
    var result_div = document.getElementById('resultcontainer');
    result_div.style.display='none';
}

</script>
<!--
Form Code End
-->
</div >
<div id='resultcontainer'>
There are three iframes below, that
shows results from each of the action scripts.

<div class='iframe_container'>
<iframe name='frame_result1' width='400px' height='400px' frameborder='0'></iframe>
</div>
<div class='iframe_container'>
<iframe name='frame_result2' width='400px' height='400px' frameborder='0'></iframe>
</div>
</div >
</div>

</body>
</html>
</code>```

答:
The first thing you need to do is to add an id to the inputs that you want the name changed. That will make your life easier when selecting those inputs.

So, the first input will be: <input id="input_administrator" type="text" size="40" name="Administrator">

Then, in your function that does the submission, after the first submit, you just change the name of the inputs, getting then by their id and changing their name attribute:

```<code>function SubmitForm()
{
    if(document.forms['contactus'].onsubmit())
    {
        showResultDiv();
        document.forms['contactus'].action='xxxx1';
        document.forms['contactus'].target='frame_result1';
        document.forms['contactus'].submit();

        // Changing the name of the inputs, to submit to location 2
        document.getElementById("input_administrator").name = "Second_Name_Administrator";

        document.forms['contactus'].action='xxxx2';
        document.forms['contactus'].target='frame_result2';
        document.forms['contactus'].submit();
    }
    return true;
}
</code>```

In this example I've used only the input Administrator, you should do it for every input

Body:
Here is the code that I am using. It submits fine the way it is to the two places I need it to. What I need to accomplish is this:

Submit the form as is to the first post location. That's obviously no problem, lol. Here's the rub.... I would like to amend the form field names that is submitted to the second post location.

Example: Field name is: "Administrator". When posting to the second post location place something like: "Some_Text_Administrator"

Is this even possible? Thanks in advance to this fine community!!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

      <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
      <title>Register</title>
      <link rel="STYLESHEET" type="text/css" href="style.css">

<form id='contactus' action='' method='post' class="xxxx" name="xxxx">

<fieldset >
<legend>Title Here</legend>

              Account Administrator

<input type=text size=40 name=Administrator>

              Administrator Email

<input type=text size=40 name=email>

              State

<select name=State_Location1>
<option></option>
<option>AL</option>
<option>AK</option>
<option>AZ</option>
<option>AR</option>
<option>CA</option>
<option>CO</option>
<option>CT</option>
<option>DC</option>
<option>DE</option>
<option>FL</option>
<option>GA</option>
<option>HI</option>
<option>ID</option>
<option>IL</option>
<option>IN</option>
<option>IA</option>
<option>KS</option>
<option>KY</option>
<option>LA</option>
<option>ME</option>
<option>MD</option>
<option>MA</option>
<option>MI</option>
<option>MN</option>
<option>MS</option>
<option>MO</option>
<option>MT</option>
<option>NE</option>
<option>NV</option>
<option>NH</option>
<option>NJ</option>
<option>NM</option>
<option>NY</option>
<option>NC</option>
<option>ND</option>
<option>OH</option>
<option>OK</option>
<option>OR</option>
<option>PA</option>
<option>RI</option>
<option>SC</option>
<option>SD</option>
<option>TN</option>
<option>TX</option>
<option>UT</option>
<option>VT</option>
<option>VA</option>
<option>WA</option>
<option>WV</option>
<option>WI</option>
<option>WY</option>
</select>

              Zip Code

<input type=text size=20 name=Zip_Code_Location1>

              Category 1

<select name=Category1>
<option></option>
<option>Cat 1</option>
<option>Cat 2</option>
<option>Cat 3</option>
</select>

    <input type='button' name='Submit' value='Submit' onclick='javascript: return SubmitForm()' />

</fieldset>
</form>

There are three iframes below, that
shows results from each of the action scripts.

Body:
The first thing you need to do is to add an id to the inputs that you want the name changed. That will make your life easier when selecting those inputs.

So, the first input will be: <input id="input_administrator" type="text" size="40" name="Administrator">

Then, in your function that does the submission, after the first submit, you just change the name of the inputs, getting then by their id and changing their name attribute:

function SubmitForm()
{
    if(document.forms['contactus'].onsubmit())
    {
        showResultDiv();
        document.forms['contactus'].action='xxxx1';
        document.forms['contactus'].target='frame_result1';
        document.forms['contactus'].submit();

        // Changing the name of the inputs, to submit to location 2
        document.getElementById("input_administrator").name = "Second_Name_Administrator";

        document.forms['contactus'].action='xxxx2';
        document.forms['contactus'].target='frame_result2';
        document.forms['contactus'].submit();
    }
    return true;
}

In this example I've used only the input Administrator, you should do it for every input


问:
Python Regex to replace absolute paths in text to relative paths added in quotes
I'm new to regex and was trying to solve the below problem.

Input String -  String that has a path as /Users/MyName/moreofPath/  with additional text

Output String - String that has a path as "$relativePath/moreofPath/"  with additional text

The absolute path in the sentence is to be recognized by

1) where /Users/MyName starts

2) where last / that comes before any other special character or space ends

This should be replaced by relative path in quotes.
Can someone please help me find correct regex for this.

答:
Since it's all Python, I would do something like this:

```<code>import re

thestring = "String that has a path as /Users/MyName/moreofPath/evenmore/ with additional text"
regex = "(.*?)/Users/MyName/(.*/)"
thestring = re.sub(regex, r'\1"$relativePath/\2"' , thestring)
print (thestring)
</code>```

Output:

```<code>String that has a path as "$relativePath/moreofPath/evenmore/" with additional text
</code>```

What I'm doing is grabbing the matches in the from the parans and substituting them back in the replacement.  Note that the .* makes it greedy up to the last /

Body:
Since it's all Python, I would do something like this:

import re

thestring = "String that has a path as /Users/MyName/moreofPath/evenmore/ with additional text"
regex = "(.*?)/Users/MyName/(.*/)"
thestring = re.sub(regex, r'\1"$relativePath/\2"' , thestring)
print (thestring)

Output:

String that has a path as "$relativePath/moreofPath/evenmore/" with additional text

What I'm doing is grabbing the matches in the from the parans and substituting them back in the replacement.  Note that the .* makes it greedy up to the last /