问:
Java JUNG EdmondsKarpMaxFlow getting stuck in infinite loop
I am trying to use JUNG's EdmondsKarpMaxFlow object to find the max flow between all node pairs in a directed graph. I created a simple directed graph and ran it on each combination of nodes with no error. Here's the working example for reference:
https://pastebin.com/TLsEduxZ

However, when I call the same 'edkAlg.evaluate()' code on a more complex graph, the loop stops on a certain edge/iteration each time.

```<code>public class SomeClass{
...
...
    MyEdmondsKarpMaxFlow edk = new MyEdmondsKarpMaxFlow(dirGraph);
    edk.runEdk();
}

public class MyEdmondsKarpMaxFlow {

    int edgeFlowMapId = 0;
    protected DirectedSparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> dirGraph;
    protected Map<GraphElements.MyEdge, Double> edgeFlowMap = new HashMap<GraphElements.MyEdge, Double>();

    protected Transformer<GraphElements.MyEdge, Double> capTransformer = new Transformer<GraphElements.MyEdge, Double>() {
        public Double transform(GraphElements.MyEdge edge) {
            return edge.getCapacity();
        }
    };

    // This Factory produces new edges for use by the algorithm
    protected Factory<GraphElements.MyEdge> edgeFactory = new Factory<GraphElements.MyEdge>() {
        public GraphElements.MyEdge create() {
           return new GraphElements.MyEdge(Integer.toString(edgeFlowMapId++));
        }
    };

    public MyEdmondsKarpMaxFlow(DirectedSparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> dirGraph) {
        this.dirGraph = dirGraph;
    }

    public void runEdk() {
        Collection<GraphElements.MyVertex> vertexCollection = dirGraph.getVertices();

        for (Iterator iterator1 = vertexCollection.iterator(); iterator1.hasNext(); ) {
            GraphElements.MyVertex v1 = (GraphElements.MyVertex) iterator1.next();
            Collection<GraphElements.MyVertex> vertexCollection2 = dirGraph.getVertices();

            for (Iterator iterator2 = vertexCollection2.iterator(); iterator2.hasNext(); ) {
                GraphElements.MyVertex v2 = (GraphElements.MyVertex) iterator2.next();
                if (v1.equals(v2)) continue;
                EdmondsKarpMaxFlow<GraphElements.MyVertex, GraphElements.MyEdge> edkAlg = new EdmondsKarpMaxFlow(dirGraph, v1, v2, capTransformer, edgeFlowMap, edgeFactory);
                edkAlg.evaluate();
                System.out.println("max edk flow between v1 and v2 is : " + edkAlg.getMaxFlow());
            }
        }
        System.out.println("FIN");
    }
}
</code>```

I use custom definitions of Vertices and Edges which behave as expected but simply have more attributes than the trivial example. The code finds max flow between v1 and v2 perfectly fine up to the first 201 iterations, but gets stuck in '.evaluate()' after each time (it uses the same order of pairs each time so it is always stuck on problemNode123 -> problemNode456). Not too sure where I'm going wrong, and there isn't much help online so any pointers are appreciated!

答: You're not providing quite enough information to be sure, but the problem is almost certainly related to the fact that you haven't defined hashCode() and equals() for your custom node and edge objects.

Body:
I am trying to use JUNG's EdmondsKarpMaxFlow object to find the max flow between all node pairs in a directed graph. I created a simple directed graph and ran it on each combination of nodes with no error. Here's the working example for reference:
https://pastebin.com/TLsEduxZ

However, when I call the same 'edkAlg.evaluate()' code on a more complex graph, the loop stops on a certain edge/iteration each time.

public class SomeClass{
...
...
    MyEdmondsKarpMaxFlow edk = new MyEdmondsKarpMaxFlow(dirGraph);
    edk.runEdk();
}

public class MyEdmondsKarpMaxFlow {

    int edgeFlowMapId = 0;
    protected DirectedSparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> dirGraph;
    protected Map<GraphElements.MyEdge, Double> edgeFlowMap = new HashMap<GraphElements.MyEdge, Double>();

    protected Transformer<GraphElements.MyEdge, Double> capTransformer = new Transformer<GraphElements.MyEdge, Double>() {
        public Double transform(GraphElements.MyEdge edge) {
            return edge.getCapacity();
        }
    };

    // This Factory produces new edges for use by the algorithm
    protected Factory<GraphElements.MyEdge> edgeFactory = new Factory<GraphElements.MyEdge>() {
        public GraphElements.MyEdge create() {
           return new GraphElements.MyEdge(Integer.toString(edgeFlowMapId++));
        }
    };

    public MyEdmondsKarpMaxFlow(DirectedSparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> dirGraph) {
        this.dirGraph = dirGraph;
    }

    public void runEdk() {
        Collection<GraphElements.MyVertex> vertexCollection = dirGraph.getVertices();

        for (Iterator iterator1 = vertexCollection.iterator(); iterator1.hasNext(); ) {
            GraphElements.MyVertex v1 = (GraphElements.MyVertex) iterator1.next();
            Collection<GraphElements.MyVertex> vertexCollection2 = dirGraph.getVertices();

            for (Iterator iterator2 = vertexCollection2.iterator(); iterator2.hasNext(); ) {
                GraphElements.MyVertex v2 = (GraphElements.MyVertex) iterator2.next();
                if (v1.equals(v2)) continue;
                EdmondsKarpMaxFlow<GraphElements.MyVertex, GraphElements.MyEdge> edkAlg = new EdmondsKarpMaxFlow(dirGraph, v1, v2, capTransformer, edgeFlowMap, edgeFactory);
                edkAlg.evaluate();
                System.out.println("max edk flow between v1 and v2 is : " + edkAlg.getMaxFlow());
            }
        }
        System.out.println("FIN");
    }
}

I use custom definitions of Vertices and Edges which behave as expected but simply have more attributes than the trivial example. The code finds max flow between v1 and v2 perfectly fine up to the first 201 iterations, but gets stuck in '.evaluate()' after each time (it uses the same order of pairs each time so it is always stuck on problemNode123 -> problemNode456). Not too sure where I'm going wrong, and there isn't much help online so any pointers are appreciated!


来源: stackexchange

问:
need help finding error in code to filter form
This is the code I am using in order to try and filter a forms subform according to the dates in the txt boxes. The code is having a compile error, stopping at the third # with a "expect expression" and I can't figure out why.  I got this code from another location and simply tried to use it for my purposes. I know nothing about vba.

```<code>Private Sub btnDateRange_Click()
Me.Filter = "[tblDeliveries].[DeliveryID] Between #" & Me.StartDate & # AND #" & Me.EndDate & "#"
DoCmd.RunCommand acCmdApplyFilterSort
End Sub
</code>```

would someone please point out what the issue is?  Thank you.

答:
Use the correct syntax:

Private Sub btnDateRange_Click()
Me.Filter = "[tblDeliveries].[DeliveryID] Between #" & Format(Me.StartDate, "yyyy\/mm\/dd") & "# AND #" & Format(Me.EndDate, "yyyy\/mm\/dd") & "#"
Me.FilterOn = True
End Sub
```

ContentLicense: CC BY-SA 4.0

Body:
This is the code I am using in order to try and filter a forms subform according to the dates in the txt boxes. The code is having a compile error, stopping at the third # with a "expect expression" and I can't figure out why.  I got this code from another location and simply tried to use it for my purposes. I know nothing about vba.

Private Sub btnDateRange_Click()
Me.Filter = "[tblDeliveries].[DeliveryID] Between #" & Me.StartDate & # AND #" & Me.EndDate & "#"
DoCmd.RunCommand acCmdApplyFilterSort
End Sub

would someone please point out what the issue is?  Thank you.


问:
Mongodb find top 10 largest array items in collection
My collection has items like

```<code>[{
  "username": "xxx",
  "wonTournaments": ['111', '123', '1234']
}, {
  "username": "xxx2",
  "wonTournaments": ['111', '123']
}, {
  "username": "xxx3",
  "wonTournaments": ['111', '123', '1234', '11111']
}, {
  "username": "xxx4",
  "wonTournaments": ['111']
}]
</code>```

I want to retrieve top items of users whose wonTournamnts is more. Can anyone tell me how to do this in MongoDB. I am using cloud MongoDB atlas.

In the above case top users are ['xxx3','xxx','xxx2','xxx4']

答:
You can easily do this using db.collection.aggregate() like:

```<code>db.collection.aggregate([
  { $project: { username: 1, won: { $size: "$wonTournaments" } } },
  { $sort: { "won": -1 } },
  { $limit : 10 }
])
</code>```

You will need to change collection with the name of the actual collection you have in db.

Body:
My collection has items like

[{
  "username": "xxx",
  "wonTournaments": ['111', '123', '1234']
}, {
  "username": "xxx2",
  "wonTournaments": ['111', '123']
}, {
  "username": "xxx3",
  "wonTournaments": ['111', '123', '1234', '11111']
}, {
  "username": "xxx4",
  "wonTournaments": ['111']
}]

I want to retrieve top items of users whose wonTournamnts is more. Can anyone tell me how to do this in MongoDB. I am using cloud MongoDB atlas.

In the above case top users are ['xxx3','xxx','xxx2','xxx4']

Body:
You can easily do this using db.collection.aggregate() like:

db.collection.aggregate([
  { $project: { username: 1, won: { $size: "$wonTournaments" } } },
  { $sort: { "won": -1 } },
  { $limit : 10 }
])

You will need to change collection with the name of the actual collection you have in db.


问:
Setting properties dynamically in react based on value of other properties
I am writing a REACT application to show some reviews.
Each reviews has two properties likes and dislikes.
The state of my main component looks like

```<code>state = {
    listings: [
        { key: 'key6', listingCity: 'City_Name', listingTitle: 'Restaurant_Name', likes: '3', dislikes: '1', listingBodyText: 'Review_Text' },
        { key: 'key7', listingCity: 'City_Name2', listingTitle: 'Restaurant_Name2', likes: '13', dislikes: '9', listingBodyText: 'Review_Text2' }
    ]
};

