问:
Why do nullable numbers not preserve identity?
In kotlin nullable values are not preserving identity but equality:

```<code>val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'
</code>```

Why is this different ?

答:
In kotlin , we have two different concepts of equality, Referential equality and Structural equality

Referential equality

We use the === symbol which allows us to evaluate the reference of an object(if it's pointing to the same object). This is an equivalent of "==" operator in java. thats why boxedA === anotherBoxedA return false(Because they are two separate objects, each pointing to a different location in memory).

Structural Equality

We use the == symbol that evaluates if both values are the same (or equal). This is usually achieved by implementing equals() method in java.
That's why it boxedA == anotherBoxedA it return true

Body:
In kotlin nullable values are not preserving identity but equality:

val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'

Why is this different ?


来源: stackexchange

问:
d3 v4 donut chart has text and poylines that overlap with small values
I am trying to figure out how to arrange the labels so that they do not overlap. Here is a picture of the chart

As you can see, with really small values, the text labels overlap. I tried to iterate over each text element and modify it's position, but that doesn't seem to be working. You can see at the bottom of this function that I tried to get the position of each text element and then modify it. What am I doing wrong? I've been at it for hours.

```<code>   _renderDonutChart() {
    let self = this;
    // console.log("Donut Chart is beginning render")
    let textOffset = 14;
    self.graph.data[0].forEach(function (d) {
        d.value = +d.value;
    })
    console.log(self.graph.data[0])
    let boxSize = (self.options.radius + self.options.padding) * 2;
    let parent = d3.select(self.ui.parent);
    //let color = d3.scaleOrdinal(['#dc8710', '#9e3400', '#f19b12']);
    let color = d3.scaleOrdinal(d3.schemeCategory20c);
    let svg = parent.append('svg')
        .attr('width', boxSize * 2)
        .attr('height', boxSize)
        .attr('transform', 'translate(-111,0)')
        .append('g')
        .attr('transform', 'translate(' + boxSize + ',' + boxSize / 2 + ')');
    svg.append('g')
        .attr('class', 'slices')
    svg.append("g")
        .attr("class", "labelName")
    svg.append("g")
        .attr("class", "labelValue")
    svg.append("g")
        .attr("class", "lines")
    svg.append("div")
        .attr("class", "progress-circle__box progress-circle__box--victorytype")
    let arc = d3.arc()
        .innerRadius(self.options.radius - self.options.border)
        .outerRadius(self.options.radius);
    let outerArc = d3.arc()
        .innerRadius((self.options.radius - self.options.border) * 1.2)
        .outerRadius((self.options.radius) * 1.2);
    let legendRectSize = self.options.radius * 0.05;
    let legendSpacing  = self.options.radius * 0.02;
    let pie = d3.pie()
        .value(function(d) { return d.value; })
        .sort(null);
    let slice = svg.select('.slices')
        .selectAll('path.slice')
        .data(pie(self.graph.data[0]))
        .enter()
        .append('path')
        .attr("class", "slice")
        .attr('d', arc)
        .attr('fill', function(d, i) {
            return color(d.data.label);
        })
        .transition().duration(1000)
        .attrTween("d", function(d) {
            this._current = this._current || 0;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                return arc(interpolate(t));
            };
        })

    function midAngle(d){
        return d.startAngle + (d.endAngle - d.startAngle)/2;
    }
    let text = svg.select(".labelName").selectAll("text")
        .data(pie(self.graph.data[0]))
        .enter()
        .append("text")
        .attr('class', 'label')
        .attr("dy", ".35em")
        .attr('transform', function(d) {

            // effectively computes the centre of the slice.
            // see https://github.com/d3/d3-shape/blob/master/README.md#arc_centroid
            var pos = outerArc.centroid(d);

            // changes the point to be on left or right depending on where label is.
            pos[0] = self.options.radius * 0.97 * (midAngle(d) < Math.PI ? 1 : -1);
            return 'translate(' + pos + ')';
        })
        .style('text-anchor', function(d) {
            // if slice centre is on the left, anchor text to start, otherwise anchor to end
            return (midAngle(d)) < Math.PI ? 'start' : 'end';
        })
        .style("fill", "white")
        .text(function(d) {
            return (" " + d.data.label+": " +d.value+"");
        })
        .transition().duration(1000)
        .attrTween("transform", function(d) {
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                var pos = outerArc.centroid(d2);
                pos[0] = self.options.radius * (midAngle(d2) < Math.PI ? 1 : -1);
                return "translate("+ pos +")";
            };
        })
        .styleTween("text-anchor", function(d){
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                return midAngle(d2) < Math.PI ? "start":"end";
            };
        })
        .text(function(d) {
            return (d.data.label+": "+d.value+"%");
        })
    let polyline = svg.select(".lines").selectAll("polyline")
        .data(pie(self.graph.data[0]))
        .enter()
        .append("polyline")
        .attr('points', function(d) {
            var pos = outerArc.centroid(d);
            pos[0] = self.options.radius * 0.95 * (midAngle(d) < Math.PI ? 1 : -1);
            return [arc.centroid(d), outerArc.centroid(d), pos]
        })
        .style("fill", "none")
        .style("stroke", "white")
        .style("stroke-width", "1px");

    let prev;
    text.each(function(d, i) {
        if(i > 0) {
            let thisbb = this.getBoundingClientRect(),
                prevbb = prev.getBoundingClientRect();
            // move if they overlap
            console.log(thisbb.left);
            console.log(prevbb.right);
            if(!(thisbb.right < prevbb.left ||
                thisbb.left > prevbb.right ||
                thisbb.bottom < prevbb.top ||
                thisbb.top > prevbb.bottom)) {
                var ctx = thisbb.left + (thisbb.right - thisbb.left)/2,
                    cty = thisbb.top + (thisbb.bottom - thisbb.top)/2,
                    cpx = prevbb.left + (prevbb.right - prevbb.left)/2,
                    cpy = prevbb.top + (prevbb.bottom - prevbb.top)/2,
                    off = Math.sqrt(Math.pow(ctx - cpx, 2) + Math.pow(cty - cpy, 2))/2;
                d3.select(this).attr("transform",
                    "translate(" + Math.cos(((d.startAngle + d.endAngle - Math.PI) / 2)) *
                    (self.options.radius + textOffset + off) + "," +
                    Math.sin((d.startAngle + d.endAngle - Math.PI) / 2) *
                    (self.options.radius + textOffset + off) + ")");
            }
        }
        prev = this;
    });

    // console.log("Donut Chart is ending render")
}
</code>```

答:
I thing you had same problem with this, you need to add more margin to your pie chart segment, assume your pie return 3% value, and you draw a text with line, it will stack on another, you need to devine margin if that value < 3 draw text with y+margin

```<code> if(percent<3){
       o[1]
       pos[1] += i*15
       }
       //return [label.centroid(d),[o[0],0[1]] , pos];
        return [label.centroid(d),[o[0],pos[1]] , pos];
      })
</code>```

try to append this code structure to your chart

ContentLicense: CC BY-SA 3.0

Body:
I am trying to figure out how to arrange the labels so that they do not overlap. Here is a picture of the chart

As you can see, with really small values, the text labels overlap. I tried to iterate over each text element and modify it's position, but that doesn't seem to be working. You can see at the bottom of this function that I tried to get the position of each text element and then modify it. What am I doing wrong? I've been at it for hours.

   _renderDonutChart() {
    let self = this;
    // console.log("Donut Chart is beginning render")
    let textOffset = 14;
    self.graph.data[0].forEach(function (d) {
        d.value = +d.value;
    })
    console.log(self.graph.data[0])
    let boxSize = (self.options.radius + self.options.padding) * 2;
    let parent = d3.select(self.ui.parent);
    //let color = d3.scaleOrdinal(['#dc8710', '#9e3400', '#f19b12']);
    let color = d3.scaleOrdinal(d3.schemeCategory20c);
    let svg = parent.append('svg')
        .attr('width', boxSize * 2)
        .attr('height', boxSize)
        .attr('transform', 'translate(-111,0)')
        .append('g')
        .attr('transform', 'translate(' + boxSize + ',' + boxSize / 2 + ')');
    svg.append('g')
        .attr('class', 'slices')
    svg.append("g")
        .attr("class", "labelName")
    svg.append("g")
        .attr("class", "labelValue")
    svg.append("g")
        .attr("class", "lines")
    svg.append("div")
        .attr("class", "progress-circle__box progress-circle__box--victorytype")
    let arc = d3.arc()
        .innerRadius(self.options.radius - self.options.border)
        .outerRadius(self.options.radius);
    let outerArc = d3.arc()
        .innerRadius((self.options.radius - self.options.border) * 1.2)
        .outerRadius((self.options.radius) * 1.2);
    let legendRectSize = self.options.radius * 0.05;
    let legendSpacing  = self.options.radius * 0.02;
    let pie = d3.pie()
        .value(function(d) { return d.value; })
        .sort(null);
    let slice = svg.select('.slices')
        .selectAll('path.slice')
        .data(pie(self.graph.data[0]))
        .enter()
        .append('path')
        .attr("class", "slice")
        .attr('d', arc)
        .attr('fill', function(d, i) {
            return color(d.data.label);
        })
        .transition().duration(1000)
        .attrTween("d", function(d) {
            this._current = this._current || 0;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                return arc(interpolate(t));
            };
        })

    function midAngle(d){
        return d.startAngle + (d.endAngle - d.startAngle)/2;
    }
    let text = svg.select(".labelName").selectAll("text")
        .data(pie(self.graph.data[0]))
        .enter()
        .append("text")
        .attr('class', 'label')
        .attr("dy", ".35em")
        .attr('transform', function(d) {

            // effectively computes the centre of the slice.
            // see https://github.com/d3/d3-shape/blob/master/README.md#arc_centroid
            var pos = outerArc.centroid(d);

            // changes the point to be on left or right depending on where label is.
            pos[0] = self.options.radius * 0.97 * (midAngle(d) < Math.PI ? 1 : -1);
            return 'translate(' + pos + ')';
        })
        .style('text-anchor', function(d) {
            // if slice centre is on the left, anchor text to start, otherwise anchor to end
            return (midAngle(d)) < Math.PI ? 'start' : 'end';
        })
        .style("fill", "white")
        .text(function(d) {
            return (" " + d.data.label+": " +d.value+"");
        })
        .transition().duration(1000)
        .attrTween("transform", function(d) {
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                var pos = outerArc.centroid(d2);
                pos[0] = self.options.radius * (midAngle(d2) < Math.PI ? 1 : -1);
                return "translate("+ pos +")";
            };
        })
        .styleTween("text-anchor", function(d){
            this._current = this._current || d;
            var interpolate = d3.interpolate(this._current, d);
            this._current = interpolate(0);
            return function(t) {
                var d2 = interpolate(t);
                return midAngle(d2) < Math.PI ? "start":"end";
            };
        })
        .text(function(d) {
            return (d.data.label+": "+d.value+"%");
        })
    let polyline = svg.select(".lines").selectAll("polyline")
        .data(pie(self.graph.data[0]))
        .enter()
        .append("polyline")
        .attr('points', function(d) {
            var pos = outerArc.centroid(d);
            pos[0] = self.options.radius * 0.95 * (midAngle(d) < Math.PI ? 1 : -1);
            return [arc.centroid(d), outerArc.centroid(d), pos]
        })
        .style("fill", "none")
        .style("stroke", "white")
        .style("stroke-width", "1px");

    let prev;
    text.each(function(d, i) {
        if(i > 0) {
            let thisbb = this.getBoundingClientRect(),
                prevbb = prev.getBoundingClientRect();
            // move if they overlap
            console.log(thisbb.left);
            console.log(prevbb.right);
            if(!(thisbb.right < prevbb.left ||
                thisbb.left > prevbb.right ||
                thisbb.bottom < prevbb.top ||
                thisbb.top > prevbb.bottom)) {
                var ctx = thisbb.left + (thisbb.right - thisbb.left)/2,
                    cty = thisbb.top + (thisbb.bottom - thisbb.top)/2,
                    cpx = prevbb.left + (prevbb.right - prevbb.left)/2,
                    cpy = prevbb.top + (prevbb.bottom - prevbb.top)/2,
                    off = Math.sqrt(Math.pow(ctx - cpx, 2) + Math.pow(cty - cpy, 2))/2;
                d3.select(this).attr("transform",
                    "translate(" + Math.cos(((d.startAngle + d.endAngle - Math.PI) / 2)) *
                    (self.options.radius + textOffset + off) + "," +
                    Math.sin((d.startAngle + d.endAngle - Math.PI) / 2) *
                    (self.options.radius + textOffset + off) + ")");
            }
        }
        prev = this;
    });

    // console.log("Donut Chart is ending render")
}

