问:
How to combined similar-named nested classes from a derived and its base class
I was working on a small project where I created standard implementations of add-ons for a system. These standard implementations would set up things like logging, configuration, etc. all in a uniform way. All with maintainability and re-usability in mind.

Now the thing I am struggling with right now is how to handle names of settings. Before I always created a nested class Settings in with I declared some const string values like

public const string BananaSetting = "BananaSetting";

so I pretty much never could misspell a setting's name ever again.

I however have an base class which should have a setting called DEBUG, to use as a generic debug-enabling setting; but also add-on specific settings, which only exist for that one specific add-on.
Seeing as I base every derived class on the class that has the DEBUG setting nested class, any derived class that tries to declare a similar nested class called Settings will trigger a compiler warning:

DerivedClass.Settings hides inherited member 'BaseClass.Settings'. Use the new keyword if hiding was intended.

But I do not want to hide it. What I would really like to do is combine the two Settings classes into one. Is there any way to do this, or is there an existing design pattern of some sort to do this correctly?

```<code>public abstract class BaseClass
{
    public class Settings
    {
        public const string BananaSetting = "BananaSetting";
    }

    public abstract void BaseAbstractMethod();
    public void BaseMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
    }
}

public class DerivedClass : BaseClass
{
    public class Settings
    {
        public const string DerivedBananaSetting = "DerivedBananaSetting";
    }

    public override void BaseAbstractMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
        var subSettingValue = settingsDictionary[Settings.DerivedBananaSetting];
    }
}
</code>```

答:
How about sth. like this:</p>

```<code>public abstract class SettingBase
{
     public abstract string GetSettingName();

     public abstract SettingBase GetSetting();

     //Shared Properties and Stuff here:
}

public class BananaSetting : SettingBase
{
     public override string GetSettingName()
     {
         return nameof(BananaSetting);
     }

     public override SettingBase GetSetting()
     {
         return this;
     }

     //Banana-Specific Settings go here
}

public class DEBUGSetting : SettingBase
{
     public override string GetSettingName()
     {
         return nameof(DEBUGSetting);
     }

     public override SettingBase GetSetting()
     {
         return this;
     }

     //DEBUG-Specific Settings go here
}

public class Program
{
     public void Demo()
     {
         var settings = LoadSettings();
         foreach(var setting in settings)
         {
             var implementation = setting.GetSetting();
             if(implementation is DEBUGSetting dbg)
             {
                 //access dbg.Properties here
             }
             [...]
         }
     }
}
</code>```

Body:
I was working on a small project where I created standard implementations of add-ons for a system. These standard implementations would set up things like logging, configuration, etc. all in a uniform way. All with maintainability and re-usability in mind.

Now the thing I am struggling with right now is how to handle names of settings. Before I always created a nested class Settings in with I declared some const string values like

public const string BananaSetting = "BananaSetting";

so I pretty much never could misspell a setting's name ever again.

I however have an base class which should have a setting called DEBUG, to use as a generic debug-enabling setting; but also add-on specific settings, which only exist for that one specific add-on.
Seeing as I base every derived class on the class that has the DEBUG setting nested class, any derived class that tries to declare a similar nested class called Settings will trigger a compiler warning:

DerivedClass.Settings hides inherited member 'BaseClass.Settings'. Use the new keyword if hiding was intended.

But I do not want to hide it. What I would really like to do is combine the two Settings classes into one. Is there any way to do this, or is there an existing design pattern of some sort to do this correctly?

public abstract class BaseClass
{
    public class Settings
    {
        public const string BananaSetting = "BananaSetting";
    }

    public abstract void BaseAbstractMethod();
    public void BaseMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
    }
}

public class DerivedClass : BaseClass
{
    public class Settings
    {
        public const string DerivedBananaSetting = "DerivedBananaSetting";
    }

    public override void BaseAbstractMethod()
    {
        // intended use
        var settingValue = settingsDictionary[Settings.BananaSetting];
        var subSettingValue = settingsDictionary[Settings.DerivedBananaSetting];
    }
}

Body:
How about sth. like this:

public abstract class SettingBase
{
     public abstract string GetSettingName();

     public abstract SettingBase GetSetting();

     //Shared Properties and Stuff here:
}

public class BananaSetting : SettingBase
{
     public override string GetSettingName()
     {
         return nameof(BananaSetting);
     }

     public override SettingBase GetSetting()
     {
         return this;
     }

     //Banana-Specific Settings go here
}

public class DEBUGSetting : SettingBase
{
     public override string GetSettingName()
     {
         return nameof(DEBUGSetting);
     }

     public override SettingBase GetSetting()
     {
         return this;
     }

     //DEBUG-Specific Settings go here
}

public class Program
{
     public void Demo()
     {
         var settings = LoadSettings();
         foreach(var setting in settings)
         {
             var implementation = setting.GetSetting();
             if(implementation is DEBUGSetting dbg)
             {
                 //access dbg.Properties here
             }
             [...]
         }
     }
}


来源: stackexchange

问:
Tests for Flask Blueprint gives attributeerror
I'm writing tests for my application using unittest in Python3.6. I'm creating a simple Flask app for this test, that I want to register my defined blueprints with. The issue I get is when I try to import my blueprints is this one:

```<code>  File "/app/test/__init__.py", line 1, in <module>
    from . import test_views
  File "/app/test/test_views.py", line 50, in <module>
    from api.metrics.views import stats
  File "/app/api/metrics/__init__.py", line 1, in <module>
    from .views import stats
  File "/app/api/metrics/views.py", line 13, in <module>
    def get_stats(client=None):
  File "/testenv/lib/python3.6/site-packages/flask/blueprints.py", line 161, in decorator
    endpoint = options.pop("endpoint", f.__name__)
  File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py", line 584, in __getattr__
    raise AttributeError(name)
AttributeError: __name__
</code>```

The error comes where I call @stats.route... in this code:

```<code>stats = Blueprint('metrics', __name__)

@stats.route('/metrics', methods=['POST'])
@setup.require_suth
def get_metrics(client=None):
  <This code is not relevant>
</code>```

Does anyone know how to do this correctly? I really can't figure out how to do this.

This is my structure:

```<code>/app
  /api
     /metrics
       __init__.py
       views.py
  /test
       test_views.py
</code>```

And here is the import statement in my tests:

```<code>app_ = define_test_app()
from api.metrics.views import stats
app_.register_blueprint(stats)
</code>```

Would appreciate help, since I'm completely stuck at this point.

答:
Do NOT name the module, the directory and the blueprint with the same name.

Basically our code has this kind of constructs. subtree to make it simpler.

```<code>-- webcompat
   |-- __init__.py
   |-- form.py
   |-- api
   |   |-- __init__.py
   |   |-- uploads.py
   |   |-- endpoints.py
   …
   |-- helpers.py
   |-- views.py
</code>```

so in webcompat/__init__.py

from webcompat.api.endpoints import api
app = Flask(__name__, static_url_path='')
app.register_blueprint(api)
```

<p>and in <code>webcompat/api/endpoints/__init__.py</code></p>

<pre class="lang-py prettyprint-override"><code>from webcompat.helpers import cool_feature

api = Blueprint('api', __name__, url_prefix='/api')

@api.route('blah')
def somewhere(foo):
    """blablah"""
    yeah = cool_feature()
</code>```

So what is happening here?
The module and the blueprint share the same name. So if in a test we need to mock cool_feature:

with patch('webcompat.api.endpoints.cool_feature') as mock_cool:
```

<p>We need to remember that when mocking, we do not mock the feature where it has been defined (aka <code>webcompat.helpers.cool_feature</code>) but where it has been imported (aka <code>webcompat.api.endpoints.cool_feature</code>). We will not be able to mock in this case because there will be a conflict of names. The error will be:</p>

```E    AttributeError: 'Blueprint' object has no attribute 'endpoints'
```

because the named webcompat.api blueprint has no attribute endpoints while the module webcompat.api has one.

ContentLicense: CC BY-SA 4.0

Body:
I'm writing tests for my application using unittest in Python3.6. I'm creating a simple Flask app for this test, that I want to register my defined blueprints with. The issue I get is when I try to import my blueprints is this one:

  File "/app/test/__init__.py", line 1, in <module>
    from . import test_views
  File "/app/test/test_views.py", line 50, in <module>
    from api.metrics.views import stats
  File "/app/api/metrics/__init__.py", line 1, in <module>
    from .views import stats
  File "/app/api/metrics/views.py", line 13, in <module>
    def get_stats(client=None):
  File "/testenv/lib/python3.6/site-packages/flask/blueprints.py", line 161, in decorator
    endpoint = options.pop("endpoint", f.__name__)
  File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py", line 584, in __getattr__
    raise AttributeError(name)
AttributeError: __name__

The error comes where I call @stats.route... in this code:

stats = Blueprint('metrics', __name__)

@stats.route('/metrics', methods=['POST'])
@setup.require_suth
def get_metrics(client=None):
  <This code is not relevant>

Does anyone know how to do this correctly? I really can't figure out how to do this.

This is my structure:

/app
  /api
     /metrics
       __init__.py
       views.py
  /test
       test_views.py

And here is the import statement in my tests:

app_ = define_test_app()
from api.metrics.views import stats
app_.register_blueprint(stats)

Would appreciate help, since I'm completely stuck at this point.

Body:
Do NOT name the module, the directory and the blueprint with the same name.

Basically our code has this kind of constructs. subtree to make it simpler.

-- webcompat
   |-- __init__.py
   |-- form.py
   |-- api
   |   |-- __init__.py
   |   |-- uploads.py
   |   |-- endpoints.py
   …
   |-- helpers.py
   |-- views.py

so in webcompat/__init__.py

from webcompat.api.endpoints import api
app = Flask(__name__, static_url_path='')
app.register_blueprint(api)

and in webcompat/api/endpoints/__init__.py

from webcompat.helpers import cool_feature

api = Blueprint('api', __name__, url_prefix='/api')

@api.route('blah')
def somewhere(foo):
    """blablah"""
    yeah = cool_feature()

So what is happening here?
The module and the blueprint share the same name. So if in a test we need to mock cool_feature:

with patch('webcompat.api.endpoints.cool_feature') as mock_cool:

We need to remember that when mocking, we do not mock the feature where it has been defined (aka webcompat.helpers.cool_feature) but where it has been imported (aka webcompat.api.endpoints.cool_feature). We will not be able to mock in this case because there will be a conflict of names. The error will be:

E    AttributeError: 'Blueprint' object has no attribute 'endpoints'

because the named webcompat.api blueprint has no attribute endpoints while the module webcompat.api has one.


问:
I am getting wrong answer for prime path problem can anyone help me in finding the issue?
Problem Link: https://www.spoj.com/problems/PPATH/

Brief explanation of the problem,

```<code>1) Construct a graph with prime numbers between 1000 and 9999.
2) Add an undirected edge between two numbers 'a' and 'b', if they differ only by one digit.
EX: 1033 and 1733 differ only by one digit.
3) In that graph we need to find the length of the shortest path from the given source to the given destination.
</code>```

I have solved the above problem by constructing a graph using the prime number between 1000 and 9999, by connecting numbers that differ only by one digit. EX: 1033 and 1733 differ only by one digit.
I have used DFS along with memorisation to find the shortest path.
For some input i am getting wrong answer, 1 greater than the actual value, since there are 1000 nodes i can't able to figure out the issue. It will be so helpful if someone help me to figure out the issue.

I know this problem can be solved by BFS, but i need to know what's wrong with this problem.

test cases when the below program prints wrong answer

1

7573 9973

Actual answer : 4

My code output : 5

(I have found the actual answer by submitting a BFS approach to the problem and it got Accepted in SPOJ).

```<code>import java.util.*;
import java.lang.*;
import java.io.*;