</code>```

I want to add another property which is like a score for each restaurant, and this will be difference between likes and dislikes.
For the two restaurants in my example state,
1. likes - 3, dislikes - 1 -- Score = 2
2. likes - 13 , dislikes - 9 -- Score = 4

I am trying to figure out what is the best way to generate this score.
One option is I add another property for each restaurant called score and initialise it to 0 in the state. Then in the componentDidMount() hook, calculate this value.
this will work well for the initial calculation, but now every time a user would like / dislike I would have to call this function to have the updated score.

Is there a way to define a property in the state as a difference of two other properties.
In my case, define score = likes - dislikes

My main goal with this question is to try and understand what would be the recommended approach for this kind of problem.

答:
You can create a separate function for this and you can pass key of each restaurant:

```<code>const calScore = (key) => {
  const listings = (this?.state?.listings??[]).map(listing => {
     if(listing.key === key) {
       return {
           ...listing,
           score: listing?.likes - listing?.dislikes
       }
     } else {
        return {...listing}
     }
  })
  this.setState({ listings })
}

</code>```

You can call this function after every like/dislike click

Body:
I am writing a REACT application to show some reviews.
Each reviews has two properties likes and dislikes.
The state of my main component looks like

state = {
    listings: [
        { key: 'key6', listingCity: 'City_Name', listingTitle: 'Restaurant_Name', likes: '3', dislikes: '1', listingBodyText: 'Review_Text' },
        { key: 'key7', listingCity: 'City_Name2', listingTitle: 'Restaurant_Name2', likes: '13', dislikes: '9', listingBodyText: 'Review_Text2' }
    ]
};

I want to add another property which is like a score for each restaurant, and this will be difference between likes and dislikes.
For the two restaurants in my example state,
1. likes - 3, dislikes - 1 -- Score = 2
2. likes - 13 , dislikes - 9 -- Score = 4

I am trying to figure out what is the best way to generate this score.
One option is I add another property for each restaurant called score and initialise it to 0 in the state. Then in the componentDidMount() hook, calculate this value.
this will work well for the initial calculation, but now every time a user would like / dislike I would have to call this function to have the updated score.

Is there a way to define a property in the state as a difference of two other properties.
In my case, define score = likes - dislikes

My main goal with this question is to try and understand what would be the recommended approach for this kind of problem.

Body:
You can create a separate function for this and you can pass key of each restaurant:

const calScore = (key) => {
  const listings = (this?.state?.listings??[]).map(listing => {
     if(listing.key === key) {
       return {
           ...listing,
           score: listing?.likes - listing?.dislikes
       }
     } else {
        return {...listing}
     }
  })
  this.setState({ listings })
}

You can call this function after every like/dislike click


问:
Finding Median and average of list in tcl
I am having trouble finding a way to calculate the median and average of a list of numbers and the resources online seem to be really limited with Tcl. So far I managed to only print the numbers of the list.

Your help would be greatly appreciated.

```<code>proc ladd {l} {
    set total 0
    set counter 0
    foreach nxt $l {
        incr total $nxt
        incr counter 1
    }
    puts "$total"
    puts "$counter"

    set average ($total/$counter)

    puts "$average"

}

set a [list 4 3 2 1 15 6 29]
ladd $a

</code>```

答:
To get the average (i.e., the arithmetic mean) of a list, you can just do:

```<code>proc average {list} {
    expr {[tcl::mathop::+ {*}$list 0.0] / max(1, [llength $list])}
}
</code>```

That sums the values in the list (the trailiing 0.0 forces the result to be a floating point value, even if all the added numbers are integers) and divides by the number of elements (or 1 if the list is empty so an empty list gets a mean of 0.0 instead of an error).

To get the median of a list, you have to sort it and pick the middle element.

```<code>proc median {list {mode -real}} {
    set list [lsort $mode $list]
    set len [llength $list]
    if {$len & 1} {
       # Odd number of elements, unique middle element
       return [lindex $list [expr {$len >> 1}]]
    } else {
       # Even number of elements, average the middle two
       return [average [lrange $list [expr {($len >> 1) - 1] [expr {$len >> 1}]]]
    }
}
</code>```

To complete the set, here's how to get the mode of the list if there is a unique one (relevant for some applications where values are selected from a fairly small set):

```<code>proc mode {list} {
    # Compute a histogram
    foreach val $list {dict incr h $val}
    # Sort the histogram in descending order of frequency; type-puns the dict as a list
    set h [lsort -stride 2 -index 1 -descending -integer $h]
    # The mode is now the first element
    return [lindex $h 0]
}
</code>```

I'll leave handling the empty and non-unique cases as an exercise.

Body:
I am having trouble finding a way to calculate the median and average of a list of numbers and the resources online seem to be really limited with Tcl. So far I managed to only print the numbers of the list.

Your help would be greatly appreciated.

proc ladd {l} {
    set total 0
    set counter 0
    foreach nxt $l {
        incr total $nxt
        incr counter 1
    }
    puts "$total"
    puts "$counter"

    set average ($total/$counter)

    puts "$average"

}

set a [list 4 3 2 1 15 6 29]
ladd $a

Body:
To get the average (i.e., the arithmetic mean) of a list, you can just do:

proc average {list} {
    expr {[tcl::mathop::+ {*}$list 0.0] / max(1, [llength $list])}
}

That sums the values in the list (the trailiing 0.0 forces the result to be a floating point value, even if all the added numbers are integers) and divides by the number of elements (or 1 if the list is empty so an empty list gets a mean of 0.0 instead of an error).

To get the median of a list, you have to sort it and pick the middle element.

proc median {list {mode -real}} {
    set list [lsort $mode $list]
    set len [llength $list]
    if {$len & 1} {
       # Odd number of elements, unique middle element
       return [lindex $list [expr {$len >> 1}]]
    } else {
       # Even number of elements, average the middle two
       return [average [lrange $list [expr {($len >> 1) - 1] [expr {$len >> 1}]]]
    }
}

To complete the set, here's how to get the mode of the list if there is a unique one (relevant for some applications where values are selected from a fairly small set):

proc mode {list} {
    # Compute a histogram
    foreach val $list {dict incr h $val}
    # Sort the histogram in descending order of frequency; type-puns the dict as a list
    set h [lsort -stride 2 -index 1 -descending -integer $h]
    # The mode is now the first element
    return [lindex $h 0]
}

I'll leave handling the empty and non-unique cases as an exercise.


问:
Java HTTP getResponseCode returns 200 for non-existent URL
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

```<code>    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }
</code>```

答:
EDIT: I see you've call openConnection() but not connect() - could that be the problem? I would expect getResponseCode() to actually make the request if it hasn't already, but it's worth just trying that...

That suggests you've possible got some DNS resolver which redirects to a "helper" (spam) page, or something like that.

The easiest way to see exactly what's going on here is to use Wireshark - have that up and capturing traffic (HTTP-only, to make life easier) and then run your code. You should be able to see what's going on that way.

Note that I wouldn't have expected a 404 - because that would involve being able to find a web server to talk to to start with. If you're trying to go to a host which doesn't involve, there shouldn't be an HTTP response at all. I'd expect connect() to throw an exception.

ContentLicense: CC BY-SA 3.0

Body:
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }


问:
Navbar a to change color after certain scrolling
I have a problem I can't seem to solve. So, what I wish to do is when scrolling to a certain distance (preferably scrolling to a specific div box); the navbar  tag should switch color (say red) after reaching its div.

Example:  tag links to #div. When I scroll down to this div, the specific  tag should change color.

    * {
    box-sizing: border-box;
}

html {
    scroll-behavior: smooth;
    font-family: 'Roboto', sans-serif;
}

body {
    width: 100%;
    margin: 0 auto;
}

#logo {
    display: inline;
}

#logoo {
    position: absolute;
    top: 6%;
    left: 2%;
}

.parallax-window {
    width: 100%;
    min-height: 1000px;
    background: transparent;
    position: absolute;
    left: 0;
    top: 0;
}

h1 {
    position: absolute;
    left: 52%;
    top: 45%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-size: 4vw;
    width: 1300px;
    text-transform: uppercase;
}

@media only screen and (max-width:1000px) {
  /* For mobile phones: */
  .nav1, .content, footer {
    width:50%;
  }
}

@media only screen and (max-width:1000px) {
    img, h1, h3 {
        font-size: 4vw;
        width: 90%;
    }
}

.content {
    left: 0;
    position: absolute;
    width: 100%;
    height: 400px;
}

#div {
    margin-top: 62.5rem;
    background-color: #222;
    color: white;
    padding: 20px 20px 5px 80px;
}

h3 {
    font-size: 50px;
    position: absolute;
    top: 0;
}

p {
    margin-top: 150px;
    width: 50%;
    text-align: justify;
}

.me {
    left: 65%;
    position: absolute;
    top: 1.5rem;
}

#me {
    border-radius: 50%;
}

#divv {
    margin-top: 87.5rem;
    background-color: #3b3a3a;
}

ul {
    position: absolute;
    list-style-type: none;
    overflow: hidden;
    background: transparent;
    padding: 0;
    z-index: 1;
    margin-top: 60px;
    left: 38%;
}

li {
    display: inline-block;
    margin: 25px;
}

li a {
    display: block;
    padding: 5px;
    margin: 0 5px;
    text-decoration: none;
}

#hem {
    background-color: #292929;
    position: fixed;
    top: -10rem;
    transition: top 0.3s;
    width: 100%;
    height: 7rem;
    z-index: 1;
}

#hem ul {
    margin-left: 30rem;
}

a span {
    color: white;
    font-size: 20px;
    font-weight: 300;
    text-transform: uppercase;
}

footer {
    position: absolute;
    top: 300%;
    left: 0;
    width: 100%;
    margin: 0px;
    padding: 1.25em;
    background-color: #87ceeb;
    color: white;
    font-size: .85em;
}

footer div {
    margin: auto;
    width: 70%;
    text-align: center;
    padding: 1.25em 0px;
}

.footer-icons a {
    display: inline-block;
    width: 35px;
    height: 35px;
    cursor: pointer;
    background-color: #33383b;
    border-radius: 4px;
    font-size: 20px;
    color: #ffffff;
    text-align: center;
    line-height: 35px;
    margin-right: 3px;
}

#facebook:hover {
    background-color: #3b5998;
    transition: 0.25s linear;
}

#twitter:hover {
    color: #008ad8;
    background-color: white;
    transition: 0.25s linear;
}

#youtube:hover {
    color: #C31A1E;
    transition: 0.25s linear;
}

#instagram:hover {
    background: radial-gradient(circle at 33% 100%, #FED373 4%, #F15245 30%, #D92E7F 62%, #9B36B7 85%, #515ECF);
}

.left-links {
    margin-right: 10px;
}

footer .name {
    font-size: 1.2rem;
}
```

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="sv">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" type="text/css" href="main.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/parallax.js/1.4.2/parallax.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    </head>
    <body>
        <main>
            <div class="parallax-window" data-parallax="scroll" data-image-src="https://i.pinimg.com/originals/bb/e7/42/bbe742c899cb149fadfc5dba9117311b.jpg">
                <header>
                    <nav class="nav1">
                        <div id="logo">
                            <img id="logoo" src="https://git-scm.com/images/logos/downloads/Git-Logo-White.png" height="100" width="239" />
                        </div>
                        <ul>
                            <li>

                                    <span>hem</span>

                            </li>
                            <li>

                                    <span>om mig</span>

                            </li>
                            <li>

                                    <span>mitt arbete</span>

                            </li>
                        </ul>
                    </nav>
                    <nav class="nav2" id="hem">
                        <div class="logo" id="logo">
                            <img id="logoo" src="https://git-scm.com/images/logos/downloads/Git-Logo-White.png" height="100" width="239" />
                        </div>
                        <ul class="ul1">
                            <li>

                                    <span>hem</span>

                            </li>
                            <li>

                                    <span>om mig</span>

                            </li>
                            <li>

                                    <span>mitt arbete</span>

                            </li>
                        </ul>
                    </nav>
                </header>
            </div>
                <h1>Välkommen till min hemsida!</h1>
                <div id="div" class="content">
                    <h3>Om mig</h3>
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                    </p>
                    <div class="me">
                        <img id="me" src="me.jpg" width="263" height="350">
                    </div>
                </div>
                <div id="divv" class="content">

                </div>
        </main>
        <footer>
            <div>
                Have a question? Email us at
                travel@dandeliontours.com
            </div>
            <div class="footer-icons">
                <i class="fa fa-facebook"></i>
                <i class="fa fa-twitter"></i>
                <i class="fa fa-instagram"></i>
                <i class="fa fa-youtube"></i>
            </div>
            <div>
                You'll travel with the wind. <span class="name">Dandelion Tours</span>.
            </div>
        </footer>
        <script>
            window.onscroll = function() {scrollFunction()};

            function scrollFunction() {
                if (document.body.scrollTop > 130 || document.documentElement.scrollTop > 130) {
                    document.getElementById("hem").style.top = "0";
                } else {
                    document.getElementById("hem").style.top = "-10rem";
                }
            }
        </script>
    </body>