Body:
I thing you had same problem with this, you need to add more margin to your pie chart segment, assume your pie return 3% value, and you draw a text with line, it will stack on another, you need to devine margin if that value < 3 draw text with y+margin

 if(percent<3){
       o[1]
       pos[1] += i*15
       }
       //return [label.centroid(d),[o[0],0[1]] , pos];
        return [label.centroid(d),[o[0],pos[1]] , pos];
      })

try to append this code structure to your chart


问:
Highest appearance of a value within each group
I'm having a table with an user-ID and the Webside-IDs he navigated through. The table looks like this:

```<code>| user-ID | website-ID |
|       1 |          1 |
|       1 |          2 |
|       1 |          1 |
|       1 |          4 |
|       2 |          1 |
|       2 |          2 |
|       2 |          5 |
|       2 |          2 |
</code>```

I'd like to select the website-ID each user has been into the most. As you can see, a min, max or avg won't work here.  Any ideas?

答:
I've introduced a temporary table just to make things a little easier to read. You could certainly substitute that query inline and eliminate the temp table if desired.

The first select sums the visits per user and website.

The second select finds the maximum visits for each user in the subquery and then joins back to the temp table to find the webiste whose count matches that maximum value.

```<code>create temporary table TempSum
    select user-ID, website-ID, count(*) as TotalCount
        from YourTable
        group by user-ID, website-ID

select ts.user-ID, ts.website-ID, ts.TotalCount
    from (select user-ID, max(TotalCount) as MaxCount
              from TempSum
              group by user-ID) ms
        inner join TempSum ts
            on ts.user-ID = ms.user-ID
                and ts.TotalCount = ms.MaxCount
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm having a table with an user-ID and the Webside-IDs he navigated through. The table looks like this:

| user-ID | website-ID |
|       1 |          1 |
|       1 |          2 |
|       1 |          1 |
|       1 |          4 |
|       2 |          1 |
|       2 |          2 |
|       2 |          5 |
|       2 |          2 |

I'd like to select the website-ID each user has been into the most. As you can see, a min, max or avg won't work here.  Any ideas?

Body:
I've introduced a temporary table just to make things a little easier to read. You could certainly substitute that query inline and eliminate the temp table if desired.

The first select sums the visits per user and website.

The second select finds the maximum visits for each user in the subquery and then joins back to the temp table to find the webiste whose count matches that maximum value.

create temporary table TempSum
    select user-ID, website-ID, count(*) as TotalCount
        from YourTable
        group by user-ID, website-ID

select ts.user-ID, ts.website-ID, ts.TotalCount
    from (select user-ID, max(TotalCount) as MaxCount
              from TempSum
              group by user-ID) ms
        inner join TempSum ts
            on ts.user-ID = ms.user-ID
                and ts.TotalCount = ms.MaxCount


问:
Why the downloaded web pages have so long *.js files?
I am learning to develop a website.
I am the backend developer but have no experience in this web development.

I have several good references such as https://mvs.org/
In order to see how many lines of code or structure of the web pages, I downloaded the entire web page using Httrack.

I am surprised that a few *.js files include around 60,000 lines of code.
Does it mean that the web developer of the pages wrote that many codes?
or am I missing something here?

答:
Front end development implies different requirements than when one is developing on the backend.

Your context is the browser and you want to reduce the number of HTTP requests as much as possible, thus you generally bundle all your javascript files into one big file using tools such as webpack.

Your code will then be bundled with all the needed npm modules, that's why you end up with one large javascript file.


问:
How to handle session to keep login information using Spring MVC

I want to make login form with Spring MVC using Hibernate.

I found that I need to use 'session' to keep login information.

So, I use it in 'Controller.java', '.jsp'.

But It seems didn't work.

Below is my code. Controller.java:

```<code>@Controller
public class PassengerController {

    @Autowired
    private PassengerService passengerService;

    public void setPassengerService(PassengerService passengerService) {
        this.passengerService = passengerService;
    }

    @RequestMapping(value = "/login")
    public String login(HttpSession session, HttpServletRequest request) {

        String id = request.getParameter("idInput");
        String pw = request.getParameter("pwInput");

        // check DB
        // if it is right, add session.
        session.setAttribute("id", id);
        session.setAttribute("pw", pw);

        return "flightschedule";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "flightschedule";
    }

}
</code>```

Below is part of flightschedule.jsp:

```<code><c:if test="${sessionScope.loginId eq null}">
    <!-- Not login: show login button  -->
    <div class="loginArea">
        <form action="${loginAction}">     <!-- // URL '/login' -->
            <input type="text" name="idInput" placeholder="ID" class="loginInput">
            <input type="password" name="pwInput" placeholder="PASSWORD" class="loginInput">
            <input id="loginButton" type="submit" value="login">
        </form>
    </div>
</c:if>

<c:if test="${sessionScope.loginId ne null}">
    <!-- already login: show logout button -->
    <div class="loginArea">
        <form action="${logoutAction}">  <!-- // URL '/logout' -->
            <input type="button" name="idInput" id="loginInfo" value="Welcome ${sessionScope.loginId}">
            <input id="logoutButton" type="submit" value="LOGOUT">
        </form>
    </div>