class FireEscapeRoutes_FIRESC {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[] args) throws Exception{
        int t = 1;
        while (t--!=0){
            int source = 7573;
            int destination = 9973;
            List<Integer> fourDigitPrimeNos = new ArrayList<>();

            for(int i=1001;i<=9999;i++){
                if(isPrime(i)){
                    fourDigitPrimeNos.add(i);
                    //System.out.println(i);
                }
            }
            Graph graph = new Graph(fourDigitPrimeNos.size());
            /*
             If two number 'a' and 'b' differ only by one digit then an edge is added.
             */
            for (int i=0;i<fourDigitPrimeNos.size();i++){
                for (int j=i+1;j<fourDigitPrimeNos.size();j++){
                    if(isSingleDistnace(fourDigitPrimeNos.get(i),fourDigitPrimeNos.get(j))){
                        graph.add(fourDigitPrimeNos.get(i),fourDigitPrimeNos.get(j));
                    }
                }
            }
            //System.out.println(graph.graph);
            Long minPath = graph.getShortestPath(source,destination);
            if(minPath!=Long.MAX_VALUE){
                System.out.println(minPath);
            }else{
                System.out.println("Impossible");
            }

        }
    }

    static boolean isSingleDistnace(int a, int b){
        String as = a+"";
        String bs = b+"";
        int ds = 0;
        for (int i=0;i<as.length();i++){
            if(!(as.charAt(i)==bs.charAt(i))){
                if(ds>=1){
                    return false;
                }
                ds++;
            }
        }
        if(ds==0){
            return false;
        }
        return true;
    }
    static boolean isPrime(int n){
        for (int i=2;i<=Math.sqrt(n);i++){
            if(n%i==0){
                return false;
            }
        }
        return true;
    }
}

class Graph{
    int noOfVertices;
    HashMap<Integer,List<Integer>> graph;
    Graph(int v){
        noOfVertices = v;
        graph = new HashMap<Integer,List<Integer>>();
    }
    void add(int u,int v){
        if (!graph.containsKey(u)){
            graph.put(u,new ArrayList<>());
        }
        if(!graph.containsKey(v)){
            graph.put(v,new ArrayList<>());
        }
        graph.get(u).add(v);
        graph.get(v).add(u);
    }

    Long getShortestPath(int start, int dest){
        HashMap<Integer,Long> visitedVsMinCost = new HashMap<>();
        Long min = Long.MAX_VALUE;
        min = getShortestPathUtil(start,dest,visitedVsMinCost);
        return min-1;

    }

    Long getShortestPathUtil(Integer start,Integer dest,HashMap<Integer,Long> visitedVsMinCost){

        if(start.equals(dest)){
            return 1l;
        }
        visitedVsMinCost.put(start, Long.MAX_VALUE);
        List<Integer> frnds = graph.get(start);
        Long min = Long.MAX_VALUE;
        for (Integer iThFrind:frnds){
            if(!visitedVsMinCost.containsKey(iThFrind)){
                Long shortestPathUtil = getShortestPathUtil(iThFrind, dest, visitedVsMinCost);
                //System.out.println(shortestPathUtil + " min " + min);
                min = Math.min(min, shortestPathUtil);

            }else {
                if(!visitedVsMinCost.get(iThFrind).equals(Long.MAX_VALUE)) {
                    min = Math.min(min, visitedVsMinCost.get(iThFrind)+1);
                }
            }
        }
        visitedVsMinCost.put(start,min);
        //System.out.println(min);
        if (min.equals(Long.MAX_VALUE)){
            return min;
        }
        return min+1;

    }
}
</code>```

NOTE: This below Part is to explain why my code works on the situation mentioned by @c0der. Since i can't able to comment more characters i am editting this question. To understand approach you can use this below part.

I can understand it is difficult to debug the code, so i try to explain my approach using the graph mentioned by @coder answer and
above code work fine in the scenario you mentioned.

Start = 1 and destination= 5, shortest path = 2 (1->4->5)

1) if DFS traverses through `1->2->3->4->5' and reached the destination '5' it return '1' to the '4'th node.

2) now the '4'th node memorise the returned value '1'. (This means between 4 and 5, there is one node, including destination, excluding the source 4).

    2.1) Then it returns '2'(1+1) to the '3'rd node. and '3'rd node memorise the value '2'. (This means between 3rd node and destination(5) node , there is 2 node, in the shortest path. including destination, excluding source 3

3) similiarly call will go back to '1'.

4) then '1'st node, calls '4'th node and see it is visited before, so it takes the memorized value of '4' th node which is '1' and it returns '2' to '1'.

答:
Debugging of the code posted is a long task.

However DFS is not the right tool for the job.
To visualize why DFS is not a good tool to find the shortest path consider the following simple graph:

If DSF happens to start by traversing nodes 1->2->3->4->5 the shortest path 1->4->5

will not be traversed because 4 is marked as visited.

This may be the reason why DFS along with memorisation is unable to find the shortest path.

Edit:
The following is a modified version of your code: it returns the actual shortest path found, if any.

This may help in debugging.

If finds the shortest path by performing DFS to traverse all possible paths and keeping the shortest one.

It is not optimized in the sense that if there are loops in the graph it may recalculate a path that has already been calculated before. You may want to add memorization of calculated pathes to make it more efficient.

```<code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

class FireEscapeRoutes_FIRESC {

    public static void main(String[] args) throws Exception{

        List<Integer> fourDigitPrimeNos = new ArrayList<>();

        for(int i=1001; i<=9999; i++){
            if(isPrime(i)){
                fourDigitPrimeNos.add(i);
            }
        }

        Graph graph = new Graph();
        /*
             If two number 'a' and 'b' differ only by one digit then an edge is added.
         */
        for (int i=0;i<fourDigitPrimeNos.size();i++){
            for (int j=i+1;j<fourDigitPrimeNos.size();j++){
                if(isSingleDistnace(fourDigitPrimeNos.get(i),fourDigitPrimeNos.get(j))){
                    graph.add(fourDigitPrimeNos.get(i),fourDigitPrimeNos.get(j));
                }
            }
        }

        int source = 1033;
        int destination = 8179;  //expected 6 : 1033  1733  3733  3739  3779  8779  8179

        /* more test cases
        int source = 7573;
        int destination = 9973; //expected 5

        int source = 1373;
        int destination = 8017; //expected 7

        int source = 1033;
        int destination = 1033; //expected 1
        */
        List<Integer> shortestPath = graph.getShortestPath(source,destination);

        if(shortestPath != null){
            System.out.println("\nPath Found :"+ shortestPath);
            System.out.println("Path length: "+shortestPath.size());
        }else{
            System.out.println("Impossible");
        }
    }

    static boolean isSingleDistnace(int a, int b){
        String as = a+"";
        String bs = b+"";
        int ds = 0;
        for (int i=0;i<as.length();i++){
            if(!(as.charAt(i)==bs.charAt(i))){
                if(ds>=1)
                    return false;
                ds++;
            }
        }
        if(ds==0)   return false;

        return true;
    }

    static boolean isPrime(int n){

        if (n <= 1) return false; //make sure it is positive

        for (int i=2;i<=Math.sqrt(n);i++){
            if(n%i==0)
                return false;
        }
        return true;
    }
}

class Graph{

    private final HashMap<Integer,List<Integer>> graph;
    //measure time and print out some progress indication
    private static long startTime, printime;
    private static long HEART_BEAT = 15000;

    Graph(){
        graph = new HashMap<>();
    }

    void add(int u,int v){
        if (!graph.containsKey(u)){
            graph.put(u,new ArrayList<>());
        }
        if(!graph.containsKey(v)){
            graph.put(v,new ArrayList<>());
        }
        graph.get(u).add(v);
        graph.get(v).add(u);
    }

    List<Integer> getShortestPath(int start, int dest){

        System.out.print("Working ");
        startTime = System.currentTimeMillis();

        List<Integer> path = new ArrayList<>();
        path = getShortestPathUtil(start,dest, Integer.MAX_VALUE, path);

        System.out.println("\n run time in minutes " + (double) (System.currentTimeMillis() - startTime) /60000);
        return path;
    }

    List<Integer> getShortestPathUtil(int start,int dest,int minLengthFound, List<Integer> path){

        if(System.currentTimeMillis() - printime >= HEART_BEAT ){
            System.out.print(".");
            printime = System.currentTimeMillis();
        }

        if(path.contains(start)) return null; //prevent loops

        path.add(start);
        if(start == dest) return path;
        //stop traverse if path is longer than the shortest one found earlier
        if(minLengthFound != Integer.MAX_VALUE && path.size() >= minLengthFound) return null;

        List <Integer> keepShortestPathFound = null;
        for (int neighbor : graph.get(start)){

            if(path.contains(neighbor)) {
                continue;
            }

            List<Integer> shortestPathFromNeighbor = getShortestPathUtil(neighbor, dest, minLengthFound, new ArrayList<>(path));
            if(shortestPathFromNeighbor != null && shortestPathFromNeighbor.contains(dest) &&
                    shortestPathFromNeighbor.size() < minLengthFound){
                keepShortestPathFound = shortestPathFromNeighbor;
                minLengthFound = shortestPathFromNeighbor.size();
            }
        }

        return keepShortestPathFound;
    }
}
</code>```

Body:
Problem Link: https://www.spoj.com/problems/PPATH/

Brief explanation of the problem,

1) Construct a graph with prime numbers between 1000 and 9999.
2) Add an undirected edge between two numbers 'a' and 'b', if they differ only by one digit.
EX: 1033 and 1733 differ only by one digit.
3) In that graph we need to find the length of the shortest path from the given source to the given destination.