</html>
</code>```

P.S: The linked js file is parallax effect scrolling.

Appreciate the help!

Demo: https://jsfiddle.net/xvg26a0e/

答:
i know this is not the optimal solution for this problem. and it will be a lot of code if you have a lot of links but just to give you a solution.

The idea is to get the offset of the divs that triggers your style changing. and listen to your window onscroll event. Whenever you reached the beginning of the div you add a class pre defined, and deleting it whenever you leave the div

in your case :

html :

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" type="text/css" href="main.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/parallax.js/1.4.2/parallax.min.js"></script>
    </head>
    <body>
        <main class="parallax-window" data-parallax="scroll" data-image-src="https://i.pinimg.com/originals/bb/e7/42/bbe742c899cb149fadfc5dba9117311b.jpg">
            <header>
                <nav class="nav1">
                    <ul>
                        <li>
                            <a id="link1">
                                <span>hem</span>
                            </a>
                        </li>
                        <li>
                            <a id="link2">
                                <span>om mig</span>
                            </a>
                        </li>
                        <li>
                            <a>
                                <span>mitt arbete</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </header>
            <div id="div"></div>
            <div id="divv"></div>
        </main>
    </body>
</html>
</code>```

CSS:

```<code>.newClass>span{
  color: red;
}
</code>```

js :

```<code>let div = document.getElementById("div");
let divv = document.getElementById("divv");

let link1 = document.getElementById("link1");
let link2 = document.getElementById("link2");

//getting offset
let divOffset = div.offsetTop;
let divvOffset = divv.offsetTop;

//setting the class when it enters the range
window.onscroll = ()=>{
if (window.pageYOffset >= divOffset && window.pageYOffset <= divvOffset) {
    link1.classList.add("newClass")
  } else {
    link1.classList.remove("newClass");
  }
 if (window.pageYOffset >= divvOffset) {
    link2.classList.add("newClass")
  } else {
    link2.classList.remove("newClass");
  }
}
</code>```

ps: this is not the perfect solution, you can use JQuery to get this done easelly. you can check this link to use that https://codepen.io/latifur/pen/qLKXpj.

Hope that it was helpful

Body:
I have a problem I can't seem to solve. So, what I wish to do is when scrolling to a certain distance (preferably scrolling to a specific div box); the navbar  tag should switch color (say red) after reaching its div.

Example:  tag links to #div. When I scroll down to this div, the specific  tag should change color.

    * {
    box-sizing: border-box;
}

html {
    scroll-behavior: smooth;
    font-family: 'Roboto', sans-serif;
}

body {
    width: 100%;
    margin: 0 auto;
}

#logo {
    display: inline;
}

#logoo {
    position: absolute;
    top: 6%;
    left: 2%;
}

.parallax-window {
    width: 100%;
    min-height: 1000px;
    background: transparent;
    position: absolute;
    left: 0;
    top: 0;
}

h1 {
    position: absolute;
    left: 52%;
    top: 45%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-size: 4vw;
    width: 1300px;
    text-transform: uppercase;
}

@media only screen and (max-width:1000px) {
  /* For mobile phones: */
  .nav1, .content, footer {
    width:50%;
  }
}

@media only screen and (max-width:1000px) {
    img, h1, h3 {
        font-size: 4vw;
        width: 90%;
    }
}

.content {
    left: 0;
    position: absolute;
    width: 100%;
    height: 400px;
}

#div {
    margin-top: 62.5rem;
    background-color: #222;
    color: white;
    padding: 20px 20px 5px 80px;
}

h3 {
    font-size: 50px;
    position: absolute;
    top: 0;
}

p {
    margin-top: 150px;
    width: 50%;
    text-align: justify;
}

.me {
    left: 65%;
    position: absolute;
    top: 1.5rem;
}

#me {
    border-radius: 50%;
}

#divv {
    margin-top: 87.5rem;
    background-color: #3b3a3a;
}

ul {
    position: absolute;
    list-style-type: none;
    overflow: hidden;
    background: transparent;
    padding: 0;
    z-index: 1;
    margin-top: 60px;
    left: 38%;
}

li {
    display: inline-block;
    margin: 25px;
}

li a {
    display: block;
    padding: 5px;
    margin: 0 5px;
    text-decoration: none;
}

#hem {
    background-color: #292929;
    position: fixed;
    top: -10rem;
    transition: top 0.3s;
    width: 100%;
    height: 7rem;
    z-index: 1;
}

#hem ul {
    margin-left: 30rem;
}

a span {
    color: white;
    font-size: 20px;
    font-weight: 300;
    text-transform: uppercase;
}

footer {
    position: absolute;
    top: 300%;
    left: 0;
    width: 100%;
    margin: 0px;
    padding: 1.25em;
    background-color: #87ceeb;
    color: white;
    font-size: .85em;
}

footer div {
    margin: auto;
    width: 70%;
    text-align: center;
    padding: 1.25em 0px;
}

.footer-icons a {
    display: inline-block;
    width: 35px;
    height: 35px;
    cursor: pointer;
    background-color: #33383b;
    border-radius: 4px;
    font-size: 20px;
    color: #ffffff;
    text-align: center;
    line-height: 35px;
    margin-right: 3px;
}

#facebook:hover {
    background-color: #3b5998;
    transition: 0.25s linear;
}

#twitter:hover {
    color: #008ad8;
    background-color: white;
    transition: 0.25s linear;
}

#youtube:hover {
    color: #C31A1E;
    transition: 0.25s linear;
}

#instagram:hover {
    background: radial-gradient(circle at 33% 100%, #FED373 4%, #F15245 30%, #D92E7F 62%, #9B36B7 85%, #515ECF);
}

.left-links {
    margin-right: 10px;
}