</c:if>
</code>```

I intended that when session.id exists, show log out button and when session.id doesn't exist, show login button.

I don't want to use interceptors or spring security etc..

I thought they're too complex to my little project.

And, I have login/logout form at all most of my pages. I don't use a separate page to login.

So I don't want to use interceptor. I just want to check whether session key exists in some jsp pages. Depending on its presence, I want to change page's view.

Above's code work partly. When login, it shows 'Welcome userId'.

But, when I click page's logo(then go to the first page), It still show 'login' button. It have to show 'log-out' button becuase session.loginId exists!

Do you have any solution?

答:
In login method you put

```<code> // check DB
    // if it is right, add session.
    session.setAttribute("id", id);
    session.setAttribute("pw", pw);
</code>```

but on JSP check sessionScope.loginId , looks like you should check attribute with name id.

Body:
I want to make login form with Spring MVC using Hibernate.

I found that I need to use 'session' to keep login information.

So, I use it in 'Controller.java', '.jsp'.

But It seems didn't work.

Below is my code. Controller.java:

@Controller
public class PassengerController {

    @Autowired
    private PassengerService passengerService;

    public void setPassengerService(PassengerService passengerService) {
        this.passengerService = passengerService;
    }

    @RequestMapping(value = "/login")
    public String login(HttpSession session, HttpServletRequest request) {

        String id = request.getParameter("idInput");
        String pw = request.getParameter("pwInput");

        // check DB
        // if it is right, add session.
        session.setAttribute("id", id);
        session.setAttribute("pw", pw);

        return "flightschedule";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "flightschedule";
    }

}

Below is part of flightschedule.jsp:

<c:if test="${sessionScope.loginId eq null}">

        <form action="${loginAction}">
            <input type="text" name="idInput" placeholder="ID" class="loginInput">
            <input type="password" name="pwInput" placeholder="PASSWORD" class="loginInput">
            <input id="loginButton" type="submit" value="login">
        </form>

</c:if>

<c:if test="${sessionScope.loginId ne null}">

        <form action="${logoutAction}">
            <input type="button" name="idInput" id="loginInfo" value="Welcome ${sessionScope.loginId}">
            <input id="logoutButton" type="submit" value="LOGOUT">
        </form>

</c:if>

I intended that when session.id exists, show log out button and when session.id doesn't exist, show login button.

I don't want to use interceptors or spring security etc..

I thought they're too complex to my little project.

And, I have login/logout form at all most of my pages. I don't use a separate page to login.

So I don't want to use interceptor. I just want to check whether session key exists in some jsp pages. Depending on its presence, I want to change page's view.

Above's code work partly. When login, it shows 'Welcome userId'.

But, when I click page's logo(then go to the first page), It still show 'login' button. It have to show 'log-out' button becuase session.loginId exists!

Do you have any solution?

Body:
In login method you put

 // check DB
    // if it is right, add session.
    session.setAttribute("id", id);
    session.setAttribute("pw", pw);

but on JSP check sessionScope.loginId , looks like you should check attribute with name id.


问:
combine blocks of code to one function
How can I make one function to do something like this</p>

```<code>$('#check_express').is(':checked') ? $('#form_express').show() : $('#form_express').hide();

$('#check_express').on('change', function(){
    $(this).is(':checked') ? $('#form_express').show() :
    $('#form_express').hide();
});

$('#check_standard').is(':checked') ? $('#form_standard').show() : $('#form_standard').hide();

$('#check_standard').on('change', function(){
    $(this).is(':checked') ? $('#form_standard').show() :
    $('#form_standard').hide();
});
</code>```

答:
First you can extract the code into a function

```<code>function bind_stuff(type) {
  $('#check_' + type).is(':checked') ? $('#form_' + type).show() : $('#form_' + type).hide();

  $('#check_' + type).on('change', function(){
      $(this).is(':checked') ? $('#form_' + type).show() :
      $('#form_' + type).hide();
  });
}

bind_stuff('express');
bind_stuff('standard');
</code>```

You can then shorten the show/hide-Parts by using toggle, which takes an optional boolean parameter which indicates whether to show or hide:

```<code>function bind_stuff(type) {
  $('#form_' + type).toggle($('#check_' + type).is(':checked'));

  $('#check_' + type).on('change', function(){
      $('#form_' + type).toggle($(this).is(':checked'));
  });
}
bind_stuff('express');
bind_stuff('standard');
</code>```

If you want to go further, you can reduce the initializing part by faking an change event:

```<code>function bind_stuff(type) {
  $('#check_' + type).on('change', function(){
      $('#form_' + type).toggle($(this).is(':checked'));
  });
  $('#check_' + type).trigger('change');
}

bind_stuff('express');
bind_stuff('standard');
</code>```

Title: combine blocks of code to one function

Body:
How can I make one function to do something like this

$('#check_express').is(':checked') ? $('#form_express').show() : $('#form_express').hide();

$('#check_express').on('change', function(){
    $(this).is(':checked') ? $('#form_express').show() :
    $('#form_express').hide();
});

$('#check_standard').is(':checked') ? $('#form_standard').show() : $('#form_standard').hide();

$('#check_standard').on('change', function(){
    $(this).is(':checked') ? $('#form_standard').show() :
    $('#form_standard').hide();
});

Body:
First you can extract the code into a function

function bind_stuff(type) {
  $('#check_' + type).is(':checked') ? $('#form_' + type).show() : $('#form_' + type).hide();

  $('#check_' + type).on('change', function(){
      $(this).is(':checked') ? $('#form_' + type).show() :
      $('#form_' + type).hide();
  });
}

bind_stuff('express');
bind_stuff('standard');

You can then shorten the show/hide-Parts by using toggle, which takes an optional boolean parameter which indicates whether to show or hide:

function bind_stuff(type) {
  $('#form_' + type).toggle($('#check_' + type).is(':checked'));

  $('#check_' + type).on('change', function(){
      $('#form_' + type).toggle($(this).is(':checked'));
  });
}
bind_stuff('express');
bind_stuff('standard');

If you want to go further, you can reduce the initializing part by faking an change event:

function bind_stuff(type) {
  $('#check_' + type).on('change', function(){
      $('#form_' + type).toggle($(this).is(':checked'));
  });
  $('#check_' + type).trigger('change');
}

bind_stuff('express');
bind_stuff('standard');


问:
Java Priority queue error about poll
I am having trouble with priority queue of poll. My try is this:

```<code>public int [][] MST(int i, int prim[][], int mst[][], int vertices, int counter, PriorityQueue priorityQueue){
    Table table = new Table();
    int next_row;
    for(int j=0;j<vertices;j++)
    {
        table.s = i;
        table.d = j;
        table.w = prim[i][j];

        priorityQueue.add(table);
    }
    table = priorityQueue.poll();
    mst[counter][0] = table.s;
    mst[counter][1] = table.d;
    return mst;

}
</code>```

Then I got error at priorityQueue.poll(). It says required Table, but found java.lang.Object.

How should I solve this problem?

答:
Use Typecasting as</p>

```<code>PriorityQueue prq = new PriorityQueue();
prq.add (new Table (values)) ;
Table data = (Table) prq.poll();
</code>```

Title: Java Priority queue error about poll

Body:
I am having trouble with priority queue of poll. My try is this:

public int [][] MST(int i, int prim[][], int mst[][], int vertices, int counter, PriorityQueue priorityQueue){
    Table table = new Table();
    int next_row;
    for(int j=0;j<vertices;j++)
    {
        table.s = i;
        table.d = j;
        table.w = prim[i][j];

        priorityQueue.add(table);
    }
    table = priorityQueue.poll();
    mst[counter][0] = table.s;
    mst[counter][1] = table.d;
    return mst;

}

Then I got error at priorityQueue.poll(). It says required Table, but found java.lang.Object.

How should I solve this problem?

Body:
Use Typecasting as

PriorityQueue prq = new PriorityQueue();
prq.add (new Table (values)) ;
Table data = (Table) prq.poll();


问:
Why does the regex (aba?)+ not match with abab?
Given (aba?)+ as the Regex and abab is the string.

Why does it only matches aba?

Since the last a in the regex is optional, isn't abab a match as well?

tested on https://regex101.com/

答:
The reason (aba?)+ only matches aba out of abab is greedy matching: The optional a in the first loop is tested before the group is tested again, and matches. Therefore, the remaining string is b, which does not match (aba?) again.

If you want to turn off greedy matching for this optional a, use  a??, or write your regex differently.


问:
How to get size of mysql database?
How to get size of a mysql database?

Suppose the target database is called "v3".

答:
It can be determined by using following MySQL command

```<code>SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema
</code>```

Result

```<code>Database    Size (MB)
db1         11.75678253
db2         9.53125000
test        50.78547382
</code>```

Get result in GB

```<code>SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 / 1024 AS "Size (GB)" FROM information_schema.TABLES GROUP BY table_schema
</code>```

Title: How to get size of mysql database?

Body:
It can be determined by using following MySQL command

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema

Result

Database    Size (MB)
db1         11.75678253
db2         9.53125000
test        50.78547382

Get result in GB

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 / 1024 AS "Size (GB)" FROM information_schema.TABLES GROUP BY table_schema

ContentLicense: CC BY-SA 4.0


问:
auto-starting Mule flow
I'm trying this approach to autostart a Mule flow

Starting a mule flow programmatically using groovy

and it does not start the flow. Here's a very simple test run in Mule Studio with the 3.4.0 CE

```<code><?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting"
xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="CE-3.4.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">