I have solved the above problem by constructing a graph using the prime number between 1000 and 9999, by connecting numbers that differ only by one digit. EX: 1033 and 1733 differ only by one digit.
I have used DFS along with memorisation to find the shortest path.
For some input i am getting wrong answer, 1 greater than the actual value, since there are 1000 nodes i can't able to figure out the issue. It will be so helpful if someone help me to figure out the issue.

I know this problem can be solved by BFS, but i need to know what's wrong with this problem.

test cases when the below program prints wrong answer

1

7573 9973

Actual answer : 4

My code output : 5

(I have found the actual answer by submitting a BFS approach to the problem and it got Accepted in SPOJ).

import java.util.*;
import java.lang.*;
import java.io.*;

class FireEscapeRoutes_FIRESC {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[] args) throws Exception{
        int t = 1;
        while (t--!=0){
            int source = 7573;
            int destination = 9973;
            List<Integer> fourDigitPrimeNos = new ArrayList<>();

            for(int i=1001;i<=9999;i++){
                if(isPrime(i)){
                    fourDigitPrimeNos.add(i);
                    //System.out.println(i);
                }
            }
            Graph graph = new Graph(fourDigitPrimeNos.size());
            /*
             If two number 'a' and 'b' differ only by one digit then an edge is added.
             */
            for (int i=0;i<fourDigitPrimeNos.size();i++){
                for (int j=i+1;j<fourDigitPrimeNos.size();j++){
                    if(isSingleDistnace(fourDigitPrimeNos.get(i),fourDigitPrimeNos.get(j))){
                        graph.add(fourDigitPrimeNos.get(i),fourDigitPrimeNos.get(j));
                    }
                }
            }
            //System.out.println(graph.graph);
            Long minPath = graph.getShortestPath(source,destination);
            if(minPath!=Long.MAX_VALUE){
                System.out.println(minPath);
            }else{
                System.out.println("Impossible");
            }

        }
    }

    static boolean isSingleDistnace(int a, int b){
        String as = a+"";
        String bs = b+"";
        int ds = 0;
        for (int i=0;i<as.length();i++){
            if(!(as.charAt(i)==bs.charAt(i))){
                if(ds>=1){
                    return false;
                }
                ds++;
            }
        }
        if(ds==0){
            return false;
        }
        return true;
    }
    static boolean isPrime(int n){
        for (int i=2;i<=Math.sqrt(n);i++){
            if(n%i==0){
                return false;
            }
        }
        return true;
    }
}

class Graph{
    int noOfVertices;
    HashMap<Integer,List<Integer>> graph;
    Graph(int v){
        noOfVertices = v;
        graph = new HashMap<Integer,List<Integer>>();
    }
    void add(int u,int v){
        if (!graph.containsKey(u)){
            graph.put(u,new ArrayList<>());
        }
        if(!graph.containsKey(v)){
            graph.put(v,new ArrayList<>());
        }
        graph.get(u).add(v);
        graph.get(v).add(u);
    }

    Long getShortestPath(int start, int dest){
        HashMap<Integer,Long> visitedVsMinCost = new HashMap<>();
        Long min = Long.MAX_VALUE;
        min = getShortestPathUtil(start,dest,visitedVsMinCost);
        return min-1;

    }

    Long getShortestPathUtil(Integer start,Integer dest,HashMap<Integer,Long> visitedVsMinCost){

        if(start.equals(dest)){
            return 1l;
        }
        visitedVsMinCost.put(start, Long.MAX_VALUE);
        List<Integer> frnds = graph.get(start);
        Long min = Long.MAX_VALUE;
        for (Integer iThFrind:frnds){
            if(!visitedVsMinCost.containsKey(iThFrind)){
                Long shortestPathUtil = getShortestPathUtil(iThFrind, dest, visitedVsMinCost);
                //System.out.println(shortestPathUtil + " min " + min);
                min = Math.min(min, shortestPathUtil);

            }else {
                if(!visitedVsMinCost.get(iThFrind).equals(Long.MAX_VALUE)) {
                    min = Math.min(min, visitedVsMinCost.get(iThFrind)+1);
                }
            }
        }
        visitedVsMinCost.put(start,min);
        //System.out.println(min);
        if (min.equals(Long.MAX_VALUE)){
            return min;
        }
        return min+1;

    }
}

NOTE: This below Part is to explain why my code works on the situation mentioned by @c0der. Since i can't able to comment more characters i am editting this question. To understand approach you can use this below part.

I can understand it is difficult to debug the code, so i try to explain my approach using the graph mentioned by @coder answer and
above code work fine in the scenario you mentioned.

Start = 1 and destination= 5, shortest path = 2 (1->4->5)

1) if DFS traverses through `1->2->3->4->5' and reached the destination '5' it return '1' to the '4'th node.

2) now the '4'th node memorise the returned value '1'. (This means between 4 and 5, there is one node, including destination, excluding the source 4).

    2.1) Then it returns '2'(1+1) to the '3'rd node. and '3'rd node memorise the value '2'. (This means between 3rd node and destination(5) node , there is 2 node, in the shortest path. including destination, excluding source 3

3) similiarly call will go back to '1'.

4) then '1'st node, calls '4'th node and see it is visited before, so it takes the memorized value of '4' th node which is '1' and it returns '2' to '1'.

Body:
Debugging of the code posted is a long task.

However DFS is not the right tool for the job.
To visualize why DFS is not a good tool to find the shortest path consider the following simple graph:

If DSF happens to start by traversing nodes 1->2->3->4->5 the shortest path 1->4->5

will not be traversed because 4 is marked as visited.

This may be the reason why DFS along with memorisation is unable to find the shortest path.

Edit:
The following is a modified version of your code: it returns the actual shortest path found, if any.

This may help in debugging.

If finds the shortest path by performing DFS to traverse all possible paths and keeping the shortest one.

It is not optimized in the sense that if there are loops in the graph it may recalculate a path that has already been calculated before. You may want to add memorization of calculated pathes to make it more efficient.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

class FireEscapeRoutes_FIRESC {

    public static void main(String[] args) throws Exception{

        List<Integer> fourDigitPrimeNos = new ArrayList<>();

        for(int i=1001; i<=9999; i++){
            if(isPrime(i)){
                fourDigitPrimeNos.add(i);
            }
        }

        Graph graph = new Graph();
        /*
             If two number 'a' and 'b' differ only by one digit then an edge is added.
         */
        for (int i=0;i<fourDigitPrimeNos.size();i++){
            for (int j=i+1;j<fourDigitPrimeNos.size();j++){
                if(isSingleDistnace(fourDigitPrimeNos.get(i),fourDigitPrimeNos.get(j))){
                    graph.add(fourDigitPrimeNos.get(i),fourDigitPrimeNos.get(j));
                }
            }
        }

        int source = 1033;
        int destination = 8179;  //expected 6 : 1033  1733  3733  3739  3779  8779  8179

        /* more test cases
        int source = 7573;
        int destination = 9973; //expected 5

        int source = 1373;
        int destination = 8017; //expected 7

        int source = 1033;
        int destination = 1033; //expected 1
        */
        List<Integer> shortestPath = graph.getShortestPath(source,destination);

        if(shortestPath != null){
            System.out.println("\nPath Found :"+ shortestPath);
            System.out.println("Path length: "+shortestPath.size());
        }else{
            System.out.println("Impossible");
        }
    }

    static boolean isSingleDistnace(int a, int b){
        String as = a+"";
        String bs = b+"";
        int ds = 0;
        for (int i=0;i<as.length();i++){
            if(!(as.charAt(i)==bs.charAt(i))){
                if(ds>=1)
                    return false;
                ds++;
            }
        }
        if(ds==0)   return false;

        return true;
    }

    static boolean isPrime(int n){

        if (n <= 1) return false; //make sure it is positive

        for (int i=2;i<=Math.sqrt(n);i++){
            if(n%i==0)
                return false;
        }
        return true;
    }
}

class Graph{

    private final HashMap<Integer,List<Integer>> graph;
    //measure time and print out some progress indication
    private static long startTime, printime;
    private static long HEART_BEAT = 15000;

    Graph(){
        graph = new HashMap<>();
    }

    void add(int u,int v){
        if (!graph.containsKey(u)){
            graph.put(u,new ArrayList<>());
        }
        if(!graph.containsKey(v)){
            graph.put(v,new ArrayList<>());
        }
        graph.get(u).add(v);
        graph.get(v).add(u);
    }

    List<Integer> getShortestPath(int start, int dest){

        System.out.print("Working ");
        startTime = System.currentTimeMillis();

        List<Integer> path = new ArrayList<>();
        path = getShortestPathUtil(start,dest, Integer.MAX_VALUE, path);

        System.out.println("\n run time in minutes " + (double) (System.currentTimeMillis() - startTime) /60000);
        return path;
    }

    List<Integer> getShortestPathUtil(int start,int dest,int minLengthFound, List<Integer> path){

        if(System.currentTimeMillis() - printime >= HEART_BEAT ){
            System.out.print(".");
            printime = System.currentTimeMillis();
        }

        if(path.contains(start)) return null; //prevent loops

        path.add(start);
        if(start == dest) return path;
        //stop traverse if path is longer than the shortest one found earlier
        if(minLengthFound != Integer.MAX_VALUE && path.size() >= minLengthFound) return null;

        List <Integer> keepShortestPathFound = null;
        for (int neighbor : graph.get(start)){

            if(path.contains(neighbor)) {
                continue;
            }

            List<Integer> shortestPathFromNeighbor = getShortestPathUtil(neighbor, dest, minLengthFound, new ArrayList<>(path));
            if(shortestPathFromNeighbor != null && shortestPathFromNeighbor.contains(dest) &&
                    shortestPathFromNeighbor.size() < minLengthFound){
                keepShortestPathFound = shortestPathFromNeighbor;
                minLengthFound = shortestPathFromNeighbor.size();
            }
        }

        return keepShortestPathFound;
    }
}


问:
rails model validation error on view does not render properly
i am using a status radio_button field on form, and when i add validate :status, presence: true error message on form doesn't render properly it makes form view weired. Is there any solution i can render status error better?

i have added screenshot look at status field it was inline but after error i get status field in open upon other.

```<code><div class="row">
  <div class="field columns large-6">
    <%= form.label :status %>
    <span>
    <%= form.radio_button :status, "1"  %>
    <%= form.label :completed %>
    </span>
    <span>
    <%= form.radio_button :status, "0"  %>
    <%= form.label :inprogess %>
    </span>
    <span>
    <%= form.radio_button :status, "2"  %>
    <%= form.label :yet_to_start %>
    </span>
  </div>
  <div class="field columns large-6"></div>