footer .name {
    font-size: 1.2rem;
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" type="text/css" href="main.css" />

        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

                                    hem

                                    om mig

                                    mitt arbete

                                    hem

                                    om mig

                                    mitt arbete

Välkommen till min hemsida!

Om mig

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                Have a question? Email us at
                travel@dandeliontours.com

                You'll travel with the wind. Dandelion Tours.

P.S: The linked js file is parallax effect scrolling.

Appreciate the help!

Demo: https://jsfiddle.net/xvg26a0e/

Body:
i know this is not the optimal solution for this problem. and it will be a lot of code if you have a lot of links but just to give you a solution.

The idea is to get the offset of the divs that triggers your style changing. and listen to your window onscroll event. Whenever you reached the beginning of the div you add a class pre defined, and deleting it whenever you leave the div

in your case :

html :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" type="text/css" href="main.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/parallax.js/1.4.2/parallax.min.js"></script>
    </head>
    <body>
        <main class="parallax-window" data-parallax="scroll" data-image-src="https://i.pinimg.com/originals/bb/e7/42/bbe742c899cb149fadfc5dba9117311b.jpg">
            <header>
                <nav class="nav1">
                    <ul>
                        <li>
                            <a id="link1">
                                <span>hem</span>
                            </a>
                        </li>
                        <li>
                            <a id="link2">
                                <span>om mig</span>
                            </a>
                        </li>
                        <li>
                            <a>
                                <span>mitt arbete</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </header>
            <div id="div"></div>
            <div id="divv"></div>
        </main>
    </body>
</html>

CSS:

.newClass>span{
  color: red;
}

js :

let div = document.getElementById("div");
let divv = document.getElementById("divv");

let link1 = document.getElementById("link1");
let link2 = document.getElementById("link2");

//getting offset
let divOffset = div.offsetTop;
let divvOffset = divv.offsetTop;

//setting the class when it enters the range
window.onscroll = ()=>{
if (window.pageYOffset >= divOffset && window.pageYOffset <= divvOffset) {
    link1.classList.add("newClass")
  } else {
    link1.classList.remove("newClass");
  }
 if (window.pageYOffset >= divvOffset) {
    link2.classList.add("newClass")
  } else {
    link2.classList.remove("newClass");
  }
}

ps: this is not the perfect solution, you can use JQuery to get this done easelly. you can check this link to use that https://codepen.io/latifur/pen/qLKXpj.

Hope that it was helpful


问:
Scala Akka Streams Merging Filter And Map
I wonder if there is any way to optimize the following Scala code because it doesn't look very efficient.
Basically, I just want to remove any object which is not a Tweet from the flow and map it to Tweet instead of Any.

```<code>val tweetsFlow = Flow[Any].filter({
  case _: Tweet => true
  case _ => false
}).map({
  case tweet: Tweet => tweet
})
</code>```

答:
Since you're only interested in filtering on a specific type you can use collectType:</p>

```<code>// case class Tweet(title: String)
// val mixedSource: Source[Any, NotUsed] = Source(List(Tweet("1"), 3, Tweet("2")))
val tweetsSource: Source[Tweet, NotUsed] = mixedSource.collectType[Tweet]
// tweetsSource.runForeach(println)
// Tweet("1")
// Tweet("2")
</code>```

Body:
I wonder if there is any way to optimize the following Scala code because it doesn't look very efficient.
Basically, I just want to remove any object which is not a Tweet from the flow and map it to Tweet instead of Any.

val tweetsFlow = Flow[Any].filter({
  case _: Tweet => true
  case _ => false
}).map({
  case tweet: Tweet => tweet
})

Body:
Since you're only interested in filtering on a specific type you can use collectType:

// case class Tweet(title: String)
// val mixedSource: Source[Any, NotUsed] = Source(List(Tweet("1"), 3, Tweet("2")))
val tweetsSource: Source[Tweet, NotUsed] = mixedSource.collectType[Tweet]
// tweetsSource.runForeach(println)
// Tweet("1")
// Tweet("2")


问:
How to optimize the query? t-sql
This query works about 3 minutes and returns 7279 rows:

```<code>SELECT identity(int,1,1) as id, c.client_code, a.account_num,
        c.client_short_name, u.uso, us.fio, null as new, null as txt
INTO #ttable
FROM accounts a INNER JOIN Clients c ON
    c.id = a.client_id INNER JOIN Uso u ON c.uso_id = u.uso_id INNER JOIN
    Magazin m ON a.account_id = m.account_id LEFT JOIN Users us ON
    m.user_id = us.user_id
WHERE m.status_id IN ('1','5','9') AND m.account_new_num is null
    AND u.branch_id = @branch_id
ORDER BY c.client_code;
</code>```

The type of 'client_code' field is VARCHAR(6).

Is it possible to somehow optimize this query?

答:
Insert the records in the Temporary table without using Order by Clause and then Sort them using the c.client_code. Hope it should help you.

Create table #temp
(
your columns...
)

and Insert the records in this table Without Using the Order by Clause. Now run the select with Order by Clause

Title: How to optimize the query? t-sql

Body:
This query works about 3 minutes and returns 7279 rows:

SELECT identity(int,1,1) as id, c.client_code, a.account_num,
        c.client_short_name, u.uso, us.fio, null as new, null as txt
INTO #ttable
FROM accounts a INNER JOIN Clients c ON
    c.id = a.client_id INNER JOIN Uso u ON c.uso_id = u.uso_id INNER JOIN
    Magazin m ON a.account_id = m.account_id LEFT JOIN Users us ON
    m.user_id = us.user_id
WHERE m.status_id IN ('1','5','9') AND m.account_new_num is null
    AND u.branch_id = @branch_id
ORDER BY c.client_code;

The type of 'client_code' field is VARCHAR(6).

Is it possible to somehow optimize this query?


问:
How to hook (swizzle) methods in Swift?
Is there any easy way to hook (swizzle) methods in Swift?</p>

答:
This framework can help: https://github.com/623637646/SwiftHook

How to use

For example, this is your class

class MyObject {
    @objc dynamic func noArgsNoReturnFunc() {
    }
    @objc dynamic func sumFunc(a: Int, b: Int) -> Int {
        return a + b
    }
    @objc dynamic class func classMethodNoArgsNoReturnFunc() {
    }
}
```

<p><img src="https://via.placeholder.com/15/f03c15/000000?text=+" alt="#f03c15"> <strong>The key words of methods <code>@objc</code> and <code>dynamic</code> are necessary</strong></p>

<p><img src="https://via.placeholder.com/15/f03c15/000000?text=+" alt="#f03c15"> <strong>The class doesn't have to inherit from NSObject. If the class is written by Objective-C, Just hook it without any more effort</strong></p>

<ol>
<li>Perform the hook closure before executing specified instance's method.</li>
</ol>

<pre class="lang-swift prettyprint-override"><code>let object = MyObject()
let token = try? hookBefore(object: object, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
object.noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook
</code>```

Perform the hook closure after executing specified instance's method. And get the parameters.

let object = MyObject()
let token = try? hookAfter(object: object, selector: #selector(MyObject.sumFunc(a:b:)), closure: { a, b in
    // get the arguments of the function
    print("arg1 is \(a)") // arg1 is 3
    print("arg2 is \(b)") // arg2 is 4
    } as @convention(block) (Int, Int) -> Void)
_ = object.sumFunc(a: 3, b: 4)
token?.cancelHook() // cancel the hook
```

<p><img src="https://via.placeholder.com/15/f03c15/000000?text=+" alt="#f03c15"> <strong>The key word <code>@convention(block)</code> is necessary</strong></p>

<p><img src="https://via.placeholder.com/15/f03c15/000000?text=+" alt="#f03c15"> <strong>For hook at <code>before</code> and <code>after</code>. The closure's args have to be empty or the same as method. The return type has to be <code>void</code></strong></p>

<ol start="3">
<li>Totally override the mehtod for specified instance. You can call original with the same parameters or different parameters. Don't even call the original method if you want.</li>
</ol>

<pre class="lang-swift prettyprint-override"><code>let object = MyObject()
let token = try? hookInstead(object: object, selector: #selector(MyObject.sumFunc(a:b:)), closure: { original, a, b in
    // get the arguments of the function
    print("arg1 is \(a)") // arg1 is 3
    print("arg2 is \(b)") // arg2 is 4

    // run original function
    let result = original(a, b) // Or change the parameters: let result = original(-1, -2)
    print("original result is \(result)") // result = 7
    return 9
    } as @convention(block) ((Int, Int) -> Int, Int, Int) -> Int)
let result = object.sumFunc(a: 3, b: 4) // result
print("hooked result is \(result)") // result = 9
token?.cancelHook() // cancel the hook
</code>```

 For hook with instead. The closure's first argument has to be a closure which has the same types with the method. The rest args and return type have to be the same as the method.

Perform the hook closure before executing the method of all instances of the class.

let token = try? hookBefore(targetClass: MyObject.self, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
MyObject().noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook
```

<ol start="5">
<li>Perform the hook closure before executing the class method.</li>
</ol>

<pre class="lang-swift prettyprint-override"><code>let token = try? hookClassMethodBefore(targetClass: MyObject.self, selector: #selector(MyObject.classMethodNoArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
MyObject.classMethodNoArgsNoReturnFunc()
token?.cancelHook() // cancel the hook
</code>```

Title: How to hook (swizzle) methods in Swift?

Body:
This framework can help: https://github.com/623637646/SwiftHook

How to use

For example, this is your class

class MyObject {
    @objc dynamic func noArgsNoReturnFunc() {
    }
    @objc dynamic func sumFunc(a: Int, b: Int) -> Int {
        return a + b
    }
    @objc dynamic class func classMethodNoArgsNoReturnFunc() {
    }
}

 The key words of methods @objc and dynamic are necessary

 The class doesn't have to inherit from NSObject. If the class is written by Objective-C, Just hook it without any more effort

Perform the hook closure before executing specified instance's method.

let object = MyObject()
let token = try? hookBefore(object: object, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
object.noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook

Perform the hook closure after executing specified instance's method. And get the parameters.

let object = MyObject()
let token = try? hookAfter(object: object, selector: #selector(MyObject.sumFunc(a:b:)), closure: { a, b in
    // get the arguments of the function
    print("arg1 is \(a)") // arg1 is 3
    print("arg2 is \(b)") // arg2 is 4
    } as @convention(block) (Int, Int) -> Void)
_ = object.sumFunc(a: 3, b: 4)
token?.cancelHook() // cancel the hook

 The key word @convention(block) is necessary

 For hook at before and after. The closure's args have to be empty or the same as method. The return type has to be void

Totally override the mehtod for specified instance. You can call original with the same parameters or different parameters. Don't even call the original method if you want.

let object = MyObject()
let token = try? hookInstead(object: object, selector: #selector(MyObject.sumFunc(a:b:)), closure: { original, a, b in
    // get the arguments of the function
    print("arg1 is \(a)") // arg1 is 3
    print("arg2 is \(b)") // arg2 is 4

    // run original function
    let result = original(a, b) // Or change the parameters: let result = original(-1, -2)
    print("original result is \(result)") // result = 7
    return 9
    } as @convention(block) ((Int, Int) -> Int, Int, Int) -> Int)
let result = object.sumFunc(a: 3, b: 4) // result
print("hooked result is \(result)") // result = 9
token?.cancelHook() // cancel the hook

 For hook with instead. The closure's first argument has to be a closure which has the same types with the method. The rest args and return type have to be the same as the method.

Perform the hook closure before executing the method of all instances of the class.