<flow name="auto2Flow1" doc:name="auto2Flow1">
    <scripting:component doc:name="Groovy">
        <scripting:script engine="Groovy">
             muleContext.registry.lookupFlowConstruct('flow1').start()
        </scripting:script>
    </scripting:component>
</flow>

<flow name="flow1" doc:name="flow1">
    <logger level="INFO" doc:name="Logger" message="hello"/>
</flow>

</mule>
</code>```

I also tried this with no luck

```<code><expression-component>
   app.registry.flow1.start();
</expression-component>
</code>```

I'm assuming flow1 is automatically registered but not sure.

答:
You should not start the flow manually. Once you deployed your mule application locally or in cloud or on premise the flow will start automatically.
If you would like to stop the flow or freeze the flow for some time then you can use some groovy Script something like sleep(1000); for some time</p>

Title: auto-starting Mule flow

Body:
I'm trying this approach to autostart a Mule flow

Starting a mule flow programmatically using groovy

and it does not start the flow. Here's a very simple test run in Mule Studio with the 3.4.0 CE

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting"
xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="CE-3.4.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">

<flow name="auto2Flow1" doc:name="auto2Flow1">

    </scripting:component>
</flow>

<flow name="flow1" doc:name="flow1">
    <logger level="INFO" doc:name="Logger" message="hello"/>
</flow>

</mule>

I also tried this with no luck

<expression-component>
   app.registry.flow1.start();
</expression-component>

I'm assuming flow1 is automatically registered but not sure.


问:
Get data from dynamically added input
I have an input field where the user enters article ID and compare.
On first application load, the user has by default three input field, but he can dynamically add more inputs.My problem is, how to get the entered value of dynamically added inputs and send them to URL
for example like this (I know how to put id's to URL, this is only for showing what I need)
'https://someurl.com/' + ID + '/someurl'

I try to make function where I pass entered value to controller but I get UNDEFINED

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {

 $scope.choices = [{id: ''}, {id: ''}, {id: ''}];

 $scope.addNewChoice = function() {
  var newItemNo = $scope.choices.length+1;
  $scope.choices.push({'id':newItemNo});
 };

 $scope.showChoiceLabel = function (choice) {
  return choice.id === $scope.choices[0].id;
 }

 $scope.submitChoice = function (name) {
  alert('url ' + name + ' url');
 }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 font-family:Arial;
 color:#333;
}
label {
 font-weight:bold;
}
#choicesDisplay {
 margin-top:1em;
}
.form-group {
 width:70%;clear:both;
}
.form-group input {
 float:right;
 width:60%;
 padding:.3em;
}
button {
 background-color:#3f7ebc;
 color:white;
 padding: .5em .7em .5em .7em;
 font-weight:bold;
 border:none;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Custom Plunker</title>

  <link rel="stylesheet" href="style.css" />

   Choices
   <button ng-show="$last" ng-click="addNewChoice()">Add another choice</button>
   <input type="text" ng-model="choice.name" name="" placeholder="enter id">
  <button ng-click="submitChoice(choice.name)">Submit</button>

   {{ choices }}

```

答:
It is not working because, your submit button is outside of the scope.

1) You either move the button inside loop to submit individually

or