</div>
</code>```

答:
Try this, add the following piece of code to your application.rb file

```<code>config.action_view.field_error_proc = Proc.new { |html_tag, instance| html_tag }
</code>```

or you can try making the fields inline by adding this css

```<code>.fields_with_error{ display: inline }
</code>```

It will stop wrapping fields with errors with divs and that might solve your problem. Worth giving a try.

Body:
i am using a status radio_button field on form, and when i add validate :status, presence: true error message on form doesn't render properly it makes form view weired. Is there any solution i can render status error better?

i have added screenshot look at status field it was inline but after error i get status field in open upon other.

    <%= form.label :status %>

    <%= form.radio_button :status, "1"  %>
    <%= form.label :completed %>

    <%= form.radio_button :status, "0"  %>
    <%= form.label :inprogess %>

    <%= form.radio_button :status, "2"  %>
    <%= form.label :yet_to_start %>

Body:
Try this, add the following piece of code to your application.rb file

config.action_view.field_error_proc = Proc.new { |html_tag, instance| html_tag }

or you can try making the fields inline by adding this css

.fields_with_error{ display: inline }

It will stop wrapping fields with errors with divs and that might solve your problem. Worth giving a try.


问:
Celery execute tasks in the order they get called (during runtime)
I have a task consisting of subtasks in a chain. How can I ensure a second call of this task does not start before the first one has finished?

```<code>@shared_task
def task(user):
    res = chain(subtask_1.s(), # each subtask takes ~1 hour
            subtask_2.s(),
            subtask_3.s())

    return res.apply_async()
</code>```

A django view might now trigger to call this task:

```<code># user A visits page that triggers task
task.delay(userA)
# 10 seconds later, while task() is still executing, user B visits page
task.delay(userB)
</code>```

This leads to the tasks racing each other instead of being executed in sequential order. E.g. once a worker has finished with subtask_1() of the first task, it begins working on subtask_1() of the second task, instead of subtask_2() and subtask_3() of the first one.

Is there a way to elegently avoid this? I guess the problem is the order the subtasks get added to the queue.

I have already set worker --concurreny=1, however that still doesn't change the order he consumes from the queue.

Official docs (task cookbook) seem to offer a solution which I don't understand and doesn't work for me unfortunately.

Perhaps include a blocking mechanism within the task, after the chain, with a while not res.ready(): sleep(1) kind of hack?

答:
You can wait for first task to finish and then execute second one like this.

```<code>res = task.delay(userA)
res.get() # will block until finished
task.delay(userB)
</code>```

But it will block the calling thread until first one finished. You can chain tasks to avoid blocking, but for that you have to modify task signature a little to accept task result as argument.

```<code>@shared_task
def task(_, user): signature takes one extra argument
    # skipped
</code>```

and

```<code>from celery.canvas import chain

chain(task.s(None, userA), task.s(userB))()
</code>```

Body:
I have a task consisting of subtasks in a chain. How can I ensure a second call of this task does not start before the first one has finished?

@shared_task
def task(user):
    res = chain(subtask_1.s(), # each subtask takes ~1 hour
            subtask_2.s(),
            subtask_3.s())

    return res.apply_async()

A django view might now trigger to call this task:

# user A visits page that triggers task
task.delay(userA)
# 10 seconds later, while task() is still executing, user B visits page
task.delay(userB)

This leads to the tasks racing each other instead of being executed in sequential order. E.g. once a worker has finished with subtask_1() of the first task, it begins working on subtask_1() of the second task, instead of subtask_2() and subtask_3() of the first one.

Is there a way to elegently avoid this? I guess the problem is the order the subtasks get added to the queue.

I have already set worker --concurreny=1, however that still doesn't change the order he consumes from the queue.

Official docs (task cookbook) seem to offer a solution which I don't understand and doesn't work for me unfortunately.

Perhaps include a blocking mechanism within the task, after the chain, with a while not res.ready(): sleep(1) kind of hack?

Body:
You can wait for first task to finish and then execute second one like this.

res = task.delay(userA)
res.get() # will block until finished
task.delay(userB)

But it will block the calling thread until first one finished. You can chain tasks to avoid blocking, but for that you have to modify task signature a little to accept task result as argument.

@shared_task
def task(_, user): signature takes one extra argument
    # skipped

and

from celery.canvas import chain

chain(task.s(None, userA), task.s(userB))()


问:
ByteBuddy create class from created class
I have an interface with some methods (unknown count).

I want to create another interface with methods, which will have same name and parameter types, but not return types.

Then, I want use second created interface for create a new class by byteBuddy. But when I use the created interface for creating a new one, I get

IllegalStateException: Could not locate class file for
  SecondInterface.

example code:

```<code>Class<?> clazz
= new ByteBuddy()
    .makeInterface()
    .name("secondInterface")
    .make()
    .load(classLoader)
    .getLoaded();

for (Method method : FirstInterface.class.getMethods()) {

    Class<?>[] classes = method.getParameterTypes();
    List<Class<?>> classList = new ArrayList<Class<?>>(Arrays.asList(classes));
    classList.add(Object.class);

    clazz
    = new ByteBuddy()
        .rebase(clazz)
        .defineMethod(method.getName() + "Reverse", Void.class, Modifier.PUBLIC)
        .withParameters(classList)
        .withoutCode()
        .make()
        .load(classLoader)
        .getLoaded();
}
</code>```

What am I doing wrong? Is byteBuddy allowed to create a class from a another which was just created?

答:
If you are rebasing a class, you are editing its already existing class file where all existing methods are retained. Is this really what you are trying to do here? I'd rather define a new interface and add the methods to it, then you will neither run into the exception.

The reason you are seeing this error is that you are loading the interface using a class loader that does not retain the original byte code as a resource what is required for future editing. Provide ClassLoadingStrategy.Default.WRAPPER_PERSISTENT as a second argument to load and you will get around it.

Body:
I have an interface with some methods (unknown count).

I want to create another interface with methods, which will have same name and parameter types, but not return types.

Then, I want use second created interface for create a new class by byteBuddy. But when I use the created interface for creating a new one, I get

IllegalStateException: Could not locate class file for
  SecondInterface.

example code:

Class<?> clazz
= new ByteBuddy()
    .makeInterface()
    .name("secondInterface")
    .make()
    .load(classLoader)
    .getLoaded();

for (Method method : FirstInterface.class.getMethods()) {

    Class<?>[] classes = method.getParameterTypes();
    List<Class<?>> classList = new ArrayList<Class<?>>(Arrays.asList(classes));
    classList.add(Object.class);

    clazz
    = new ByteBuddy()
        .rebase(clazz)
        .defineMethod(method.getName() + "Reverse", Void.class, Modifier.PUBLIC)
        .withParameters(classList)
        .withoutCode()
        .make()
        .load(classLoader)
        .getLoaded();
}

What am I doing wrong? Is byteBuddy allowed to create a class from a another which was just created?


问:
Data from Realtime Firebase is displaying in console but not in html page
Component.ts

plats is the root node of my Firebase database,I want to display every child of my root node in
angular page.The data is displayed in console but not in angular page. Thank you for your helps in
advance.

```<code>    itemValue = '';
    name: string;
    plats: Observable<any[]>;
    itemRef: AngularFireObject<any>;

    constructor(public db: AngularFireDatabase)
    {
    this.itemRef = db.object('plats');
    this.itemRef.snapshotChanges().subscribe(action => {
    const data = action.payload.val();
    console.log(action.payload.val());
    return { ...data };
    });

 }
</code>```

component.html

```<code>    <div class="container">
      <table>
        <tr>
          <th>Community</th>
        </tr>
       <tr *ngFor="let item of plats | async">
          <td>{{item}}</td>
      </tr>
     </table>
   </div>
</code>```

答:
Try this:</p>

```<code>this.itemRef = db.object('plats');
this.plats = this.itemRef.snapshotChanges().map(items => {
  return items.map(val => {
    const data = val.payload.doc.data();
    const id = val.payload.doc.id;
    return { id, ...data };
});
</code>```

Body:
Component.ts

plats is the root node of my Firebase database,I want to display every child of my root node in
angular page.The data is displayed in console but not in angular page. Thank you for your helps in
advance.

    itemValue = '';
    name: string;
    plats: Observable<any[]>;
    itemRef: AngularFireObject<any>;

    constructor(public db: AngularFireDatabase)
    {
    this.itemRef = db.object('plats');
    this.itemRef.snapshotChanges().subscribe(action => {
    const data = action.payload.val();
    console.log(action.payload.val());
    return { ...data };
    });

 }

component.html

          Community

          {{item}}

Body:
Try this:

this.itemRef = db.object('plats');
this.plats = this.itemRef.snapshotChanges().map(items => {
  return items.map(val => {
    const data = val.payload.doc.data();
    const id = val.payload.doc.id;
    return { id, ...data };
});


问:
I don't know how to solve this error [client is not defined]
ReferenceError: client is not defined
    at Object. (C:\Users\Utilizador\Desktop\securitybot\bot.js:3:1)

```<code>at Module._compile (internal/modules/cjs/loader.js:1157:30)

at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)

at Module.load (internal/modules/cjs/loader.js:1001:32)

at Function.Module._load (internal/modules/cjs/loader.js:900:14)

at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
</code>```

PS C:\Users\Utilizador\Desktop\securitybot>

答:
Add the below to the top of the file.

const Discord = require('discord.js');
const client = new Discord.Client();
```

If you have already defined discord.js don't define it again.

Also, it could be a small chance that your client variable is named bot, some people use bot instead of client as the variable. Check at the top of your file and see if you have a different name.

Body:
ReferenceError: client is not defined
    at Object. (C:\Users\Utilizador\Desktop\securitybot\bot.js:3:1)

at Module._compile (internal/modules/cjs/loader.js:1157:30)

at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)

at Module.load (internal/modules/cjs/loader.js:1001:32)

at Function.Module._load (internal/modules/cjs/loader.js:900:14)

at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47

PS C:\Users\Utilizador\Desktop\securitybot>

Body:
Add the below to the top of the file.

const Discord = require('discord.js');
const client = new Discord.Client();

If you have already defined discord.js don't define it again.

Also, it could be a small chance that your client variable is named bot, some people use bot instead of client as the variable. Check at the top of your file and see if you have a different name.


问:
Missing page numbers in the indicies of Doxygen generated PDF
I'm using Doxygen 1.8.5 and I have an issue with the generated indicies (Module Index, Data Structure Index, File Index etc.).
When I generate the PDF documentation with Doxygen extra indicies chapters "Module Index", "Data Structure Index" and "File Index" are generated. Unfortunately the page numbers in that indicies are not generated correctly, so that a "??" is shown instead of the page number, similar like this:

Chapter 5

File Index

5.1 File List

Here is a list of all files with brief descriptions:

bar.c  Doxygen C-file Example . . . . . . . . . . . . . . . . . . . ??

bar.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ??

foo.c Doxygen C-file Example . . . . . . . . . . . . . . . . . . .  ??

foo.h Doxygen H-file Example . . . . . . . . . . . . . . . . . . .  ??