let token = try? hookBefore(targetClass: MyObject.self, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
MyObject().noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook

Perform the hook closure before executing the class method.

let token = try? hookClassMethodBefore(targetClass: MyObject.self, selector: #selector(MyObject.classMethodNoArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
MyObject.classMethodNoArgsNoReturnFunc()
token?.cancelHook() // cancel the hook


问:
How to get data in Angular 8 when only we have one object to be received
The error I get:

core.js:6260 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

at NgForOf.ngDoCheck (common.js:4406)

  at callHook (core.js:4762)

  at callHooks (core.js:4722)

  at executeCheckHooks (core.js:4642)

  at refreshView (core.js:11979)

  at refreshComponent (core.js:13449)

  at refreshChildComponents (core.js:11689)

  at refreshView (core.js:12024)

  at refreshComponent (core.js:13449)

  at refreshChildComponents (core.js:11689)

The code below works if I have more then one object. When the data is as shown below, and from that, I understand that something is wrong with array or object but I am unable to figure it out. So when I have 2 objects I get the data in the dropdown, but when it is one I get the error mentioned above.

```<code>[
{..},
{..}
]
</code>```

My data Looks like this:

```<code>{
"details_id": 218,
"master_code": 218,
"MstCode": null,
"start_date": "2020-02-29T00:00:00",
"end_date": "2020-02-29T00:00:00",
"canceled": "False   ",
"data_archived": null,
"last_updated_on": "2020-02-28 11:37:08",
"last_updated_by": null
}
</code>```

My http get request code is as below:

```<code>this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res => this.Details = res as TrDetails);
</code>```

My model code:

```<code>export class TrDetails {
    details_id: number;
    master_code: number;
    MstCode: number;
    start_date: Date;
    end_date: Date;
    canceled: string;
    data_archived: string;
    last_updated_on: Date;
    last_updated_by: string;
}
</code>```

My service code:

```<code>apiBaseUrl = "http://localhost:2676/api/";
Details : TrainingDetails;

GetDetails(id){
    this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res =>
    this.Details = res as TrDetails);
  }
</code>```

My dropdown code:

```<code><option *ngFor="let data of service.Details" [value]="data.start_date">{{data.program_start_date}}</option>
</code>```

答:
I think what you need to is this:

```<code>GetDetails(id){
    this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res =>
    this.Details = res.json() as TrDetails);
  }
</code>```

Updating the answer after some discussion:

If res was coming an object, you needed to convert this into an array, else if it's an array assign as it is. Also needed to catch if there's an error :

```<code>GetDetails(id){
    this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res =>
    if(Array.isArray(res)){
        this.Details = res;
    }else{
        this.Details = [res] as any //change any to your type that matches
    }
  }).catch(err => console.log(err));
}
</code>```

Body:
The error I get:

core.js:6260 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

at NgForOf.ngDoCheck (common.js:4406)

  at callHook (core.js:4762)

  at callHooks (core.js:4722)

  at executeCheckHooks (core.js:4642)

  at refreshView (core.js:11979)

  at refreshComponent (core.js:13449)

  at refreshChildComponents (core.js:11689)

  at refreshView (core.js:12024)

  at refreshComponent (core.js:13449)

  at refreshChildComponents (core.js:11689)

The code below works if I have more then one object. When the data is as shown below, and from that, I understand that something is wrong with array or object but I am unable to figure it out. So when I have 2 objects I get the data in the dropdown, but when it is one I get the error mentioned above.

[
{..},
{..}
]

My data Looks like this:

{
"details_id": 218,
"master_code": 218,
"MstCode": null,
"start_date": "2020-02-29T00:00:00",
"end_date": "2020-02-29T00:00:00",
"canceled": "False   ",
"data_archived": null,
"last_updated_on": "2020-02-28 11:37:08",
"last_updated_by": null
}

My http get request code is as below:

this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res => this.Details = res as TrDetails);

My model code:

export class TrDetails {
    details_id: number;
    master_code: number;
    MstCode: number;
    start_date: Date;
    end_date: Date;
    canceled: string;
    data_archived: string;
    last_updated_on: Date;
    last_updated_by: string;
}

My service code:

apiBaseUrl = "http://localhost:2676/api/";
Details : TrainingDetails;

GetDetails(id){
    this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res =>
    this.Details = res as TrDetails);
  }

My dropdown code:

<option *ngFor="let data of service.Details" [value]="data.start_date">{{data.program_start_date}}</option>

Body:
I think what you need to is this:

GetDetails(id){
    this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res =>
    this.Details = res.json() as TrDetails);
  }

Updating the answer after some discussion:

If res was coming an object, you needed to convert this into an array, else if it's an array assign as it is. Also needed to catch if there's an error :

GetDetails(id){
    this.http.get(this.apiBaseUrl+"ProgramDets/"+id).toPromise().then(res =>
    if(Array.isArray(res)){
        this.Details = res;
    }else{
        this.Details = [res] as any //change any to your type that matches
    }
  }).catch(err => console.log(err));
}


答:
service.Details should be an array for *ngFor to work, it seems like the value of service.Details is an object here and hence you getting the error.

Ideally you should not subscribe within your service method, you should just return the observable from your service and subscribe it inside the component.

I recommend you to change your service method to this

```<code> getDetails(id){
    return this.http.get(this.apiBaseUrl+"ProgramDets/"+id);
 }
</code>```

And inside your component wherever you are calling getDetails method you can do this

```<code>this.details = this.service.getDetails(id).pipe(map(res => [res]))
</code>```

Then in your html you can simply use your async operator to subscribe.I would suggest to use observable pattern instead of promise pattern, this will make your code look more clean

```<code><option *ngFor="let data of (details | async)" [value]="data.start_date">{{data.program_start_date}}</option>
</code>```

Title: How to get data in Angular 8 when only we have one object to be received

Body:
service.Details should be an array for *ngFor to work, it seems like the value of service.Details is an object here and hence you getting the error.

Ideally you should not subscribe within your service method, you should just return the observable from your service and subscribe it inside the component.

I recommend you to change your service method to this

 getDetails(id){
    return this.http.get(this.apiBaseUrl+"ProgramDets/"+id);
 }

And inside your component wherever you are calling getDetails method you can do this

this.details = this.service.getDetails(id).pipe(map(res => [res]))

Then in your html you can simply use your async operator to subscribe.I would suggest to use observable pattern instead of promise pattern, this will make your code look more clean

<option *ngFor="let data of (details | async)" [value]="data.start_date">{{data.program_start_date}}</option>