2) Submit multiple instances by loooping all.

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {

 $scope.choices = [{id: ''}, {id: ''}, {id: ''}];

 $scope.addNewChoice = function() {
  var newItemNo = $scope.choices.length+1;
  $scope.choices.push({'id':newItemNo});
 };

 $scope.showChoiceLabel = function (choice) {
  return choice.id === $scope.choices[0].id;
 }

 $scope.submitChoice = function (name) {
  $scope.choices.forEach(function(choice, index){
  alert('url ' + choice.name + ' url');
  if(choice.name)
  {
  switch (index) {
    case 0:
        $scope.first = choice.name;
        break;
    case 1:
        $scope.second = choice.name;
        break;
    case 2:
        $scope.third = choice.name;
        break;
    case 3:
        $scope.fourth = choice.name;
        break;
}
console.log($scope.first,$scope.second,$scope.third,$scope.fourth)
  }

  })

 }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 font-family:Arial;
 color:#333;
}
label {
 font-weight:bold;
}
#choicesDisplay {
 margin-top:1em;
}
.form-group {
 width:70%;clear:both;
}
.form-group input {
 float:right;
 width:60%;
 padding:.3em;
}
button {
 background-color:#3f7ebc;
 color:white;
 padding: .5em .7em .5em .7em;
 font-weight:bold;
 border:none;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Custom Plunker</title>

  <link rel="stylesheet" href="style.css" />

   Choices
   <button ng-show="$last" ng-click="addNewChoice()">Add another choice</button>
   <input type="text" ng-model="choice.name" name="" placeholder="enter id">

    <button ng-click="submitChoice()">Submit</button>

   {{ choices }}

```

Please run the above snippet for second example

PS: As per your request, based on the index of the choice in loop, assigned the choice names to respective scope variables using switch case.

Title: Get data from dynamically added input

Body:
I have an input field where the user enters article ID and compare.
On first application load, the user has by default three input field, but he can dynamically add more inputs.My problem is, how to get the entered value of dynamically added inputs and send them to URL
for example like this (I know how to put id's to URL, this is only for showing what I need)
'https://someurl.com/' + ID + '/someurl'

I try to make function where I pass entered value to controller but I get UNDEFINED

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {

 $scope.choices = [{id: ''}, {id: ''}, {id: ''}];

 $scope.addNewChoice = function() {
  var newItemNo = $scope.choices.length+1;
  $scope.choices.push({'id':newItemNo});
 };

 $scope.showChoiceLabel = function (choice) {
  return choice.id === $scope.choices[0].id;
 }

 $scope.submitChoice = function (name) {
  alert('url ' + name + ' url');
 }
});

body {
 font-family:Arial;
 color:#333;
}
label {
 font-weight:bold;
}
#choicesDisplay {
 margin-top:1em;
}
.form-group {
 width:70%;clear:both;
}
.form-group input {
 float:right;
 width:60%;
 padding:.3em;
}
button {
 background-color:#3f7ebc;
 color:white;
 padding: .5em .7em .5em .7em;
 font-weight:bold;
 border:none;
}

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Custom Plunker</title>

  <link rel="stylesheet" href="style.css" />

   Choices
   <button ng-show="$last" ng-click="addNewChoice()">Add another choice</button>
   <input type="text" ng-model="choice.name" name="" placeholder="enter id">
  <button ng-click="submitChoice(choice.name)">Submit</button>

   {{ choices }}

Body:
It is not working because, your submit button is outside of the scope.

1) You either move the button inside loop to submit individually

or

2) Submit multiple instances by loooping all.

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {

 $scope.choices = [{id: ''}, {id: ''}, {id: ''}];

 $scope.addNewChoice = function() {
  var newItemNo = $scope.choices.length+1;
  $scope.choices.push({'id':newItemNo});
 };

 $scope.showChoiceLabel = function (choice) {
  return choice.id === $scope.choices[0].id;
 }

 $scope.submitChoice = function (name) {
  $scope.choices.forEach(function(choice, index){
  alert('url ' + choice.name + ' url');
  if(choice.name)
  {
  switch (index) {
    case 0:
        $scope.first = choice.name;
        break;
    case 1:
        $scope.second = choice.name;
        break;
    case 2:
        $scope.third = choice.name;
        break;
    case 3:
        $scope.fourth = choice.name;
        break;
}
console.log($scope.first,$scope.second,$scope.third,$scope.fourth)
  }

  })

 }
});

body {
 font-family:Arial;
 color:#333;
}
label {
 font-weight:bold;
}
#choicesDisplay {
 margin-top:1em;
}
.form-group {
 width:70%;clear:both;
}
.form-group input {
 float:right;
 width:60%;
 padding:.3em;
}
button {
 background-color:#3f7ebc;
 color:white;
 padding: .5em .7em .5em .7em;
 font-weight:bold;
 border:none;
}

<!DOCTYPE html>
<html ng-app="angularjs-starter">
 <head lang="en">
  <meta charset="utf-8" />
  <title>Custom Plunker</title>
  <script data-require="angular.js@*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script>
   document.write('<base href="' + document.location + '" />');
  </script>
  <script src="app.js"></script>
 </head>
 <body ng-controller="MainCtrl">
  <div class="form-group" data-ng-repeat="choice in choices">
   <label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
   <button ng-show="$last" ng-click="addNewChoice()">Add another choice</button>
   <input type="text" ng-model="choice.name" name="" placeholder="enter id">

  </div>
    <button ng-click="submitChoice()">Submit</button>

  <div id="choicesDisplay">
   {{ choices }}
  </div>
 </body>
</html>

Please run the above snippet for second example

PS: As per your request, based on the index of the choice in loop, assigned the choice names to respective scope variables using switch case.


问:
How to reload spfx web part after post()?
I am creating spfx webpart with React framework.
I am having render method where all the controls were rendered. i am having a button, few checkboxes in the DOM which will send data to SharePoint using post method this.context.spHttpClient.post when user clicks on button. I am able to submit the data to SharePoint. But once I submit the data I am not able to reload the spfx webpart. I have to reload the web part again without reloading the page. I have tried to call the render method again. Of course it may not be correct way, so it is not working.

答:
You can either call a force reload or set state as shown here and here

"By default, when your component’s state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().
Calling forceUpdate() will cause render() to be called on the component, skipping shouldComponentUpdate(). This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes.
Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render()."


答:
I will recommend having a map of checkbox ID vs. form to do it at one shot:

```<code>var map = {
  check_express: $('#form_express'),
  check_standard: $('#form_standard')
};

$('#check_express, #check_standard').on('change', function() {
    map[this.id].toggle($(this).is(':checked'));
});
</code>```

In case you have more such cases, simply add them to map.

Title: combine blocks of code to one function

Body:
I will recommend having a map of checkbox ID vs. form to do it at one shot:

var map = {
  check_express: $('#form_express'),
  check_standard: $('#form_standard')
};

$('#check_express, #check_standard').on('change', function() {
    map[this.id].toggle($(this).is(':checked'));
});

In case you have more such cases, simply add them to map.


问:
Error when predicting with DirichletReg package in R
I am trying to make predictions on a test set using the DirichReg function from the DirichletReg package. When I run the model with only a few predictors it works fine, but when I use more than ~5 predictors I get an error that I can't figure out. The code below creates an MWE that reproduces the error.

```<code>library(DirichletReg)
set.seed(1)
# create dataset
predictor1 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor2 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor3 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor4 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor5 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor6 <- rnorm(n = 1000, mean = 5, sd = 1)
prob_A <- runif(n = 1000, min = 0, max = 0.5)
prob_B <- runif(n = 1000, min = 0, max = 0.5)
prob_C <- 1 - prob_A - prob_B
dat <- data.frame(predictor1, predictor2, predictor3, predictor4, predictor5,
                  predictor6, prob_A, prob_B, prob_C)

# split data into training and test sets
train_vec <- sample(c(0, 1), size = nrow(dat), replace = T, prob = c(0.2, 0.8))
train_dat <- dat[train_vec == 1, ]
test_dat <- dat[train_vec == 0, ]

# run model
train_dat$prob <- DR_data(train_dat[, c('prob_A', 'prob_B', 'prob_C')])
mod <- DirichReg(prob ~ predictor1 + predictor2 + predictor3 + predictor4 +
                        predictor5 + predictor6,
                 data = train_dat, model = 'common')

# run predictions
test_dat$prob <- DR_data(test_dat[, c('prob_A', 'prob_B', 'prob_C')])
preds <- predict(object = mod, newdata = test_dat)
</code>```

Here's the error that I'm getting:

```<code>Error in parse(text = x, keep.source = FALSE) :
  <text>:1:74: unexpected '|'
1: prob ~ predictor1 + predictor2 + predictor3 + predictor4 + predictor5 +  |
                                                                             ^
</code>```

I would appreciate any help. I haven't been able to google the error or find it in the package documentation.

答:
This seems to be a bug in the package. I recommend that you contact the package maintainer to report it.

A possible workaround is to explicitly list the separate parts of the regression specification instead of relying on the package to internally replicate the regressors for all parts.

```<code>mod2 <- DirichReg(prob ~
  predictor1 + predictor2 + predictor3 + predictor4 + predictor5 + predictor6 |
  predictor1 + predictor2 + predictor3 + predictor4 + predictor5 + predictor6 |
  predictor1 + predictor2 + predictor3 + predictor4 + predictor5 + predictor6,
  data = train_dat, model = "common")
all.equal(coef(mod), coef(mod2))
## [1] TRUE
predict(mod2, newdata = test_dat)
##             [,1]      [,2]      [,3]
##   [1,] 0.2436493 0.2715895 0.4847612
##   [2,] 0.2541715 0.2252292 0.5205993
##   [3,] 0.2618741 0.2345063 0.5036196
##   ...
</code>```

Body:
I am trying to make predictions on a test set using the DirichReg function from the DirichletReg package. When I run the model with only a few predictors it works fine, but when I use more than ~5 predictors I get an error that I can't figure out. The code below creates an MWE that reproduces the error.

library(DirichletReg)
set.seed(1)
# create dataset
predictor1 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor2 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor3 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor4 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor5 <- rnorm(n = 1000, mean = 5, sd = 1)
predictor6 <- rnorm(n = 1000, mean = 5, sd = 1)
prob_A <- runif(n = 1000, min = 0, max = 0.5)
prob_B <- runif(n = 1000, min = 0, max = 0.5)
prob_C <- 1 - prob_A - prob_B
dat <- data.frame(predictor1, predictor2, predictor3, predictor4, predictor5,
                  predictor6, prob_A, prob_B, prob_C)

# split data into training and test sets
train_vec <- sample(c(0, 1), size = nrow(dat), replace = T, prob = c(0.2, 0.8))
train_dat <- dat[train_vec == 1, ]
test_dat <- dat[train_vec == 0, ]

# run model
train_dat$prob <- DR_data(train_dat[, c('prob_A', 'prob_B', 'prob_C')])
mod <- DirichReg(prob ~ predictor1 + predictor2 + predictor3 + predictor4 +
                        predictor5 + predictor6,
                 data = train_dat, model = 'common')

# run predictions
test_dat$prob <- DR_data(test_dat[, c('prob_A', 'prob_B', 'prob_C')])
preds <- predict(object = mod, newdata = test_dat)

Here's the error that I'm getting:

Error in parse(text = x, keep.source = FALSE) :
  <text>:1:74: unexpected '|'
1: prob ~ predictor1 + predictor2 + predictor3 + predictor4 + predictor5 +  |
                                                                             ^

I would appreciate any help. I haven't been able to google the error or find it in the package documentation.

Body:
This seems to be a bug in the package. I recommend that you contact the package maintainer to report it.

A possible workaround is to explicitly list the separate parts of the regression specification instead of relying on the package to internally replicate the regressors for all parts.

mod2 <- DirichReg(prob ~
  predictor1 + predictor2 + predictor3 + predictor4 + predictor5 + predictor6 |
  predictor1 + predictor2 + predictor3 + predictor4 + predictor5 + predictor6 |
  predictor1 + predictor2 + predictor3 + predictor4 + predictor5 + predictor6,
  data = train_dat, model = "common")
all.equal(coef(mod), coef(mod2))
## [1] TRUE
predict(mod2, newdata = test_dat)
##             [,1]      [,2]      [,3]
##   [1,] 0.2436493 0.2715895 0.4847612
##   [2,] 0.2541715 0.2252292 0.5205993
##   [3,] 0.2618741 0.2345063 0.5036196
##   ...


问:
How to set onClick on Notification(Firebase)
I want to set onclick on notification to go to specific activity that i getting from backend.(FireBase). At present when i clicking on notification it open application launcher activity. </p>

答:
Please check this is MyFirebaseMessagingService file here i'm set an onclick and open a different activity:-

Here in first "if (json instanceof JSONObject) {" condition get response from json response got from notification and then open a comment activity.

And in "else" got simple message and display on notification and restart app from Splash Screen.

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

        private static final String TAG = "MyFirebaseMsgService";
        Context mContext;

        /**
         * Called when message is received.
         *
         * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
         */
        // [START receive_message]
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            // TODO(developer): Handle FCM messages here.

            Log.d(TAG, "From: " + remoteMessage.getFrom());
            Log.d(TAG, "Notification Message getMessageId: " + remoteMessage.getMessageId());
            Log.d(TAG, "Notification Message getMessage: " + remoteMessage.getData().get("message"));
            Log.d(TAG, "Notification Message getAction: " + remoteMessage.getData().get("action"));
            Log.d(TAG, "Notification Message ImageURL: " + remoteMessage.getData().get("imageUrl"));
            Log.d(TAG, "Notification Message from: " + remoteMessage.getData().get("from"));
            Log.d(TAG, "Notification Message google.message_id " + remoteMessage.getData().get("google.message_id"));
            mContext = getApplicationContext();

            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            String msg = remoteMessage.getData().get("message");
            try {
                sendNotification(msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        private void sendNotification(String message) throws JSONException {
            String commenterFname = "", commenterLname = "", commenterProfileImage = "", userID = "", postID = "";

            Object json = new JSONTokener(message).nextValue();
            if (json instanceof JSONObject) {
                try {
                    JSONObject msg = new JSONObject(message);
                    commenterFname = msg.getString(Constant.JSON_KEY.COM_FNAME);
                    commenterLname = msg.getString(Constant.JSON_KEY.COM_LNAME);
                    commenterProfileImage = msg.getString(Constant.JSON_KEY.COM_IMAGE);
                    userID = msg.getString(Constant.JSON_KEY.USER_ID);
                    postID = msg.getString(Constant.JSON_KEY.POST_ID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                String msg = commenterFname + " " + commenterLname + " " + getResources().getString(R.string.commented_on_your_post);

                int id = (int) System.currentTimeMillis();
                Intent notificationIntent = new Intent(this, CommentActivity.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                notificationIntent.putExtra("postID", postID);
                notificationIntent.setAction(postID);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                        notificationIntent, 0);

                Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setContentTitle("App_name")
                        .setContentText(msg)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
                } else {
                    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
                }

                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(id, notificationBuilder.build());

            } else {
                int id = (int) System.currentTimeMillis();
                Intent notificationIntent = new Intent(this, SplashActivity.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                        notificationIntent, 0);

                Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setContentTitle("KhetiVadi")
                        .setContentText(message)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
                } else {
                    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
                }

                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(id, notificationBuilder.build());
            }
        }
    }
</code>```

Hope it's helps you.

Body:
Please check this is MyFirebaseMessagingService file here i'm set an onclick and open a different activity:-

Here in first "if (json instanceof JSONObject) {" condition get response from json response got from notification and then open a comment activity.

And in "else" got simple message and display on notification and restart app from Splash Screen.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

        private static final String TAG = "MyFirebaseMsgService";
        Context mContext;

        /**
         * Called when message is received.
         *
         * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
         */
        // [START receive_message]
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            // TODO(developer): Handle FCM messages here.

            Log.d(TAG, "From: " + remoteMessage.getFrom());
            Log.d(TAG, "Notification Message getMessageId: " + remoteMessage.getMessageId());
            Log.d(TAG, "Notification Message getMessage: " + remoteMessage.getData().get("message"));
            Log.d(TAG, "Notification Message getAction: " + remoteMessage.getData().get("action"));
            Log.d(TAG, "Notification Message ImageURL: " + remoteMessage.getData().get("imageUrl"));
            Log.d(TAG, "Notification Message from: " + remoteMessage.getData().get("from"));
            Log.d(TAG, "Notification Message google.message_id " + remoteMessage.getData().get("google.message_id"));
            mContext = getApplicationContext();

            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            String msg = remoteMessage.getData().get("message");
            try {
                sendNotification(msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        private void sendNotification(String message) throws JSONException {
            String commenterFname = "", commenterLname = "", commenterProfileImage = "", userID = "", postID = "";

            Object json = new JSONTokener(message).nextValue();
            if (json instanceof JSONObject) {
                try {
                    JSONObject msg = new JSONObject(message);
                    commenterFname = msg.getString(Constant.JSON_KEY.COM_FNAME);
                    commenterLname = msg.getString(Constant.JSON_KEY.COM_LNAME);
                    commenterProfileImage = msg.getString(Constant.JSON_KEY.COM_IMAGE);
                    userID = msg.getString(Constant.JSON_KEY.USER_ID);
                    postID = msg.getString(Constant.JSON_KEY.POST_ID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                String msg = commenterFname + " " + commenterLname + " " + getResources().getString(R.string.commented_on_your_post);

                int id = (int) System.currentTimeMillis();
                Intent notificationIntent = new Intent(this, CommentActivity.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                notificationIntent.putExtra("postID", postID);
                notificationIntent.setAction(postID);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                        notificationIntent, 0);

                Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setContentTitle("App_name")
                        .setContentText(msg)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
                } else {
                    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
                }

                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(id, notificationBuilder.build());

            } else {
                int id = (int) System.currentTimeMillis();
                Intent notificationIntent = new Intent(this, SplashActivity.class);
                notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                        notificationIntent, 0);

                Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setContentTitle("KhetiVadi")
                        .setContentText(message)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
                } else {
                    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
                }

                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(id, notificationBuilder.build());
            }
        }
    }

Hope it's helps you.


答:
Since (aba?)+ is greedy, your pattern tries to match as much as possible. And since it first matches "aba", the remaining "b" is not matched.

Try the non-greedy version (it will match the first and second "ab"'s):

```<code>$ echo "abab" | grep -Po "(aba?)+"
aba
$ echo "abab" | grep -Po "(aba??)+"
abab
</code>```

Title: Why does the regex (aba?)+ not match with abab?

Body:
Given (aba?)+ as the Regex and abab is the string.

Why does it only matches aba?

Since the last a in the regex is optional, isn't abab a match as well?

tested on https://regex101.com/

Body:
Since (aba?)+ is greedy, your pattern tries to match as much as possible. And since it first matches "aba", the remaining "b" is not matched.

Try the non-greedy version (it will match the first and second "ab"'s):

$ echo "abab" | grep -Po "(aba?)+"
aba
$ echo "abab" | grep -Po "(aba??)+"
abab


问:
how to handle array of 'promis'
I built a database that contains a list of users who receive messages from firebase with a request key. Every time a new request with status 'open' inserted, I am trying to sort them all by the value of 'Timestamp' and send it by this order to the receivers(each receiver will get one message).
if the list of receivers is empty I want to hold it, until another receiver will be added to the list and continue to the next request.
I am not sure how to send each 'promise' separately one after another-</p>

```<code>exports.notificationListener=functions.database.ref('requests')
.onWrite(event=>{
    const ref = event.data.ref;
    let requests= [];
    var query=ref.orderByChild('TimeStamp');

    query.once('value',function(snap){
        snap.forEach(request=>{
            if(request.val().Status==OPEN)
                requests.push(request.key);
        });
    });
    for (let key of requests) {
       return getOnlinReceiversToken().then(token=>{
       let msg = {
        data: {
          source: key
               }
         };
         return admin.messaging().sendToDevice(token, msg);
       )};
     }
 });

function getOnlinReceiversToken() {
    let result = new Promise((resolve, reject) => {
     receiverRef.once('value', (snap) => {
      resolve(snap);
        },
       (err) => {
         reject(err);
      });
    });
    return result.then(snap => {
        snap.forEach(child => {
            if(child.Status == ONLINE){
                let token = helper.getToken(child.key,db);
                break;
            }
        });
        return token;
    });
  }
</code>```

答:
You could use a function that calls itself to iterate through the promises sequentially to send them one after the other</p>

```<code>function runPromise(index) {
  // jump out of loop if there are no more requests
  if (index >= requests.length) {
    return console.log('finished!');
  }

  return getOnlinReceiversToken().then((token) => {
    let msg = {
      data: { source: key }
    };
    admin.messaging().sendToDevice(token, msg);
    // iterate to the next item
    return runPromise(index + 1);
  }).catch((err) => {
      // break out of loop when an error occurs
      console.log(err);
  });
}

runPromise(0);
</code>```

Title: how to handle array of 'promis'

Body:
I built a database that contains a list of users who receive messages from firebase with a request key. Every time a new request with status 'open' inserted, I am trying to sort them all by the value of 'Timestamp' and send it by this order to the receivers(each receiver will get one message).
if the list of receivers is empty I want to hold it, until another receiver will be added to the list and continue to the next request.
I am not sure how to send each 'promise' separately one after another-

exports.notificationListener=functions.database.ref('requests')
.onWrite(event=>{
    const ref = event.data.ref;
    let requests= [];
    var query=ref.orderByChild('TimeStamp');

    query.once('value',function(snap){
        snap.forEach(request=>{
            if(request.val().Status==OPEN)
                requests.push(request.key);
        });
    });
    for (let key of requests) {
       return getOnlinReceiversToken().then(token=>{
       let msg = {
        data: {
          source: key
               }
         };
         return admin.messaging().sendToDevice(token, msg);
       )};
     }
 });

function getOnlinReceiversToken() {
    let result = new Promise((resolve, reject) => {
     receiverRef.once('value', (snap) => {
      resolve(snap);
        },
       (err) => {
         reject(err);
      });
    });
    return result.then(snap => {
        snap.forEach(child => {
            if(child.Status == ONLINE){
                let token = helper.getToken(child.key,db);
                break;
            }
        });
        return token;
    });
  }

Body:
You could use a function that calls itself to iterate through the promises sequentially to send them one after the other

function runPromise(index) {
  // jump out of loop if there are no more requests
  if (index >= requests.length) {
    return console.log('finished!');
  }

  return getOnlinReceiversToken().then((token) => {
    let msg = {
      data: { source: key }
    };
    admin.messaging().sendToDevice(token, msg);
    // iterate to the next item
    return runPromise(index + 1);
  }).catch((err) => {
      // break out of loop when an error occurs
      console.log(err);
  });
}

runPromise(0);


问:
Twitter Bootstrap : Same height for grid
With Bootstrap 4, I want to same height for my sections. But I want to enlarge only content
 (Not the header and the footer)

section {
  background: #ccc;
  border: 1px solid #000
}

header {
  background: red;
  color: #fff
}

footer {
  background: blue;
  color: #fff
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
          <li>
            Item 3
          </li>
          <li>
            Item 4
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
</div></code>```

Can you help me?

答:
Something like this?

```<code>.content {
  min-height: 150px;
  height: 150px;
}
</code>```

section {
  background: #ccc;
  border: 1px solid #000
}

header {
  background: red;
  color: #fff
}

footer {
  background: blue;
  color: #fff
}

.content {
  min-height: 150px;
  height: 150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
          <li>
            Item 3
          </li>
          <li>
            Item 4
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
</div></code>```

Body:
With Bootstrap 4, I want to same height for my sections. But I want to enlarge only content
 (Not the header and the footer)

section {
  background: #ccc;
  border: 1px solid #000
}

header {
  background: red;
  color: #fff
}

footer {
  background: blue;
  color: #fff
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

        Title

            Item 1

        Footer

        Title

            Item 1

            Item 2

        Footer

        Title

            Item 1

            Item 2

            Item 3

            Item 4

        Footer

Can you help me?

Body:
Something like this?

.content {
  min-height: 150px;
  height: 150px;
}

section {
  background: #ccc;
  border: 1px solid #000
}

header {
  background: red;
  color: #fff
}

footer {
  background: blue;
  color: #fff
}

.content {
  min-height: 150px;
  height: 150px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
  <div class="col-3">
    <section>
      <header>
        Title
      </header>
      <div class="content">
        <ul>
          <li>
            Item 1
          </li>
          <li>
            Item 2
          </li>
          <li>
            Item 3
          </li>
          <li>
            Item 4
          </li>
        </ul>
      </div>
      <footer>
        Footer
      </footer>
    </section>
  </div>
</div>


问:
Sort products by DESC order in Woocommerce
I wrote this code in functions.php file of my active theme:

```<code>    add_filter( 'woocommerce_get_catalog_ordering_args',
    'custom_woocommerce_get_catalog_ordering_args' );
    function custom_woocommerce_get_catalog_ordering_args( $args ) {
     $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'random_list' == $orderby_value ) {
        $args['orderby'] = 'date';
        $args['order'] = 'desc';
        $args['meta_key'] = '';
    }
    return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['random_list'] = 'DESC SORT';
    return $sortby;
}
</code>```

I am trying to sort products by Desc, but products still sorting by default (ASC).

How can I sort them by DESC?

答:
```<code>add_action( 'woocommerce_product_query', 'default_catalog_ordering_desc', 10, 2 );
function default_catalog_ordering_desc( $q, $query ){
    if( $q->get( 'orderby' ) == 'date' )
        $q->set( 'order', 'DESC' );
}
</code>```

Body:
I wrote this code in functions.php file of my active theme:

    add_filter( 'woocommerce_get_catalog_ordering_args',
    'custom_woocommerce_get_catalog_ordering_args' );
    function custom_woocommerce_get_catalog_ordering_args( $args ) {
     $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'random_list' == $orderby_value ) {
        $args['orderby'] = 'date';
        $args['order'] = 'desc';
        $args['meta_key'] = '';
    }
    return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['random_list'] = 'DESC SORT';
    return $sortby;
}

I am trying to sort products by Desc, but products still sorting by default (ASC).

How can I sort them by DESC?


问:
Calculate how many clients ordered less than one month after their first, second, ... order
Let's start with my tables (simplified for my question) (using MySQL):

```<code>client :
+----------+----------------------+
| idClient |    insctiptionDate   |
+----------+----------------------+
|     1    | 2017-07-31 14:51:22  |
+----------+----------------------+
|     2    | 2017-07-18 08:25:36  |
+----------+----------------------+

delivery :
+----------+----------------------+
| fkClient |         date         |
+----------+----------------------+
|     1    | 2017-07-31 14:51:22  |
+----------+----------------------+
|     1    | 2017-08-10 13:30:22  |
+----------+----------------------+
|     2    | 2017-07-18 08:25:36  |
+----------+----------------------+
</code>```

The inscriptionDate column is equal to the date of the first delivery for each client.

I need to know how many clients ordered a second time in the 28 firsts days after their first command.

So far, I have this :

```<code>SELECT
  YEARWEEK(tmp.first) AS Week,
  COUNT(tmp.id) AS Total
FROM (
  SELECT
    c.idClient as id,
    (SELECT
        MIN(d.date)
     FROM delivery d
     WHERE c.idClient = d.fkClient
    ) AS first
  FROM client c
  ORDER BY first ASC
  ) AS tmp
WHERE (
  SELECT
    MIN(d.date)
  FROM delivery d
  WHERE tmp.id = d.fkClient
  AND d.date != tmp.first
  AND DATEDIFF(d.date, tmp.first) <= 28
  ) IS NOT NULL
 GROUP BY YEARWEEK(first)
 ORDER BY YEARWEEK(first);
</code>```

I first get the first delivery for all my clients, then I count how many of them ordered a second time in the next 28 days.

My problems are:

I'm not sure this is the most elegant solution or even if this really work so I'm open to any suggestion here

I am limited to only one SELECT to do this (I am using the SQL mode
of Chartio to visualize the results)

I need to expand this to also know how many clients order after their
second delivery, their third, ... and I am really stuck here!

Thank you for your help!

答:
Finally, I've decided to use a python script to calculate those kind of values.

Thanks anyway!

Body:
Let's start with my tables (simplified for my question) (using MySQL):

client :
+----------+----------------------+
| idClient |    insctiptionDate   |
+----------+----------------------+
|     1    | 2017-07-31 14:51:22  |
+----------+----------------------+
|     2    | 2017-07-18 08:25:36  |
+----------+----------------------+

delivery :
+----------+----------------------+
| fkClient |         date         |
+----------+----------------------+
|     1    | 2017-07-31 14:51:22  |
+----------+----------------------+
|     1    | 2017-08-10 13:30:22  |
+----------+----------------------+
|     2    | 2017-07-18 08:25:36  |
+----------+----------------------+

The inscriptionDate column is equal to the date of the first delivery for each client.

I need to know how many clients ordered a second time in the 28 firsts days after their first command.

So far, I have this :

SELECT
  YEARWEEK(tmp.first) AS Week,
  COUNT(tmp.id) AS Total
FROM (
  SELECT
    c.idClient as id,
    (SELECT
        MIN(d.date)
     FROM delivery d
     WHERE c.idClient = d.fkClient
    ) AS first
  FROM client c
  ORDER BY first ASC
  ) AS tmp
WHERE (
  SELECT
    MIN(d.date)
  FROM delivery d
  WHERE tmp.id = d.fkClient
  AND d.date != tmp.first
  AND DATEDIFF(d.date, tmp.first) <= 28
  ) IS NOT NULL
 GROUP BY YEARWEEK(first)
 ORDER BY YEARWEEK(first);

I first get the first delivery for all my clients, then I count how many of them ordered a second time in the next 28 days.

My problems are:

I'm not sure this is the most elegant solution or even if this really work so I'm open to any suggestion here

I am limited to only one SELECT to do this (I am using the SQL mode
of Chartio to visualize the results)

I need to expand this to also know how many clients order after their
second delivery, their third, ... and I am really stuck here!

Thank you for your help!


问:
Downgrade SQL CE from 4 to 3.5?
Does anyone know if it's possible to downgrade an existing SQL CE 4 database to 3.5? The reason I ask is because I'm looking to migrate from SQL CE to VistaDB...and VistaDB's data migration wizard only takes SQL CE 3.5 db's.</p>

答: I actually just found an answer to my own question. Using Data Port Console, you can do an export of an existing SQL CE 4 database to a 3.5 db. Then using Vista DB's Data Migration Wizard, you can import that 3.5 version of the db. It seems to have worked amazingly well and took about 2 minutes.</p>

Title: Downgrade SQL CE from 4 to 3.5?


问:
how to prevent undefined property when only one record found in Laravel
I was try to make a search function so i'm doing like this:

```<code>public function search(Request $request)
{
    $query = $request->query('q');

    $posts = DB::table('posts')->where('title', 'LIKE',  '%'.$query.'%')->get();

    return view('admin.dashboard.search')->with('users',$users)->with('posts',$posts);
}
</code>```

but when i try to fetch the result i got some errors like this:

Undefined property: stdClass::$user (View:
  E:\laragon\www\blog\resources\views\admin\dashboard\search.blade.php)

It was errors in this line:

```<code><td><?php echo e($post->user->name); ?></td>
</code>```

So how can i fix it?

答:
You have to eager load the user in your search query like this :</p>

```<code>$posts = App\Post::with('user')
                   ->where('title', 'LIKE', '%'.$query.'%')
                   ->get();
</code>```

Body:
I was try to make a search function so i'm doing like this:

public function search(Request $request)
{
    $query = $request->query('q');

    $posts = DB::table('posts')->where('title', 'LIKE',  '%'.$query.'%')->get();

    return view('admin.dashboard.search')->with('users',$users)->with('posts',$posts);
}

but when i try to fetch the result i got some errors like this:

Undefined property: stdClass::$user (View:
  E:\laragon\www\blog\resources\views\admin\dashboard\search.blade.php)

It was errors in this line:

<?php echo e($post->user->name); ?>

So how can i fix it?

Body:
You have to eager load the user in your search query like this :

$posts = App\Post::with('user')
                   ->where('title', 'LIKE', '%'.$query.'%')
                   ->get();


问:
Python load json file with UTF-8 BOM header
I needed to parse files generated by other tool, which unconditionally outputs json file with UTF-8 BOM header (EFBBBF). I soon found that this was the problem, as Python 2.7 module can't seem to parse it:

```<code>>>> import json
>>> data = json.load(open('sample.json'))

ValueError: No JSON object could be decoded
</code>```

Removing BOM, solves it, but I wonder if there is another way of parsing json file with BOM header?

答:
If this is a one-off, a very simple super high-tech solution that worked for me...

Open the JSON file in your favorite text editor.

Select-all

Create a new file

Paste

Save.

BOOM, BOM header gone!

Body:
I needed to parse files generated by other tool, which unconditionally outputs json file with UTF-8 BOM header (EFBBBF). I soon found that this was the problem, as Python 2.7 module can't seem to parse it:

>>> import json
>>> data = json.load(open('sample.json'))

ValueError: No JSON object could be decoded

Removing BOM, solves it, but I wonder if there is another way of parsing json file with BOM header?


问:
How do I check whether a file exists without exceptions?
How do I check whether a file exists or not, without using the try statement?

答:
Date: 2017-12-04

Every possible solution has been listed in other answers.

An intuitive and arguable way to check if a file exists is the following:

```<code>import os

os.path.isfile('~/file.md')  # Returns True if exists, else False

# Additionally, check a directory
os.path.isdir('~/folder')  # Returns True if the folder exists, else False

# Check either a directory or a file
os.path.exists('~/file')
</code>```

I made an exhaustive cheat sheet for your reference:

```<code># os.path methods in exhaustive cheat sheet
{'definition': ['dirname',
               'basename',
               'abspath',
               'relpath',
               'commonpath',
               'normpath',
               'realpath'],
'operation': ['split', 'splitdrive', 'splitext',
               'join', 'normcase'],
'compare': ['samefile', 'sameopenfile', 'samestat'],
'condition': ['isdir',
              'isfile',
              'exists',
              'lexists'
              'islink',
              'isabs',
              'ismount',],
 'expand': ['expanduser',
            'expandvars'],
 'stat': ['getatime', 'getctime', 'getmtime',
          'getsize']}
</code>```

LastEditorDisplayName: Mark Biek

Body:
Date: 2017-12-04

Every possible solution has been listed in other answers.

An intuitive and arguable way to check if a file exists is the following:

import os

os.path.isfile('~/file.md')  # Returns True if exists, else False

# Additionally, check a directory
os.path.isdir('~/folder')  # Returns True if the folder exists, else False

# Check either a directory or a file
os.path.exists('~/file')

I made an exhaustive cheat sheet for your reference:

# os.path methods in exhaustive cheat sheet
{'definition': ['dirname',
               'basename',
               'abspath',
               'relpath',
               'commonpath',
               'normpath',
               'realpath'],
'operation': ['split', 'splitdrive', 'splitext',
               'join', 'normcase'],
'compare': ['samefile', 'sameopenfile', 'samestat'],
'condition': ['isdir',
              'isfile',
              'exists',
              'lexists'
              'islink',
              'isabs',
              'ismount',],
 'expand': ['expanduser',
            'expandvars'],
 'stat': ['getatime', 'getctime', 'getmtime',
          'getsize']}


问:
Inserting multiple rows into mysql db using php
Am having a problem inserting multiple rows of data into a table at once. The following is what i have.When i click on submit, only the last row is inserted with only the first digit of quantity. please help.

html form:

```<code><form method="post" action="insert.php">
<p><input type="text"  id="product_id" name="product_id[]"/>
   <input type="text" id="quantity" name="quantity[]"/></p>
<p><input type="text"  id="product_id" name="product_id[]"/>
   <input type="text" id="quantity" name="quantity[]"/></p>
<p><input type="text"  id="product_id" name="product_id[]"/>
   <input type="text" id="quantity" name="quantity[]"/></p>
<input type="submit" name="submit" value="submit"/>
</form>
</code>```

insert.php page:

```<code><?php
include 'config/auth.php';//database connection
if(isset($_POST['submit'])){
    $product = mysqli_real_escape_string($dbc, $_POST['product_id']);
    $quantity = mysqli_real_escape_string($dbc, $_POST['quantity']);
    $count = sizeof($product);
    for ($i=0; $i < $count; $i++) {
        $Inproduct = $product[$i];
        $Inquantity = $quantity[$i];
    $query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
    $results = mysqli_query($dbc, $query);
    }
    if ($results) {
        echo 'Success';
    }
}
?>
</code>```

答:
the following code worked... thanks @kmdm</p>

```<code>    $product = $_POST['product_id'];
    $quantity = $_POST['quantity'];
    $count = sizeof($product);
    for ($i=0; $i < $count; $i++) {
        $Inproduct = mysqli_real_escape_string($dbc, $product[$i]);
        $Inquantity = mysqli_real_escape_string($dbc, $quantity[$i]);
    $query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
    $results = mysqli_query($dbc, $query);
    }
</code>```

Body:
Am having a problem inserting multiple rows of data into a table at once. The following is what i have.When i click on submit, only the last row is inserted with only the first digit of quantity. please help.

html form:

<form method="post" action="insert.php">

<input type="text"  id="product_id" name="product_id[]"/>
   <input type="text" id="quantity" name="quantity[]"/>

<input type="text"  id="product_id" name="product_id[]"/>
   <input type="text" id="quantity" name="quantity[]"/>

<input type="text"  id="product_id" name="product_id[]"/>
   <input type="text" id="quantity" name="quantity[]"/>

<input type="submit" name="submit" value="submit"/>
</form>

insert.php page:

<?php
include 'config/auth.php';//database connection
if(isset($_POST['submit'])){
    $product = mysqli_real_escape_string($dbc, $_POST['product_id']);
    $quantity = mysqli_real_escape_string($dbc, $_POST['quantity']);
    $count = sizeof($product);
    for ($i=0; $i < $count; $i++) {
        $Inproduct = $product[$i];
        $Inquantity = $quantity[$i];
    $query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
    $results = mysqli_query($dbc, $query);
    }
    if ($results) {
        echo 'Success';
    }
}
?>

Body:
the following code worked... thanks @kmdm

    $product = $_POST['product_id'];
    $quantity = $_POST['quantity'];
    $count = sizeof($product);
    for ($i=0; $i < $count; $i++) {
        $Inproduct = mysqli_real_escape_string($dbc, $product[$i]);
        $Inquantity = mysqli_real_escape_string($dbc, $quantity[$i]);
    $query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
    $results = mysqli_query($dbc, $query);
    }


答:
You need to first set with['user'] in your query!

```<code>$posts = App\Post::with('user')->where('title', 'LIKE', '%'.$query.'%')->get();
</code>```

Then you can get it in your view like:

```<code><td>{{ $post->user->name ? $post->user->name : 'No User Found'  }}/td>
</code>```

Hope this helps you!

Title: how to prevent undefined property when only one record found in Laravel

Body:
You need to first set with['user'] in your query!

$posts = App\Post::with('user')->where('title', 'LIKE', '%'.$query.'%')->get();

Then you can get it in your view like:

<td>{{ $post->user->name ? $post->user->name : 'No User Found'  }}/td>

Hope this helps you!


问:
Builder design pattern in C#/C++ requires elevated access modifiers?
Let's say we have a Vehicle class containing a private collection of wheels, and a method AddWheel(Wheel i_WheelToAdd). without using a builder pattern, I would want this method to be protected, but because I am using the builder design pattern, I have no choice but to set it to internal (to allow the builder to add wheels).

what is the correct object-oriented way to fix this issue?

(the use of a nested class doesn't help me in C#/C++, assuming inside Vehicle I have a nested class 'VehicleBuilder', this doesn't give it the ability to access a private/protected member of the parent like in java)

答:
One way is to make the builder as an inner class that gets exposed from the object itself:</p>

```<code>class Vehicle
{
  ⁞
  class VehicleBuilder
  {
    ⁞
  }
  private Vehicle(...) { ... }
  public VehicleBuilder New => new VehicleBuilder();
}
</code>```

Body:
One way is to make the builder as an inner class that gets exposed from the object itself:

class Vehicle
{
  ⁞
  class VehicleBuilder
  {
    ⁞
  }
  private Vehicle(...) { ... }
  public VehicleBuilder New => new VehicleBuilder();
}