Has anyone an idea what I'm doing wrong?

答:
I was able to solve this problem by using MiKTeX / pdflatex: I execute pdflatex refman via command line in the folder latex/output/doxygen. After two using the command finally managed to get the page number :3

Screenshot before

Screenshot afterwards:

if you try still can't. try installing all the Requirement files

Ghostscript

HTML Help Workshop and Documentation

GraphViz

MikTex (LaTeX)

TexMaker – LaTeX Editor

ContentLicense: CC BY-SA 3.0


问:
What unix command can we use to append some text to a specific line in a file?
Does anyone know of a series of unix commands that allows someone to append some text to the end of a specific line in a file?

eg

Line 1

Line 2

Line 3

Line 4

I wish to append the text ", extra information" to Line 3 so that the File will now look like this:

Line 1

Line 2

Line 3, extra information

Line 4

答:
in awk it's:

```<code>awk '{s=$0; if( NR==3 ){ s=s ", Extra Information" } print s;}' myfile > newfile
</code>```

proper sed version:

```<code>sed -e '3s/$/, Extra Information/' -i myfile
</code>```

OwnerDisplayName: Alex Wong

ContentLicense: CC BY-SA 2.5

Body:
in awk it's:

awk '{s=$0; if( NR==3 ){ s=s ", Extra Information" } print s;}' myfile > newfile

proper sed version:

sed -e '3s/$/, Extra Information/' -i myfile

OwnerDisplayName: sfossen

LastEditorDisplayName: sfossen


问:
Syncing a random variable in ruby
I am making a simple Tic tac toe game where the rows are represented by three arrays and columns are items in those arrays. For my computer choice I use two separate functions to get the row and column.

```<code>$first = ["-","-","-"]
$secound = ["-","-","-"]
$third = ["-","-","-"]
def get_row
    row = nil
    case rand(3)
    when 0
        row = $first
    when 1
        row = $secound
    else
        row = $third
    end
    row
end
def get_col
    col = nil
    case rand(3)
    when 0
        col = 0
    when 1
        col = 1
    else
        col = 2
    end
    col
end
</code>```

I then use a third function that keeps generating a new "guess" until it finds an empty spot, at which point it marks an 0.

```<code>def computer_guess
    temp = false
    try = get_row[get_col]
    while temp == false
        if try == "-"
           get_row[get_col] = "O"
            temp = true
        else
            try = get_row[get_col]
        end
    end
end
</code>```

My problem is that i cant return the guess to the same position that i check for validity. Is the there a way to sync these or do i need a different approach?

答:
when there is only one available spot, it might take time to guess it.

So it might be better to collate the available spots and get a random value from there:

```<code>def computer_guess
  free_spots=[]
  free_spots.concat($first.each_with_index.map{|x,i|x=='-' ? ['$first',i] : nil}.compact)
  free_spots.concat($secound.each_with_index.map{|x,i|x=='-' ? ['$secound',i] : nil}.compact)
  free_spots.concat($third.each_with_index.map{|x,i|x=='-' ? ['$third',i] : nil}.compact)
  try=free_spots.sample
  eval"#{try[0]}[#{try[1]}]='O'" unless try.nil?
end
</code>```

Title: Syncing a random variable in ruby

Body:
I am making a simple Tic tac toe game where the rows are represented by three arrays and columns are items in those arrays. For my computer choice I use two separate functions to get the row and column.

$first = ["-","-","-"]
$secound = ["-","-","-"]
$third = ["-","-","-"]
def get_row
    row = nil
    case rand(3)
    when 0
        row = $first
    when 1
        row = $secound
    else
        row = $third
    end
    row
end
def get_col
    col = nil
    case rand(3)
    when 0
        col = 0
    when 1
        col = 1
    else
        col = 2
    end
    col
end

I then use a third function that keeps generating a new "guess" until it finds an empty spot, at which point it marks an 0.

def computer_guess
    temp = false
    try = get_row[get_col]
    while temp == false
        if try == "-"
           get_row[get_col] = "O"
            temp = true
        else
            try = get_row[get_col]
        end
    end
end

My problem is that i cant return the guess to the same position that i check for validity. Is the there a way to sync these or do i need a different approach?

Body:
when there is only one available spot, it might take time to guess it.

So it might be better to collate the available spots and get a random value from there:

def computer_guess
  free_spots=[]
  free_spots.concat($first.each_with_index.map{|x,i|x=='-' ? ['$first',i] : nil}.compact)
  free_spots.concat($secound.each_with_index.map{|x,i|x=='-' ? ['$secound',i] : nil}.compact)
  free_spots.concat($third.each_with_index.map{|x,i|x=='-' ? ['$third',i] : nil}.compact)
  try=free_spots.sample
  eval"#{try[0]}[#{try[1]}]='O'" unless try.nil?
end


问:
Constructore for derived class if base class contain double pointer member
I am using double pointer member in base class. but in derived class constructor I am getting error

error: no matching function for call to ‘Layer::Layer(tensor&, float&)’
                       :Layer(**tn, **input)

```<code>// base class
class Layer
{
    protected:
        struct tensor **tensor_node;
        float **tensor_input_activation;

    public:

        /*  ***Constructor*** */
        Layer(struct tensor **, float **);
};

Layer::Layer(struct tensor **tn, float **input)
{
    *tensor_node = *tn;
    *tensor_input_activation = *input;
}

// derived class from Layer
class BatchNormalization : public Layer
{
    string layer_name;

    public:
        /* ***Constructor*** */
        BatchNormalization(struct tensor **, float **, string);

        /* ***Member_function*** */
        float* batch_normalization_operation_function();
};

BatchNormalization::BatchNormalization(struct tensor **tn, float **input, string l_name)
                    :Layer(**tn, **input)
{
    layer_name = l_name;
}
</code>```

How can resolve this problem? How can we define constructors if the base class contains double-pointer member?

答:
You pass Layer(tn, input). But before you do that you should fix Layer::Layer to stop dereferencing invalid pointers.

```<code>Layer::Layer(tensor **tn, float **input)
   : tensor_node(tn), tensor_input_activation(input)
{}

BatchNormalization::BatchNormalization(tensor **tn, float **input, string l_name)
   : Layer(tn, input), layer_name(l_name)
{}
</code>```

Body:
I am using double pointer member in base class. but in derived class constructor I am getting error

error: no matching function for call to ‘Layer::Layer(tensor&, float&)’
                       :Layer(**tn, **input)

// base class
class Layer
{
    protected:
        struct tensor **tensor_node;
        float **tensor_input_activation;

    public:

        /*  ***Constructor*** */
        Layer(struct tensor **, float **);
};

Layer::Layer(struct tensor **tn, float **input)
{
    *tensor_node = *tn;
    *tensor_input_activation = *input;
}

// derived class from Layer
class BatchNormalization : public Layer
{
    string layer_name;

    public:
        /* ***Constructor*** */
        BatchNormalization(struct tensor **, float **, string);

        /* ***Member_function*** */
        float* batch_normalization_operation_function();
};

BatchNormalization::BatchNormalization(struct tensor **tn, float **input, string l_name)
                    :Layer(**tn, **input)
{
    layer_name = l_name;
}

How can resolve this problem? How can we define constructors if the base class contains double-pointer member?

Body:
You pass Layer(tn, input). But before you do that you should fix Layer::Layer to stop dereferencing invalid pointers.

Layer::Layer(tensor **tn, float **input)
   : tensor_node(tn), tensor_input_activation(input)
{}

BatchNormalization::BatchNormalization(tensor **tn, float **input, string l_name)
   : Layer(tn, input), layer_name(l_name)
{}


问:
Laravel - How to Approve all the posts of a particular Employee
Using Laravel-5.8, I have written a code for post of employees and it is working perfectly:

Controller

```<code>public function index()
{
    $userEmployee = Auth::user()->employee_id;
    $posts = Post::latest()->where('employee_id', $userEmployee)->get();

    return view('admin.post.index', compact('posts'));
}
</code>```

And it generates this view shown below. The view loads all the unapproved posts for a particular employee:

```<code><table class="table table-bordered table-striped table-hover dataTable js-exportable">
  <thead>
    <tr>
      <th>ID</th>
      <th>Title</th>
      <th>Author</th>
      <th><i class="material-icons">visibility</i></th>
      <th>Is Approved</th>
      <th>Status</th>
      <th>Action</th>
   </tr>
  </thead>
  <tbody>
    @foreach($posts as $key=>$post)
     <tr>
       <td>{{ $key + 1 }}</td>
       <td>{{ str_limit($post->title,'10') }}</td>
       <td>{{ $post->user->name }}</td>
       <td>{{ $post->view_count }}</td>
       <td>
         @if($post->is_approved == true)
            <span class="badge bg-blue">Approved</span>
         @else
            <span class="badge bg-pink">Pending</span>
         @endif
       </td>
       <td>
          @if($post->status == true)
             <span class="badge bg-blue">Published</span>
          @else
             <span class="badge bg-pink">Pending</span>
          @endif
        </td>
       </tr>
         @endforeach
  </tbody>
</code>```

```<code><form action="{{route('admin.post.approve', $post->id)}}" method="POST" enctype="multipart/form-data">
    @csrf
    @method('PUT')
    <div>
        <button type="submit" class="btn btn-primary"><i class="fas fa-arrow-right"></i> {{ trans('global.submit') }}</button>
    </div>
</form>
</code>```

I want to add a submit button to the view called approve. Once the button is clicked, it checks where is_approved is = 0 for the loaded employee and turns all the is_approved that relates to the employee (the loaded) data to 1.

I have written this function in the same controller, but I see that it will only work for a selected row:

```<code>public function approve($id){

    $post = Post::find($id);
    if ($post->is_approved == false){
        $post->is_approved = true;
        $post->save();
        $post->user->notify(new AuthorPostApprove($post));

        Toastr::success('Post Successfully Approved');
    }else{
        Toastr::info('Post is already Approved');
    }

    return redirect()->back();
}
</code>```

and have this route/web.php

```<code>Route::get('posts/', 'PostController@index')->name('post.index');
Route::put('/post/{id}/approve', 'PostController@approve')->name('post.approve');
</code>```

How do I re-write my Controller, view and route to achieve this?

Thank you.

答:
Ok I do something like below

All you need to do is that when user click the button then it should call for a function where that function will update all unapproved posts. So Im implementing it as below.

First I load all the unapproved post of the current logged in user . With just adding extra where clause in to your index function

Controoler for all unapproved posts

```<code>  public function index()
    {  //Fetching all unapproved post and passing it into view

        $userEmployee = Auth::user()->employee_id;
        $posts = Post::latest()->where('employee_id', $userEmployee)->where('is_approved',0)->get();
        return view('admin.post.index', compact('posts'));
    }
</code>```