问:
Integrating a Web API and a .net MVC Project (C#)
I do have 2 projects, one written in Web API and other in MVC , it just uploading the data to azure blob storage , both my projects are in in running state but when it comes to integrating both in one particular solution in VS , I am facing issues in it.
Please help, I am an entry level developer in this industry.</p>

答:
You can place both the MVC and WebAPI in the same project.  This answer on StackOverflow may help you:

How to Use mvc Controller and WebAPI Controller in Same Project


问:
ASP.NET - redirect 301
How do I redirect permanently in ASP DOT NET? I'd like to do a 301 redirect from one page on my site to another page. </p>

答:
```<code>protected void Page_PreInit(object sender, EventArgs e)
{
    Response.StatusCode = 301;
    Response.StatusDescription = "Moved Permanently";
    Response.RedirectLocation = "AnotherPage.aspx";
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}
</code>```

And in 4.0, there's a simple HttpResponse.RedirectPermanent() method that does everything above for you:

```<code>Response.RedirectPermanent("AnotherPage.aspx");
</code>```

OwnerDisplayName: Arjun

ContentLicense: CC BY-SA 2.5

Title: ASP.NET - redirect 301

LastEditorDisplayName: Joel Coehoorn

Body:
protected void Page_PreInit(object sender, EventArgs e)
{
    Response.StatusCode = 301;
    Response.StatusDescription = "Moved Permanently";
    Response.RedirectLocation = "AnotherPage.aspx";
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

And in 4.0, there's a simple HttpResponse.RedirectPermanent() method that does everything above for you:

Response.RedirectPermanent("AnotherPage.aspx");

OwnerDisplayName: cxfx


问:
Can't get <select> input from form?
I can figure out how to loop through input and select. My function below does not include select lists.

Any help welcome.

```<code>$('input', '#consumer_form').each(function(key, value)
{
    if ((this.type === "radio" || this.type === "checkbox") && this.checked === false) {
        return;
    } else {
         val = this.value;
    }

         //alert($('#'+this.id).attr('name')+'='+replaceAmp(val));
             formData += '&'+this.name+'='+replaceAmp(val);

});
</code>```

Thanks

答:
Try</p>

```<code>$('input, select', '#consumer_form').each(function(key, value)
</code>```

Title: Can't get <select> input from form?

Body:
I can figure out how to loop through input and select. My function below does not include select lists.

Any help welcome.

$('input', '#consumer_form').each(function(key, value)
{
    if ((this.type === "radio" || this.type === "checkbox") && this.checked === false) {
        return;
    } else {
         val = this.value;
    }

         //alert($('#'+this.id).attr('name')+'='+replaceAmp(val));
             formData += '&'+this.name+'='+replaceAmp(val);

});

Thanks

Body:
Try

$('input, select', '#consumer_form').each(function(key, value)


问:
Does DOORS maintain a history of all the modules I have worked in?

Background

I am currently doing a task where I am relinking objects inside a module (Module_B). While relinking, I forgot to include a new "Link_" column to set up the new links for Module_C.  Therefore I erroneously linked to the wrong module (Module_D).  I did not realize this until I looked at both the links to the old module (Module_A) and the new module (Module_D but should be Module_C).  Now all the links inside the Link_Module_A and Link_Module_C columns of Module_B go to nowhere.

I need to figure which module contains my mistake, that is, I want to find which Module was Module_B.

Question

Is there a way I can find the history of all modules that I have opened in DOORS?

答:
AFAIK, there is no built-in running history of modules that have been opened for vanilla DOORS.

I know on the database I work on, we created a trigger to log what you're asking for.

Assuming you're not the admin, maybe you can ask your admin if they have something like this implemented on the database you're working on.


问:
RxSwift Text field Delegate Methods
I'm new to RxSwift. I need to ask how can I bind textField delegate methods using RxSwift like textFieldShouldReturn or textViewDidBeginEditing.  </p>

答:
RxSwift, RxSwiftExt, RxCocoa 5.0:</p>

```<code>let textField = UITextField()
textField.rx.controlEvent(.editingDidBegin).subscribe(onNext: { () in

}, onError: { (error) in

}, onCompleted: {

}).disposed(by: disposeBag)
</code>```

Title: RxSwift Text field Delegate Methods

Body:
RxSwift, RxSwiftExt, RxCocoa 5.0:

let textField = UITextField()
textField.rx.controlEvent(.editingDidBegin).subscribe(onNext: { () in

}, onError: { (error) in

}, onCompleted: {

}).disposed(by: disposeBag)


问:
Sonarqube integration and startSonar.bat failed Error(0x2)
Yesterday I started a new Unreal Engine Project on Visual Studio Team Service, I decided to learn by myself the art of videogames programming.
Anyway the best thing I wanted to use for this project was to integrate SonarQube in Visual Studio and get reports from it (I already used it at University and it was really useful for me), but I had some curious Problems:

First of all, I wanted to run the analisys on my Local PC, the problem is that today i ran the bat and i got this problem, I already checked somewhere for this problem but I believe It's not the %JAVA_HOME% Variable.

```<code>Wrapper Started as Console
Launching a JVM...
Unable to execute Java command.  Impossibile trovare il file specificato. (0x2)
    "java" -Djava.awt.headless=true -Xms3m -Xmx3m -Djava.library.path="./lib" -classpath "../../lib/jsw/wrapper-3.2.3.jar;../../lib/sonar-application-6.1.jar"
-Dwrapper.key="GMa9Ff98pvtqrHYZ" -Dwrapper.port=32000 -Dwrapper.jvm.port.min=31000 -Dwrapper.jvm.port.max=31999 -Dwrapper.pid=6352 -Dwrapper.version="3.2.3" -Dwrapper.native_library="wrapper" -Dwrapper.cpu.timeout="10" -Dwrapper.jvmid=1 org.tanukisoftware.wrapper.WrapperSimpleApp org.sonar.application.App
Critical error: wait for JVM process failed
</code>```

If I'm able to solve this problem I have  the necessity to understand how to integrate the code analysis in my Build definition on VSTS Locally (It requires a correct  Endpoint and I don't know how to set it).

Last but not least, if i'm am not able to run this Build Definition Locally, is there any online free server that supports SonarQube to use it and finally get a report from SonarQube?

EDIT:

Wrapper Config

```<code># Path to JVM executable. By default it must be available in PATH.
# Can be an absolute path, for example:
set Mypath=C:/Program Files
wrapper.java.command=%Mypath%\Java\jdk1.8.0_77\bin\java
wrapper.java.command=java

#
# DO NOT EDIT THE FOLLOWING SECTIONS
#

#********************************************************************
# Wrapper Java
#********************************************************************
wrapper.java.additional.1=-Djava.awt.headless=true
wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp
wrapper.java.classpath.1=../../lib/jsw/*.jar
wrapper.java.classpath.2=../../lib/*.jar
wrapper.java.library.path.1=./lib
wrapper.app.parameter.1=org.sonar.application.App
wrapper.java.initmemory=3
wrapper.java.maxmemory=3

#********************************************************************
# Wrapper Logs
#********************************************************************

wrapper.console.format=PM
wrapper.console.loglevel=INFO
wrapper.logfile=../../logs/sonar.log
wrapper.logfile.format=M
wrapper.logfile.loglevel=INFO

# Maximum size that the log file will be allowed to grow to before
#  the log is rolled. Size is specified in bytes.  The default value
#  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or
#  'm' (mb) suffix.  For example: 10m = 10 megabytes.
#wrapper.logfile.maxsize=0

# Maximum number of rolled log files which will be allowed before old
#  files are deleted.  The default value of 0 implies no limit.
#wrapper.logfile.maxfiles=0

# Log Level for sys/event log output.  (See docs for log levels)
wrapper.syslog.loglevel=NONE

#********************************************************************
# Wrapper Windows Properties
#********************************************************************
# Title to use when running as a console
wrapper.console.title=SonarQube

# Disallow start of multiple instances of an application at the same time on Windows
wrapper.single_invocation=true

#********************************************************************
# Wrapper Windows NT/2000/XP Service Properties
#********************************************************************
# WARNING - Do not modify any of these properties when an application
#  using this configuration file has been installed as a service.
#  Please uninstall the service before modifying this section.  The
#  service can then be reinstalled.

# Name of the service
wrapper.ntservice.name=SonarQube

# Display name of the service
wrapper.ntservice.displayname=SonarQube

# Description of the service
wrapper.ntservice.description=SonarQube

# Service dependencies.  Add dependencies as needed starting from 1
wrapper.ntservice.dependency.1=

# Mode in which the service is installed.  AUTO_START or DEMAND_START
wrapper.ntservice.starttype=AUTO_START

# Allow the service to interact with the desktop.
wrapper.ntservice.interactive=false

#********************************************************************
# Forking Properties
#********************************************************************
wrapper.disable_restarts=TRUE
wrapper.ping.timeout=0
wrapper.shutdown.timeout=3000
wrapper.jvm_exit.timeout=3000
</code>```

Sonar Config

```<code>    # Property values can:
# - reference an environment variable, for example sonar.jdbc.url= ${env:SONAR_JDBC_URL}
# - be encrypted. See http://redirect.sonarsource.com/doc/settings-encryption.html

#--------------------------------------------------------------------------------------------------
# DATABASE
#
# IMPORTANT: the embedded H2 database is used by default. It is recommended for tests but not for
# production use. Supported databases are MySQL, Oracle, PostgreSQL and Microsoft SQLServer.

# User credentials.
# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
#sonar.jdbc.username=
#sonar.jdbc.password=

#----- Embedded Database (default)
# H2 embedded database server listening port, defaults to 9092
#sonar.embeddedDatabase.port=9092
#----- MySQL 5.6 or greater
# Only InnoDB storage engine is supported (not myISAM).
# Only the bundled driver is supported. It can not be changed.
#sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance

#----- Oracle 11g/12c
# - Only thin client is supported
# - Only versions 11.2.x and 12.x of Oracle JDBC driver are supported
# - The JDBC driver must be copied into the directory extensions/jdbc-driver/oracle/
# - If you need to set the schema, please refer to http://jira.sonarsource.com/browse/SONAR-5000
#sonar.jdbc.url=jdbc:oracle:thin:@localhost:1521/XE

#----- PostgreSQL 8.x/9.x
# If you don't use the schema named "public", please refer to http://jira.sonarsource.com/browse/SONAR-5000
#sonar.jdbc.url=jdbc:postgresql://localhost/sonar

#----- Microsoft SQLServer 2012/2014 and SQL Azure
# A database named sonar must exist and its collation must be case-sensitive (CS) and accent-sensitive (AS)
# Use the following connection string if you want to use integrated security with Microsoft Sql Server
# Do not set sonar.jdbc.username or sonar.jdbc.password property if you are using Integrated Security
# For Integrated Security to work, you have to download the Microsoft SQL JDBC driver package from
# http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11774
# and copy sqljdbc_auth.dll to your path. You have to copy the 32 bit or 64 bit version of the dll
# depending upon the architecture of your server machine.
# This version of SonarQube has been tested with Microsoft SQL JDBC version 4.1
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar;integratedSecurity=true

# Use the following connection string if you want to use SQL Auth while connecting to MS Sql Server.
# Set the sonar.jdbc.username and sonar.jdbc.password appropriately.
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar

#----- Connection pool settings
# The maximum number of active connections that can be allocated
# at the same time, or negative for no limit.
# The recommended value is 1.2 * max sizes of HTTP pools. For example if HTTP ports are
# enabled with default sizes (50, see property sonar.web.http.maxThreads)
# then sonar.jdbc.maxActive should be 1.2 * (50) = 120.
#sonar.jdbc.maxActive=60

# The maximum number of connections that can remain idle in the
# pool, without extra ones being released, or negative for no limit.
#sonar.jdbc.maxIdle=5

# The minimum number of connections that can remain idle in the pool,
# without extra ones being created, or zero to create none.
#sonar.jdbc.minIdle=2

# The maximum number of milliseconds that the pool will wait (when there
# are no available connections) for a connection to be returned before
# throwing an exception, or <= 0 to wait indefinitely.
#sonar.jdbc.maxWait=5000

#sonar.jdbc.minEvictableIdleTimeMillis=600000
#sonar.jdbc.timeBetweenEvictionRunsMillis=30000

#--------------------------------------------------------------------------------------------------
# WEB SERVER
# Web server is executed in a dedicated Java process. By default heap size is 512Mb.
# Use the following property to customize JVM options.
#    Recommendations:
#
#    The HotSpot Server VM is recommended. The property -server should be added if server mode
#    is not enabled by default on your environment:
#    http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
#
#    Startup can be long if entropy source is short of entropy. Adding
#    -Djava.security.egd=file:/dev/./urandom is an option to resolve the problem.
#    See https://wiki.apache.org/tomcat/HowTo/FasterStartUp#Entropy_Source
#
#sonar.web.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError

# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.web.javaAdditionalOpts=

# Binding IP address. For servers with more than one IP address, this property specifies which
# address will be used for listening on the specified ports.
# By default, ports will be used on all IP addresses associated with the server.
#sonar.web.host=0.0.0.0

# Web context. When set, it must start with forward slash (for example /sonarqube).
# The default value is root context (empty value).
#sonar.web.context=
# TCP port for incoming HTTP connections. Default value is 9000.
sonar.web.port=8888

# The maximum number of connections that the server will accept and process at any given time.
# When this number has been reached, the server will not accept any more connections until
# the number of connections falls below this value. The operating system may still accept connections
# based on the sonar.web.connections.acceptCount property. The default value is 50.
#sonar.web.http.maxThreads=50

# The minimum number of threads always kept running. The default value is 5.
#sonar.web.http.minThreads=5

# The maximum queue length for incoming connection requests when all possible request processing
# threads are in use. Any requests received when the queue is full will be refused.
# The default value is 25.
#sonar.web.http.acceptCount=25

# By default users are logged out and sessions closed when server is restarted.
# If you prefer keeping user sessions open, a secret should be defined. Value is
# HS256 key encoded with base64. It must be unique for each installation of SonarQube.
# Example of command-line:
# echo -n "type_what_you_want" | openssl dgst -sha256 -hmac "key" -binary | base64
#sonar.auth.jwtBase64Hs256Secret=

#--------------------------------------------------------------------------------------------------
# COMPUTE ENGINE
# The Compute Engine is responsible for processing background tasks.
# Compute Engine is executed in a dedicated Java process. Default heap size is 512Mb.
# Use the following property to customize JVM options.
#    Recommendations:
#
#    The HotSpot Server VM is recommended. The property -server should be added if server mode
#    is not enabled by default on your environment:
#    http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
#
#sonar.ce.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError

# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.ce.javaAdditionalOpts=
# The number of workers in the Compute Engine. Value must be greater than zero.
# By default the Compute Engine uses a single worker and therefore processes tasks one at a time.
#    Recommendations:
#
#    Using N workers will require N times as much Heap memory (see property
#    sonar.ce.javaOpts to tune heap) and produce N times as much IOs on disk, database and
#    Elasticsearch. The number of workers must suit your environment.
#sonar.ce.workerCount=1

#--------------------------------------------------------------------------------------------------
# ELASTICSEARCH
# Elasticsearch is used to facilitate fast and accurate information retrieval.
# It is executed in a dedicated Java process. Default heap size is 1Gb.

# JVM options of Elasticsearch process
#    Recommendations:
#
#    Use HotSpot Server VM. The property -server should be added if server mode
#    is not enabled by default on your environment:
#    http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
#
#sonar.search.javaOpts=-Xmx1G -Xms256m -Xss256k -Djna.nosys=true \
#  -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 \
#  -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError

# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.search.javaAdditionalOpts=

# Elasticsearch port. Default is 9001. Use 0 to get a free port.
# As a security precaution, should be blocked by a firewall and not exposed to the Internet.
#sonar.search.port=9001

# Elasticsearch host. The search server will bind this address and the search client will connect to it.
# Default is 127.0.0.1.
# As a security precaution, should NOT be set to a publicly available address.
#sonar.search.host=127.0.0.1

#--------------------------------------------------------------------------------------------------
# UPDATE CENTER

# Update Center requires an internet connection to request https://update.sonarsource.org
# It is enabled by default.
#sonar.updatecenter.activate=true

# HTTP proxy (default none)
#http.proxyHost=
#http.proxyPort=
# HTTPS proxy (defaults are values of http.proxyHost and http.proxyPort)
#https.proxyHost=
#https.proxyPort=

# NT domain name if NTLM proxy is used
#http.auth.ntlm.domain=

# SOCKS proxy (default none)
#socksProxyHost=
#socksProxyPort=

# Proxy authentication (used for HTTP, HTTPS and SOCKS proxies)
#http.proxyUser=
#http.proxyPassword=

#--------------------------------------------------------------------------------------------------
# LOGGING

# Level of logs. Supported values are INFO(default), DEBUG and TRACE (DEBUG + SQL + ES requests)
#sonar.log.level=INFO

# Path to log files. Can be absolute or relative to installation directory.
# Default is <installation home>/logs
#sonar.path.logs=logs

# Rolling policy of log files
#    - based on time if value starts with "time:", for example by day ("time:yyyy-MM-dd")
#      or by month ("time:yyyy-MM")
#    - based on size if value starts with "size:", for example "size:10MB"
#    - disabled if value is "none".  That needs logs to be managed by an external system like logrotate.
#sonar.log.rollingPolicy=time:yyyy-MM-dd

# Maximum number of files to keep if a rolling policy is enabled.
#    - maximum value is 20 on size rolling policy
#    - unlimited on time rolling policy. Set to zero to disable old file purging.
#sonar.log.maxFiles=7

# Access log is the list of all the HTTP requests received by server. If enabled, it is stored
# in the file {sonar.path.logs}/access.log. This file follows the same rolling policy as for
# sonar.log (see sonar.log.rollingPolicy and sonar.log.maxFiles).
#sonar.web.accessLogs.enable=true

# Format of access log. It is ignored if sonar.web.accessLogs.enable=false. Possible values are:
#    - "common" is the Common Log Format, shortcut to: %h %l %u %user %date "%r" %s %b
#    - "combined" is another format widely recognized, shortcut to: %h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}"
#    - else a custom pattern. See http://logback.qos.ch/manual/layouts.html#AccessPatternLayout.
# The login of authenticated user is not implemented with "%u" but with "%reqAttribute{LOGIN}" (since version 6.1).
# The value displayed for anonymous users is "-".
# If SonarQube is behind a reverse proxy, then the following value allows to display the correct remote IP address:
#sonar.web.accessLogs.pattern=%i{X-Forwarded-For} %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}"
# Default value is:
#sonar.web.accessLogs.pattern=combined

#--------------------------------------------------------------------------------------------------
# OTHERS

# Delay in seconds between processing of notification queue. Default is 60 seconds.
#sonar.notifications.delay=60

# Paths to persistent data files (embedded database and search index) and temporary files.
# Can be absolute or relative to installation directory.
# Defaults are respectively <installation home>/data and <installation home>/temp
#sonar.path.data=data
#sonar.path.temp=temp

#--------------------------------------------------------------------------------------------------
# DEVELOPMENT - only for developers
# The following properties MUST NOT be used in production environments.

# Dev mode allows to reload web sources on changes and to restart server when new versions
# of plugins are deployed.
#sonar.web.dev=false

# Path to webapp sources for hot-reloading of Ruby on Rails, JS and CSS (only core,
# plugins not supported).
#sonar.web.dev.sources=/path/to/server/sonar-web/src/main/webapp

# Elasticsearch HTTP connector, for example for KOPF:
# http://lmenezes.com/elasticsearch-kopf/?location=http://localhost:9010
#sonar.search.httpPort=-1
</code>```

答:
I have updated JDK path in wrapper.conf file and it worked. Now, Wrapper.conf file looks like below:</p>

```<code># Path to JVM executable. By default it must be available in PATH.
# Can be an absolute path, for example:
wrapper.java.command=C:\Program Files\Java\jdk-11.0.7\bin\java
#wrapper.java.command=java
</code>```

Body:
Yesterday I started a new Unreal Engine Project on Visual Studio Team Service, I decided to learn by myself the art of videogames programming.
Anyway the best thing I wanted to use for this project was to integrate SonarQube in Visual Studio and get reports from it (I already used it at University and it was really useful for me), but I had some curious Problems:

First of all, I wanted to run the analisys on my Local PC, the problem is that today i ran the bat and i got this problem, I already checked somewhere for this problem but I believe It's not the %JAVA_HOME% Variable.

Wrapper Started as Console
Launching a JVM...
Unable to execute Java command.  Impossibile trovare il file specificato. (0x2)
    "java" -Djava.awt.headless=true -Xms3m -Xmx3m -Djava.library.path="./lib" -classpath "../../lib/jsw/wrapper-3.2.3.jar;../../lib/sonar-application-6.1.jar"
-Dwrapper.key="GMa9Ff98pvtqrHYZ" -Dwrapper.port=32000 -Dwrapper.jvm.port.min=31000 -Dwrapper.jvm.port.max=31999 -Dwrapper.pid=6352 -Dwrapper.version="3.2.3" -Dwrapper.native_library="wrapper" -Dwrapper.cpu.timeout="10" -Dwrapper.jvmid=1 org.tanukisoftware.wrapper.WrapperSimpleApp org.sonar.application.App
Critical error: wait for JVM process failed

If I'm able to solve this problem I have  the necessity to understand how to integrate the code analysis in my Build definition on VSTS Locally (It requires a correct  Endpoint and I don't know how to set it).

Last but not least, if i'm am not able to run this Build Definition Locally, is there any online free server that supports SonarQube to use it and finally get a report from SonarQube?

EDIT:

Wrapper Config

# Path to JVM executable. By default it must be available in PATH.
# Can be an absolute path, for example:
set Mypath=C:/Program Files
wrapper.java.command=%Mypath%\Java\jdk1.8.0_77\bin\java
wrapper.java.command=java

#
# DO NOT EDIT THE FOLLOWING SECTIONS
#

#********************************************************************
# Wrapper Java
#********************************************************************
wrapper.java.additional.1=-Djava.awt.headless=true
wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp
wrapper.java.classpath.1=../../lib/jsw/*.jar
wrapper.java.classpath.2=../../lib/*.jar
wrapper.java.library.path.1=./lib
wrapper.app.parameter.1=org.sonar.application.App
wrapper.java.initmemory=3
wrapper.java.maxmemory=3

#********************************************************************
# Wrapper Logs
#********************************************************************

wrapper.console.format=PM
wrapper.console.loglevel=INFO
wrapper.logfile=../../logs/sonar.log
wrapper.logfile.format=M
wrapper.logfile.loglevel=INFO

# Maximum size that the log file will be allowed to grow to before
#  the log is rolled. Size is specified in bytes.  The default value
#  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or
#  'm' (mb) suffix.  For example: 10m = 10 megabytes.
#wrapper.logfile.maxsize=0

# Maximum number of rolled log files which will be allowed before old
#  files are deleted.  The default value of 0 implies no limit.
#wrapper.logfile.maxfiles=0

# Log Level for sys/event log output.  (See docs for log levels)
wrapper.syslog.loglevel=NONE

#********************************************************************
# Wrapper Windows Properties
#********************************************************************
# Title to use when running as a console
wrapper.console.title=SonarQube

# Disallow start of multiple instances of an application at the same time on Windows
wrapper.single_invocation=true

#********************************************************************
# Wrapper Windows NT/2000/XP Service Properties
#********************************************************************
# WARNING - Do not modify any of these properties when an application
#  using this configuration file has been installed as a service.
#  Please uninstall the service before modifying this section.  The
#  service can then be reinstalled.

# Name of the service
wrapper.ntservice.name=SonarQube

# Display name of the service
wrapper.ntservice.displayname=SonarQube

# Description of the service
wrapper.ntservice.description=SonarQube

# Service dependencies.  Add dependencies as needed starting from 1
wrapper.ntservice.dependency.1=

# Mode in which the service is installed.  AUTO_START or DEMAND_START
wrapper.ntservice.starttype=AUTO_START

# Allow the service to interact with the desktop.
wrapper.ntservice.interactive=false

#********************************************************************
# Forking Properties
#********************************************************************
wrapper.disable_restarts=TRUE
wrapper.ping.timeout=0
wrapper.shutdown.timeout=3000
wrapper.jvm_exit.timeout=3000

Sonar Config

    # Property values can:
# - reference an environment variable, for example sonar.jdbc.url= ${env:SONAR_JDBC_URL}
# - be encrypted. See http://redirect.sonarsource.com/doc/settings-encryption.html

#--------------------------------------------------------------------------------------------------
# DATABASE
#
# IMPORTANT: the embedded H2 database is used by default. It is recommended for tests but not for
# production use. Supported databases are MySQL, Oracle, PostgreSQL and Microsoft SQLServer.

# User credentials.
# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
#sonar.jdbc.username=
#sonar.jdbc.password=

#----- Embedded Database (default)
# H2 embedded database server listening port, defaults to 9092
#sonar.embeddedDatabase.port=9092
#----- MySQL 5.6 or greater
# Only InnoDB storage engine is supported (not myISAM).
# Only the bundled driver is supported. It can not be changed.
#sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance

#----- Oracle 11g/12c
# - Only thin client is supported
# - Only versions 11.2.x and 12.x of Oracle JDBC driver are supported
# - The JDBC driver must be copied into the directory extensions/jdbc-driver/oracle/
# - If you need to set the schema, please refer to http://jira.sonarsource.com/browse/SONAR-5000
#sonar.jdbc.url=jdbc:oracle:thin:@localhost:1521/XE

#----- PostgreSQL 8.x/9.x
# If you don't use the schema named "public", please refer to http://jira.sonarsource.com/browse/SONAR-5000
#sonar.jdbc.url=jdbc:postgresql://localhost/sonar

#----- Microsoft SQLServer 2012/2014 and SQL Azure
# A database named sonar must exist and its collation must be case-sensitive (CS) and accent-sensitive (AS)
# Use the following connection string if you want to use integrated security with Microsoft Sql Server
# Do not set sonar.jdbc.username or sonar.jdbc.password property if you are using Integrated Security
# For Integrated Security to work, you have to download the Microsoft SQL JDBC driver package from
# http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11774
# and copy sqljdbc_auth.dll to your path. You have to copy the 32 bit or 64 bit version of the dll
# depending upon the architecture of your server machine.
# This version of SonarQube has been tested with Microsoft SQL JDBC version 4.1
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar;integratedSecurity=true

# Use the following connection string if you want to use SQL Auth while connecting to MS Sql Server.
# Set the sonar.jdbc.username and sonar.jdbc.password appropriately.
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar

#----- Connection pool settings
# The maximum number of active connections that can be allocated
# at the same time, or negative for no limit.
# The recommended value is 1.2 * max sizes of HTTP pools. For example if HTTP ports are
# enabled with default sizes (50, see property sonar.web.http.maxThreads)
# then sonar.jdbc.maxActive should be 1.2 * (50) = 120.
#sonar.jdbc.maxActive=60

# The maximum number of connections that can remain idle in the
# pool, without extra ones being released, or negative for no limit.
#sonar.jdbc.maxIdle=5

# The minimum number of connections that can remain idle in the pool,
# without extra ones being created, or zero to create none.
#sonar.jdbc.minIdle=2

# The maximum number of milliseconds that the pool will wait (when there
# are no available connections) for a connection to be returned before
# throwing an exception, or <= 0 to wait indefinitely.
#sonar.jdbc.maxWait=5000

#sonar.jdbc.minEvictableIdleTimeMillis=600000
#sonar.jdbc.timeBetweenEvictionRunsMillis=30000

#--------------------------------------------------------------------------------------------------
# WEB SERVER
# Web server is executed in a dedicated Java process. By default heap size is 512Mb.
# Use the following property to customize JVM options.
#    Recommendations:
#
#    The HotSpot Server VM is recommended. The property -server should be added if server mode
#    is not enabled by default on your environment:
#    http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
#
#    Startup can be long if entropy source is short of entropy. Adding
#    -Djava.security.egd=file:/dev/./urandom is an option to resolve the problem.
#    See https://wiki.apache.org/tomcat/HowTo/FasterStartUp#Entropy_Source
#
#sonar.web.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError

# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.web.javaAdditionalOpts=

# Binding IP address. For servers with more than one IP address, this property specifies which
# address will be used for listening on the specified ports.
# By default, ports will be used on all IP addresses associated with the server.
#sonar.web.host=0.0.0.0

# Web context. When set, it must start with forward slash (for example /sonarqube).
# The default value is root context (empty value).
#sonar.web.context=
# TCP port for incoming HTTP connections. Default value is 9000.
sonar.web.port=8888

# The maximum number of connections that the server will accept and process at any given time.
# When this number has been reached, the server will not accept any more connections until
# the number of connections falls below this value. The operating system may still accept connections
# based on the sonar.web.connections.acceptCount property. The default value is 50.
#sonar.web.http.maxThreads=50

# The minimum number of threads always kept running. The default value is 5.
#sonar.web.http.minThreads=5

# The maximum queue length for incoming connection requests when all possible request processing
# threads are in use. Any requests received when the queue is full will be refused.
# The default value is 25.
#sonar.web.http.acceptCount=25

# By default users are logged out and sessions closed when server is restarted.
# If you prefer keeping user sessions open, a secret should be defined. Value is
# HS256 key encoded with base64. It must be unique for each installation of SonarQube.
# Example of command-line:
# echo -n "type_what_you_want" | openssl dgst -sha256 -hmac "key" -binary | base64
#sonar.auth.jwtBase64Hs256Secret=

#--------------------------------------------------------------------------------------------------
# COMPUTE ENGINE
# The Compute Engine is responsible for processing background tasks.
# Compute Engine is executed in a dedicated Java process. Default heap size is 512Mb.
# Use the following property to customize JVM options.
#    Recommendations:
#
#    The HotSpot Server VM is recommended. The property -server should be added if server mode
#    is not enabled by default on your environment:
#    http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
#
#sonar.ce.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError

# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.ce.javaAdditionalOpts=
# The number of workers in the Compute Engine. Value must be greater than zero.
# By default the Compute Engine uses a single worker and therefore processes tasks one at a time.
#    Recommendations:
#
#    Using N workers will require N times as much Heap memory (see property
#    sonar.ce.javaOpts to tune heap) and produce N times as much IOs on disk, database and
#    Elasticsearch. The number of workers must suit your environment.
#sonar.ce.workerCount=1

#--------------------------------------------------------------------------------------------------
# ELASTICSEARCH
# Elasticsearch is used to facilitate fast and accurate information retrieval.
# It is executed in a dedicated Java process. Default heap size is 1Gb.

# JVM options of Elasticsearch process
#    Recommendations:
#
#    Use HotSpot Server VM. The property -server should be added if server mode
#    is not enabled by default on your environment:
#    http://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
#
#sonar.search.javaOpts=-Xmx1G -Xms256m -Xss256k -Djna.nosys=true \
#  -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 \
#  -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError

# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.search.javaAdditionalOpts=

# Elasticsearch port. Default is 9001. Use 0 to get a free port.
# As a security precaution, should be blocked by a firewall and not exposed to the Internet.
#sonar.search.port=9001

# Elasticsearch host. The search server will bind this address and the search client will connect to it.
# Default is 127.0.0.1.
# As a security precaution, should NOT be set to a publicly available address.
#sonar.search.host=127.0.0.1

#--------------------------------------------------------------------------------------------------
# UPDATE CENTER

# Update Center requires an internet connection to request https://update.sonarsource.org
# It is enabled by default.
#sonar.updatecenter.activate=true

# HTTP proxy (default none)
#http.proxyHost=
#http.proxyPort=
# HTTPS proxy (defaults are values of http.proxyHost and http.proxyPort)
#https.proxyHost=
#https.proxyPort=

# NT domain name if NTLM proxy is used
#http.auth.ntlm.domain=

# SOCKS proxy (default none)
#socksProxyHost=
#socksProxyPort=

# Proxy authentication (used for HTTP, HTTPS and SOCKS proxies)
#http.proxyUser=
#http.proxyPassword=

#--------------------------------------------------------------------------------------------------
# LOGGING

# Level of logs. Supported values are INFO(default), DEBUG and TRACE (DEBUG + SQL + ES requests)
#sonar.log.level=INFO

# Path to log files. Can be absolute or relative to installation directory.
# Default is <installation home>/logs
#sonar.path.logs=logs

# Rolling policy of log files
#    - based on time if value starts with "time:", for example by day ("time:yyyy-MM-dd")
#      or by month ("time:yyyy-MM")
#    - based on size if value starts with "size:", for example "size:10MB"
#    - disabled if value is "none".  That needs logs to be managed by an external system like logrotate.
#sonar.log.rollingPolicy=time:yyyy-MM-dd

# Maximum number of files to keep if a rolling policy is enabled.
#    - maximum value is 20 on size rolling policy
#    - unlimited on time rolling policy. Set to zero to disable old file purging.
#sonar.log.maxFiles=7

# Access log is the list of all the HTTP requests received by server. If enabled, it is stored
# in the file {sonar.path.logs}/access.log. This file follows the same rolling policy as for
# sonar.log (see sonar.log.rollingPolicy and sonar.log.maxFiles).
#sonar.web.accessLogs.enable=true

# Format of access log. It is ignored if sonar.web.accessLogs.enable=false. Possible values are:
#    - "common" is the Common Log Format, shortcut to: %h %l %u %user %date "%r" %s %b
#    - "combined" is another format widely recognized, shortcut to: %h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}"
#    - else a custom pattern. See http://logback.qos.ch/manual/layouts.html#AccessPatternLayout.
# The login of authenticated user is not implemented with "%u" but with "%reqAttribute{LOGIN}" (since version 6.1).
# The value displayed for anonymous users is "-".
# If SonarQube is behind a reverse proxy, then the following value allows to display the correct remote IP address:
#sonar.web.accessLogs.pattern=%i{X-Forwarded-For} %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}"
# Default value is:
#sonar.web.accessLogs.pattern=combined

#--------------------------------------------------------------------------------------------------
# OTHERS

# Delay in seconds between processing of notification queue. Default is 60 seconds.
#sonar.notifications.delay=60

# Paths to persistent data files (embedded database and search index) and temporary files.
# Can be absolute or relative to installation directory.
# Defaults are respectively <installation home>/data and <installation home>/temp
#sonar.path.data=data
#sonar.path.temp=temp

#--------------------------------------------------------------------------------------------------
# DEVELOPMENT - only for developers
# The following properties MUST NOT be used in production environments.

# Dev mode allows to reload web sources on changes and to restart server when new versions
# of plugins are deployed.
#sonar.web.dev=false

# Path to webapp sources for hot-reloading of Ruby on Rails, JS and CSS (only core,
# plugins not supported).
#sonar.web.dev.sources=/path/to/server/sonar-web/src/main/webapp

# Elasticsearch HTTP connector, for example for KOPF:
# http://lmenezes.com/elasticsearch-kopf/?location=http://localhost:9010
#sonar.search.httpPort=-1

Body:
I have updated JDK path in wrapper.conf file and it worked. Now, Wrapper.conf file looks like below:

# Path to JVM executable. By default it must be available in PATH.
# Can be an absolute path, for example:
wrapper.java.command=C:\Program Files\Java\jdk-11.0.7\bin\java
#wrapper.java.command=java