Defining the route

Define a route like below  first and that route will call for the function named as  approve_all_posts in PostController .

```<code>Route::post('/post/approve_all_posts', 'PostController@approve_all_posts')->name('post.approve.all');
</code>```

New function for update

Then I make the function approve_all_posts () in PostController

```<code>public function approve_all_posts(){

 $unapproved_post = Post::where('is_approved',0)->update(['is_approved' => 1]);
  return redirect()->back();
}
</code>```

Update blade file with button

Then in admin/post/index.blade.php

I add a button called approve all posts like below

```<code><a href ="{{ route('post.approve.all')}}" class="btn btn-success">Approve all unapproved posts</a>
</code>```

Body:
Using Laravel-5.8, I have written a code for post of employees and it is working perfectly:

Controller

public function index()
{
    $userEmployee = Auth::user()->employee_id;
    $posts = Post::latest()->where('employee_id', $userEmployee)->get();

    return view('admin.post.index', compact('posts'));
}

And it generates this view shown below. The view loads all the unapproved posts for a particular employee:

      ID
      Title
      Author
      visibility
      Is Approved
      Status
      Action

    @foreach($posts as $key=>$post)

       {{ $key + 1 }}
       {{ str_limit($post->title,'10') }}
       {{ $post->user->name }}
       {{ $post->view_count }}

         @if($post->is_approved == true)
            Approved
         @else
            Pending
         @endif

          @if($post->status == true)
             Published
          @else
             Pending
          @endif

         @endforeach

<form action="{{route('admin.post.approve', $post->id)}}" method="POST" enctype="multipart/form-data">
    @csrf
    @method('PUT')

        <button type="submit" class="btn btn-primary"> {{ trans('global.submit') }}</button>

</form>

I want to add a submit button to the view called approve. Once the button is clicked, it checks where is_approved is = 0 for the loaded employee and turns all the is_approved that relates to the employee (the loaded) data to 1.

I have written this function in the same controller, but I see that it will only work for a selected row:

public function approve($id){

    $post = Post::find($id);
    if ($post->is_approved == false){
        $post->is_approved = true;
        $post->save();
        $post->user->notify(new AuthorPostApprove($post));

        Toastr::success('Post Successfully Approved');
    }else{
        Toastr::info('Post is already Approved');
    }

    return redirect()->back();
}

and have this route/web.php

Route::get('posts/', 'PostController@index')->name('post.index');
Route::put('/post/{id}/approve', 'PostController@approve')->name('post.approve');

How do I re-write my Controller, view and route to achieve this?

Thank you.

Body:
Ok I do something like below

All you need to do is that when user click the button then it should call for a function where that function will update all unapproved posts. So Im implementing it as below.

First I load all the unapproved post of the current logged in user . With just adding extra where clause in to your index function

Controoler for all unapproved posts

  public function index()
    {  //Fetching all unapproved post and passing it into view

        $userEmployee = Auth::user()->employee_id;
        $posts = Post::latest()->where('employee_id', $userEmployee)->where('is_approved',0)->get();
        return view('admin.post.index', compact('posts'));
    }

Defining the route

Define a route like below  first and that route will call for the function named as  approve_all_posts in PostController .

Route::post('/post/approve_all_posts', 'PostController@approve_all_posts')->name('post.approve.all');

New function for update

Then I make the function approve_all_posts () in PostController

public function approve_all_posts(){

 $unapproved_post = Post::where('is_approved',0)->update(['is_approved' => 1]);
  return redirect()->back();
}

Update blade file with button

Then in admin/post/index.blade.php

I add a button called approve all posts like below

<a href ="{{ route('post.approve.all')}}" class="btn btn-success">Approve all unapproved posts</a>


问:
How do I add my new User Control to the Toolbox or a new Winform?
I have an existing library (not a Winforms application) that supplies some Winforms to a bona-fide Windows application.  Within this library, I would like to create a User Control to group some controls together.  To accomplish this, I right-clicked, Add, User Control and dragged some controls onto the new User Control.

So far, so good.  The User Control even has the requisite User Control icon.  But dragging the new User Control from the Solution Explorer to a new blank Winform does not work (I get a circle with a line through it), and dragging it over to the Toolbox doesn't work either (even though I get a + sign when I drag it over the Toolbox).

Is there some sort of XML magic or something else I'm missing to make this work?

Note: I had some problems with Visual Studio 2008 that I managed to fix by following the workarounds that can be found here.  I am now able to get User Controls I added to my existing project into the toolbox by simply rebuilding the project.

答: One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.</p>


答:
You have 3 levels of nested lists, so you need to drill down</p>

```<code>l_b = [[['%.2f' % y[0], '%.2f' % y[1]] for y in x] for x in l_b]
</code>```

Title: How to round floats in a nested list to 2 decimal places?

Body:
I have coordinate lists of several polygons as listed below:

l_b =  [[[57.5, 2.875],
   [83.75, 4.1875],
   [83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 2.875]],
  [[83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 34.08695652173913],
   [83.75, 34.54347826086956],
   [83.75, 18.70923913043478]],
  [[0.0, 0.0],
   [18.125, 0.90625],
   [18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [0.0, 0.0]],
  [[18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [-5.0, 33.0],
   [18.125, 33.40217391304348],
   [18.125, 16.70108695652174]]]

How can I make all the numbers in list to round to 2 decimal places while keeping its format?

I've tried l_b = [ '%.2f' % elem for elem in l_b ] but it's giving me TypeError: must be real number, not list

Body:
You have 3 levels of nested lists, so you need to drill down

l_b = [[['%.2f' % y[0], '%.2f' % y[1]] for y in x] for x in l_b]


问:
What technology behind Chrome Angry Bird
I was wondering what is the technology used behind Chrome Angry Bird?

It is using HTML5 canvas for display. For the programming logic code, it seems not to be flash. Or, do Angry Bird team rewrite their code in JavaScript?

答:
EDIT: Following a discussion with @WSkid, I discovered that it is heavy GWT, and probably no webgl at all. You cannot be always right :)

Actually this is not GWT, this is WebGL. The point is that the original angrybirds was written in opengl ES, ie opengl supported by most modern phones (android, iphone...).
Chrome is working hard to come up with a new 3D standard for the web, which is webgl. Basically you can handle 3D stuff with a javascript API.

As for migrating, both are openGL based language, sort of reduced set of openGL capabilities, so they had to come up with a few changes to port Angry birds to google chrome. It is however not easy, because being low level, you always come up with difficult issues when you do texture management for instance.

more:
 http://www.khronos.org/opengles/
 http://en.wikipedia.org/wiki/WebGL

my two cents...


问:
Issue with wildcards into arguments of a Bash function
From the following link, I tried to use the following solution to compare a group of source files (here fortran90 = *.f90).

To do this and see the source which are different, I have put into my ~/.bashrc :

```<code>function diffm { for file in "$1"/"$2"; do diff -qs "$file" "$3"/"${file##*/}"; done ;}
</code>```

But unfortunately, if I am in the current directory for argument $1, i.e by execute :

```<code>$ diffm . '*.f90' ../../dir2
</code>```

The result is : impossible to access to './*.f90'. However, the sources *.f90 exist but wildcards are not taken into account.

Surely a problem with double quotes on arguments of my function ($1, $2, $3)?

More generally, this function doesn't work well.

How can I modify this function in order to make it work in all cases, even being in the current directory "." for  the first argument $1 or the third $3?

答:
Filename generation does not occur within quotes. Hence, you pass the literal string *.f90 to the function, and this string is used there literally too. If you know for sure that there is exactly one f90 files in your directory, don't use quotes and write

```<code>diffm . *.f90 ../../dir2
</code>```

Things get ugly if the file name has a space embedded (which, BTW, is one reason why I prefer Zsh over bash - you don't have to care about this in Zsh). To deal with this case, you could do a

```<code>myfile=*.f90
diffm . "$myfile" ../../dir2
</code>```

But sooner or later, you will be bitten by the fact, that for whatever reason, you have more than one f90 file, and your strategy will break. Therefore, a better solution would be to use a loop, which also works for the border case of having only one file:

```<code>iterating=0
for myfile in *.f90
do
    if ((iterating == 0))
    then
      ((iterating+=1))
      diffm . "$myfile" ../../dir2
    elif [[ ! -f $myfile ]]
    then
      echo "No files matching $myfile in this directory"
    else
      echo "ERROR: More than one f90-file. Don't know which one to diff" 1>&2
    fi
done
</code>```

The elif part just cares for the case that you don't have any f90 files. In this case, the loop body is executed once, and myfile contains the wildcard pattern.

Body:
From the following link, I tried to use the following solution to compare a group of source files (here fortran90 = *.f90).

To do this and see the source which are different, I have put into my ~/.bashrc :

function diffm { for file in "$1"/"$2"; do diff -qs "$file" "$3"/"${file##*/}"; done ;}

But unfortunately, if I am in the current directory for argument $1, i.e by execute :

$ diffm . '*.f90' ../../dir2

The result is : impossible to access to './*.f90'. However, the sources *.f90 exist but wildcards are not taken into account.

Surely a problem with double quotes on arguments of my function ($1, $2, $3)?

More generally, this function doesn't work well.

How can I modify this function in order to make it work in all cases, even being in the current directory "." for  the first argument $1 or the third $3?

Body:
Filename generation does not occur within quotes. Hence, you pass the literal string *.f90 to the function, and this string is used there literally too. If you know for sure that there is exactly one f90 files in your directory, don't use quotes and write

diffm . *.f90 ../../dir2

Things get ugly if the file name has a space embedded (which, BTW, is one reason why I prefer Zsh over bash - you don't have to care about this in Zsh). To deal with this case, you could do a

myfile=*.f90
diffm . "$myfile" ../../dir2

But sooner or later, you will be bitten by the fact, that for whatever reason, you have more than one f90 file, and your strategy will break. Therefore, a better solution would be to use a loop, which also works for the border case of having only one file:

iterating=0
for myfile in *.f90
do
    if ((iterating == 0))
    then
      ((iterating+=1))
      diffm . "$myfile" ../../dir2
    elif [[ ! -f $myfile ]]
    then
      echo "No files matching $myfile in this directory"
    else
      echo "ERROR: More than one f90-file. Don't know which one to diff" 1>&2
    fi
done

The elif part just cares for the case that you don't have any f90 files. In this case, the loop body is executed once, and myfile contains the wildcard pattern.


问:
AppInsight TrackDependency() from javascript is not working
I am trying to log into dependency table of appinsight, I am using frontend code javascript. Below is the snippet. It executes fine but I don't see any entry in dependency table of appinsight.

```<code>var appInsights = window.appInsights || function (a){function b(a){c[a]=function(){var b=arguments;c.queue.push(function(){c[a].apply(c,b)})}}var c={config:a},d=document,e=window;setTimeout(function(){var b=d.createElement("script");b.src=a.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js",d.getElementsByTagName("script")[0].parentNode.appendChild(b)});try{c.cookie=d.cookie}catch(a){}c.queue=[];for(var f=["Event","Exception","Metric","PageView","Trace","Dependency"];f.length;)b("track"+f.pop());if(b("setAuthenticatedUserContext"),b("clearAuthenticatedUserContext"),b("startTrackEvent"),b("stopTrackEvent"),b("startTrackPage"),b("stopTrackPage"),b("flush"),!a.disableExceptionTracking){f="onerror",b("_"+f);var g=e[f];e[f]=function(a,b,d,e,h){var i=g&&g(a,b,d,e,h);return!0!==i&&c["_"+f](a,b,d,e,h),i}}return c
     }({
         instrumentationKey: '@Model.InstrumentationKey'
     });

    window.appInsights = appInsights;
    appInsights.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:231, resultCode:0, success: true, dependencyTypeName: "ZSQL"});
</code>```

Is there anything wrong in above code?

答:
It should be incorrect use of trackDependency method. You can refer to this doc for the definition of trackDependency(in the page, search trackDependency).

And here is another link about how to use trackDependency method in JavaScript.

Here is a sample code, and works at my side(you can modify it to meet your need):

```<code><script type="text/javascript">
var appInsights=window.appInsights||function(config){
    function s(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } } var t = { config: config }, r = document, f = window, e = "script", o = r.createElement(e), i, u; for (o.src = config.url || "//az416426.vo.msecnd.net/scripts/a/ai.0.js", r.getElementsByTagName(e)[0].parentNode.appendChild(o), t.cookie = r.cookie, t.queue = [], i = ["Event", "Exception", "Metric", "PageView", "Trace","Dependency"];i.length;)s("track"+i.pop());return config.disableExceptionTracking||(i="onerror",s("_"+i),u=f[i],f[i]=function(config,r,f,e,o){var s=u&&u(config,r,f,e,o);return s!==!0&&t["_"+i](config,r,f,e,o),s}),t
}({
    instrumentationKey:"the key"
});
window.appInsights = appInsights;

// end of insertion
    appInsights.trackPageView();
    appInsights.trackTrace("sssssss114");
    appInsights.trackDependency("id", "GET", "https://www.bing.com", null, null, true, null, { prop1: 'abc' }, { meas1: 4.5 })
</script>
</code>```

And the dependency data is shown in azure portal -> application insights logs:

Body:
I am trying to log into dependency table of appinsight, I am using frontend code javascript. Below is the snippet. It executes fine but I don't see any entry in dependency table of appinsight.

var appInsights = window.appInsights || function (a){function b(a){c[a]=function(){var b=arguments;c.queue.push(function(){c[a].apply(c,b)})}}var c={config:a},d=document,e=window;setTimeout(function(){var b=d.createElement("script");b.src=a.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js",d.getElementsByTagName("script")[0].parentNode.appendChild(b)});try{c.cookie=d.cookie}catch(a){}c.queue=[];for(var f=["Event","Exception","Metric","PageView","Trace","Dependency"];f.length;)b("track"+f.pop());if(b("setAuthenticatedUserContext"),b("clearAuthenticatedUserContext"),b("startTrackEvent"),b("stopTrackEvent"),b("startTrackPage"),b("stopTrackPage"),b("flush"),!a.disableExceptionTracking){f="onerror",b("_"+f);var g=e[f];e[f]=function(a,b,d,e,h){var i=g&&g(a,b,d,e,h);return!0!==i&&c["_"+f](a,b,d,e,h),i}}return c
     }({
         instrumentationKey: '@Model.InstrumentationKey'
     });

    window.appInsights = appInsights;
    appInsights.trackDependency({target:"http://dbname", name:"select customers proc", data:"SELECT * FROM Customers", duration:231, resultCode:0, success: true, dependencyTypeName: "ZSQL"});

Is there anything wrong in above code?

Body:
It should be incorrect use of trackDependency method. You can refer to this doc for the definition of trackDependency(in the page, search trackDependency).

And here is another link about how to use trackDependency method in JavaScript.

Here is a sample code, and works at my side(you can modify it to meet your need):

<script type="text/javascript">
var appInsights=window.appInsights||function(config){
    function s(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } } var t = { config: config }, r = document, f = window, e = "script", o = r.createElement(e), i, u; for (o.src = config.url || "//az416426.vo.msecnd.net/scripts/a/ai.0.js", r.getElementsByTagName(e)[0].parentNode.appendChild(o), t.cookie = r.cookie, t.queue = [], i = ["Event", "Exception", "Metric", "PageView", "Trace","Dependency"];i.length;)s("track"+i.pop());return config.disableExceptionTracking||(i="onerror",s("_"+i),u=f[i],f[i]=function(config,r,f,e,o){var s=u&&u(config,r,f,e,o);return s!==!0&&t["_"+i](config,r,f,e,o),s}),t
}({
    instrumentationKey:"the key"
});
window.appInsights = appInsights;

// end of insertion
    appInsights.trackPageView();
    appInsights.trackTrace("sssssss114");
    appInsights.trackDependency("id", "GET", "https://www.bing.com", null, null, true, null, { prop1: 'abc' }, { meas1: 4.5 })
</script>

And the dependency data is shown in azure portal -> application insights logs:


问:
Merge multiple SQL Server tables into one
I have many SQL Server tables in a database that have information about the same domain (same columns) and their names are the same plus a date suffix (yyyyMMdd):

TABLE_ABOUT_THIS_THING_20200131

TABLE_ABOUT_THIS_THING_20191231

TABLE_ABOUT_THIS_THING_20191130

TABLE_ABOUT_THIS_THING_20191031

TABLE_ABOUT_THIS_THING_20190930

TABLE_ABOUT_THIS_THING_20190831

...

This seems like it would make more sense if it was all in the same table. Is there a way, using a query/SSIS or something similar, to merge this tables into one (TABLE_ABOUT_THIS_THING) with a new column (extraction_date) made out of the current table suffix?

答:
You can use SSIS with the new table "TABLE_ABOUT_THIS_THING" as destination and a query that look like this as source: </p>

```<code>`Select * FROM table1
UNION
Select * FROM table2
UNION
.
.
.`
</code>```

Body:
You can use SSIS with the new table "TABLE_ABOUT_THIS_THING" as destination and a query that look like this as source:

`Select * FROM table1
UNION
Select * FROM table2
UNION
.
.
.`


问:
how can i alter the contents and log it in console in angular?
I am using services in angular and pulling data from the URL :
http://jsonplaceholder.typicode.com/posts  And rendering it on the browser in form of a table.
Next I want to perform an update operation to the contents in such a way that my posts[] gets updated and render it on console.
Any idea how to do it?

My post.component.ts

```<code>import { PostsService } from './../posts.service';
import { Component, OnInit } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {

  posts: any[];

  constructor( private service : PostsService ) {

    this.service.getPosts().subscribe(response => {
  this.posts = response;
})
  }

  ngOnInit(): void {
  }

}
</code>```

posts.component.html

```<code>    <table *ngFor="let post of posts" >
<tr><td>{{post.title}}</td>
<td>{{post.id}}</td>
<td>{{post.body}}</td></tr>
    </table>
</code>```

答:
there could be a button on the html which calls the update method and
  update the data of the row which has been passed and then display on
  the console.

This is quite simple. Add the button in the html:

```<code><table *ngFor="let post of posts" >
<tr><td>{{post.title}}</td>
<td>{{post.id}}</td>
<td>{{post.body}}</td></tr>
    </table>
<button (click)="updateData()">Update</button>
</code>```

in the ts file, add the function:

```<code>public updateData(): void {
  this.posts.forEach(post => {
    post.body = "New custom body for each post";
  });

  console.log(this.posts);
}
</code>```

This is just an example. Since you haven't tell us how do you want the data to be modified, I just assigned a new body to each entry.

EDIT: Like when i click on the update button,the corresponding row
  should become editable and once edited it should update the original
  posts[] corresponding to that entry and display on console

I came up with this idea: https://codesandbox.io/s/cool-shadow-sksf9

Basically you add a custom property to posts and set it to false by default:

```<code>interface Post {
  id: number;
  body: string;
  inEdit?: boolean;
}

posts: Post[] = [
    {
      id: 1,
      body: "body 1",
      inEdit: false
    },
    {
      id: 2,
      body: "body 2",
      inEdit: false
    },
    {
      id: 3,
      body: "body 3",
      inEdit: false
    },
    {
      id: 4,
      body: "body 4",
      inEdit: false
    }
  ];
</code>```

To add the custom property when you get the data from the API, you can do that:

```<code>public getData(): void {
  this.yourService.getData()
    .subscribe((response: Post[]) => {
      this.posts = response.map(post => {
        post.inEdit = false;
      };
    });
}
</code>```

Then modifiy the html in order to use an input only when you're editing the row (after pressing a button):

```<code><table *ngFor="let post of posts; let i = index">
  <tr>
    <ng-container *ngIf="!post.inEdit">
      <td>{{post.id}}</td>
      <td class="long-body">
        {{post.body}}
      </td>
      <button (click)="post.inEdit = !post.inEdit">
        Edit me
      </button>
    </ng-container>
    <ng-container *ngIf="post.inEdit">
      <td>{{post.id}}</td>
      <td>
        <input type="text" #bodyValue [value]="post.body" />
      </td>
      <button *ngIf="post.inEdit" (click)="updateRow(i, bodyValue.value)">
        Save changes
      </button>
    </ng-container>
  </tr>
</table>
</code>```

Finally, the updateRow function:

```<code>public updateRow(index: number, newBody: string): void {
    this.posts[index].body = newBody;
    this.posts[index].inEdit = false;

    console.table(this.posts[index]);
  }
</code>```

Here's the little css I used in order to have the text in edit and not in edit the same width:

```<code>table {
  margin-bottom: 10px;
}

.long-body,
input {
  width: 150px;
  background-color: #cdcdcd;
}
</code>```

Body:
I am using services in angular and pulling data from the URL :
http://jsonplaceholder.typicode.com/posts  And rendering it on the browser in form of a table.
Next I want to perform an update operation to the contents in such a way that my posts[] gets updated and render it on console.
Any idea how to do it?

My post.component.ts

import { PostsService } from './../posts.service';
import { Component, OnInit } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {

  posts: any[];

  constructor( private service : PostsService ) {

    this.service.getPosts().subscribe(response => {
  this.posts = response;
})
  }

  ngOnInit(): void {
  }

}

posts.component.html

{{post.title}}
{{post.id}}
{{post.body}}

Body:
there could be a button on the html which calls the update method and
  update the data of the row which has been passed and then display on
  the console.

This is quite simple. Add the button in the html:

<table *ngFor="let post of posts" >
<tr><td>{{post.title}}</td>
<td>{{post.id}}</td>
<td>{{post.body}}</td></tr>
    </table>
<button (click)="updateData()">Update</button>

in the ts file, add the function:

public updateData(): void {
  this.posts.forEach(post => {
    post.body = "New custom body for each post";
  });

  console.log(this.posts);
}

This is just an example. Since you haven't tell us how do you want the data to be modified, I just assigned a new body to each entry.

EDIT: Like when i click on the update button,the corresponding row
  should become editable and once edited it should update the original
  posts[] corresponding to that entry and display on console

I came up with this idea: https://codesandbox.io/s/cool-shadow-sksf9

Basically you add a custom property to posts and set it to false by default:

interface Post {
  id: number;
  body: string;
  inEdit?: boolean;
}

posts: Post[] = [
    {
      id: 1,
      body: "body 1",
      inEdit: false
    },
    {
      id: 2,
      body: "body 2",
      inEdit: false
    },
    {
      id: 3,
      body: "body 3",
      inEdit: false
    },
    {
      id: 4,
      body: "body 4",
      inEdit: false
    }
  ];

To add the custom property when you get the data from the API, you can do that:

public getData(): void {
  this.yourService.getData()
    .subscribe((response: Post[]) => {
      this.posts = response.map(post => {
        post.inEdit = false;
      };
    });
}

Then modifiy the html in order to use an input only when you're editing the row (after pressing a button):

<table *ngFor="let post of posts; let i = index">
  <tr>
    <ng-container *ngIf="!post.inEdit">
      <td>{{post.id}}</td>
      <td class="long-body">
        {{post.body}}
      </td>
      <button (click)="post.inEdit = !post.inEdit">
        Edit me
      </button>
    </ng-container>
    <ng-container *ngIf="post.inEdit">
      <td>{{post.id}}</td>
      <td>
        <input type="text" #bodyValue [value]="post.body" />
      </td>
      <button *ngIf="post.inEdit" (click)="updateRow(i, bodyValue.value)">
        Save changes
      </button>
    </ng-container>
  </tr>
</table>

Finally, the updateRow function:

public updateRow(index: number, newBody: string): void {
    this.posts[index].body = newBody;
    this.posts[index].inEdit = false;

    console.table(this.posts[index]);
  }

Here's the little css I used in order to have the text in edit and not in edit the same width:

table {
  margin-bottom: 10px;
}

.long-body,
input {
  width: 150px;
  background-color: #cdcdcd;
}


问:
How do i import and export Localizations files in a cocoa application xcode so others can translate it?
I'm currently working on a mac application to which I added localizations. I want to know how i can export them so that others can translate it and once that is done how do I import the localization files so that I can use them in my application again. I saw a bunch of stuff saying got to editor and there you'll see "Export for localization.." I tried to look for that but couldn't find it. I'm using xcode 10.1.

答:
What I did was directly copy the .string file and give it a different name(i.e name of the language to be translated) you can find these files in the project files they're usually located in the folder <short form of language name>.lproj (for example fr.lproj for french) these will exist in the main project folder containing all the files, Inside these language folders you will find a the Main.strings files. Make a copy of the Main.strings file rename it to something like french.strings and give it to your translator once it's done rename it to Main.strings again and replace the original file of the respect language.

It's a bit tedious but it's the method I use since i can't find the export localizations option either.


答:
Using SSIS: use union  for the collect data from the multi table and use Derived Column for the extraction_date before the destination for more information you can take from following link:
https://www.tutorialgateway.org/union-all-transformation-in-ssis/</p>

Title: Merge multiple SQL Server tables into one

Body:
I have many SQL Server tables in a database that have information about the same domain (same columns) and their names are the same plus a date suffix (yyyyMMdd):

TABLE_ABOUT_THIS_THING_20200131

TABLE_ABOUT_THIS_THING_20191231

TABLE_ABOUT_THIS_THING_20191130

TABLE_ABOUT_THIS_THING_20191031

TABLE_ABOUT_THIS_THING_20190930

TABLE_ABOUT_THIS_THING_20190831

...

This seems like it would make more sense if it was all in the same table. Is there a way, using a query/SSIS or something similar, to merge this tables into one (TABLE_ABOUT_THIS_THING) with a new column (extraction_date) made out of the current table suffix?


问:
How to iterate by all not empty rows without using break or continue statement?
I want to get data from Excel file. I'm using while loop, iterator and hasNext() method to go by all rows.
My problem: sometimes after rows with data there are empty rows (propably with cell type string and value "" or null), which I don't want to iterate by.
So I added method isCellEmpty():

```<code>public static boolean isCellEmpty(final Cell cell) {
    if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
        return true;
    }
    if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().isEmpty()) {
        return true;
    }
    return false;
}
</code>```

and added it after starring while loop in main method:

```<code>while (rowIterator.hasNext()) {
    row = rowIterator.next();
    if (isCellEmpty(row.getCell(2))) {
        break;
    }
    // some code ...
}
</code>```

But now I have a break statement. How can I iterate by all not empty rows without using break or continue? Now (with break) my algorithm is working properly - I'm getting data which I need. I'm just wondering if it's possible to write code without break or continue.

答:
Able to remove empty rows based on the Laiv's answer's. I've modified to support passing the Row. This is the modified answer

```<code>import org.apache.commons.collections4.Predicate;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;

public class ValidRowPredicate implements Predicate<Row> {

    @Override
    public boolean evaluate(Row row) {
        Cell cell = row.getCell(2);
        if (cell == null || cell.getCellType() == CellType.BLANK) {
            return false;
        } else if (cell.getCellType() == CellType.STRING &&
                cell.getStringCellValue().isEmpty()) {
            return false;
        }
        return true;
    }
}
</code>```

Credits goes to Laiv

Body:
I want to get data from Excel file. I'm using while loop, iterator and hasNext() method to go by all rows.
My problem: sometimes after rows with data there are empty rows (propably with cell type string and value "" or null), which I don't want to iterate by.
So I added method isCellEmpty():

public static boolean isCellEmpty(final Cell cell) {
    if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
        return true;
    }
    if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().isEmpty()) {
        return true;
    }
    return false;
}

and added it after starring while loop in main method:

while (rowIterator.hasNext()) {
    row = rowIterator.next();
    if (isCellEmpty(row.getCell(2))) {
        break;
    }
    // some code ...
}

But now I have a break statement. How can I iterate by all not empty rows without using break or continue? Now (with break) my algorithm is working properly - I'm getting data which I need. I'm just wondering if it's possible to write code without break or continue.

Body:
Able to remove empty rows based on the Laiv's answer's. I've modified to support passing the Row. This is the modified answer

import org.apache.commons.collections4.Predicate;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;

public class ValidRowPredicate implements Predicate<Row> {

    @Override
    public boolean evaluate(Row row) {
        Cell cell = row.getCell(2);
        if (cell == null || cell.getCellType() == CellType.BLANK) {
            return false;
        } else if (cell.getCellType() == CellType.STRING &&
                cell.getStringCellValue().isEmpty()) {
            return false;
        }
        return true;
    }
}

Credits goes to Laiv


问:
Having issues with .php files and the GAE
I am trying to get a contact form to work on my GAE.  I have the app.yaml complete and it's working for everything bar the .php files it shows a No web page was found for the web address when you try to go onto the webpage.  The files are all in the correct directory.  I originally had the form as form.php but when deploying it showed: WARNING: The URL path "/form" is reserved and will not be matched. So I changed it contact.php, but it's still showing the same error.  Would you guys have any recommendations on what I should try?  The contact.php has the form in it and I also have contact_control.php to do form validation and send the email.

Thanks!

```<code>#service: default
service: test-landing
runtime: php55
api_version: 1
threadsafe: true

handlers:
- url: /
  static_files: www/index.html
  upload: www/index.html
  secure: always

- url: /(.+\.php)$
  script: assets/\1
  secure: always

- url: /home
  static_files: www/index.html
  upload: www/index.html
  secure: always

- url: /news
  static_files: www/news.html
  upload: www/news.html
  secure: always

- url: /terms
  static_files: www/terms.html
  upload: www/terms/news.html
  secure: always

- url: /privacy
  static_files: www/privacy.html
  upload: www/privacy.html
  secure: always

- url: /faq
  static_files: www/faq.html
  upload: www/faq.html
  secure: always

- url: /contact
  script: /contact.php
  secure: always
- url: /contact
  static_files: /contact.php
  upload: /contact.php
  secure: always

- url: /contact_control
  script: www/contact_control.php
  secure: always

- url: /(.*)
  static_files: www/\1
  upload: www/(.*)
  secure: always
</code>```

答:
It seems that you will need to configure your app.yaml to recognize and use the PHP files on your Google App Engine.

I would recommend you to take a look at the following documentation on how to configure your app.yaml to work with PHP.

Configuring your App with app.yaml

app.yaml Configuration File

Besides that, there is the following documentation, on how to configure your App Engine to work correctly with PHP, that I would recommend you to take a look - they are actually quickstart documentation, which seems to be the exact place where you are. :)

Quickstart for PHP in the App Engine Flexible Environment

Quickstart for PHP 7 in the App Engine Standard Environment

Let me know if the information helped you!

Body:
I am trying to get a contact form to work on my GAE.  I have the app.yaml complete and it's working for everything bar the .php files it shows a No web page was found for the web address when you try to go onto the webpage.  The files are all in the correct directory.  I originally had the form as form.php but when deploying it showed: WARNING: The URL path "/form" is reserved and will not be matched. So I changed it contact.php, but it's still showing the same error.  Would you guys have any recommendations on what I should try?  The contact.php has the form in it and I also have contact_control.php to do form validation and send the email.

Thanks!

#service: default
service: test-landing
runtime: php55
api_version: 1
threadsafe: true

handlers:
- url: /
  static_files: www/index.html
  upload: www/index.html
  secure: always

- url: /(.+\.php)$
  script: assets/\1
  secure: always

- url: /home
  static_files: www/index.html
  upload: www/index.html
  secure: always

- url: /news
  static_files: www/news.html
  upload: www/news.html
  secure: always

- url: /terms
  static_files: www/terms.html
  upload: www/terms/news.html
  secure: always

- url: /privacy
  static_files: www/privacy.html
  upload: www/privacy.html
  secure: always

- url: /faq
  static_files: www/faq.html
  upload: www/faq.html
  secure: always

- url: /contact
  script: /contact.php
  secure: always
- url: /contact
  static_files: /contact.php
  upload: /contact.php
  secure: always

- url: /contact_control
  script: www/contact_control.php
  secure: always

- url: /(.*)
  static_files: www/\1
  upload: www/(.*)
  secure: always