问:
How to redirect old to new URLs in PrestaShop after modifying SEO patterns
I've changed the SEO Schema settings in the PrestaShop back office (e.g. added .html extension for Product URLs).

Now, the old URLs don't work anymore and they are not redirect to the new URLs (the ones with .html extension).

I'd like that whenever I change the settings for Products or Categories URLs, the previous URLs are redirected to the new ones (301 permanent redirects).

Any solutions?

答:
For PrestaShop is not important if the URL end with/without .html, the real problem is if you has remove the ID in the route or changed the order of the ID, if this is your case you will need to create a large list of redirections (for each of the categories) in your .htaccess like this example:

Redirect 301 /3-my-old-category-url /my-new-category-url


来源: stackexchange

问:
Scala - Add elements based on logic
I am new to Scala.
I have a function that accepts a string and based on different logics, I need to create a Seq of String with all permutations.
Example - input string is 00US_India0234. The result will be Seq of:

```<code>US // Condition - if string contains "US"
India // Condition - if string contains "India"
234 // Condition - if string contains number and trim
US_India // One more condition to keep countries intact and so on
</code>```

Code tried so far which I didn't work

```<code>val retSeq: Seq[String] = Seq.empty
if myStr contains "US" retSeq +: "US"
</code>```

I have the conditions in place but adding to Seq is not possible and I do not want to create a var.

答:
You could create a list of tuples containing predicates and functions to process your input you want to potentially apply and append to Seq:

```<code>val numberRegex = "([0-9]{4,})".r

val predicates = List[(String => Boolean, String => String)](
    (s => s.contains("US"), _  => "US"),
    (s => s.contains("India"), s => s.toUpperCase()),
    (s => numberRegex.findFirstIn(s).nonEmpty, s => numberRegex.findFirstIn(s).head)
 )
</code>```

And then you need to just create a method to build up Seq:

```<code>def process(s: String): Seq[String] = predicates.collect{
   case (predicate, value) if predicate(s) => value(s)
}

process("00US_India0234") //List(US, 00US_INDIA0234, 0234)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Scala - Add elements based on logic

Body:
I am new to Scala.
I have a function that accepts a string and based on different logics, I need to create a Seq of String with all permutations.
Example - input string is 00US_India0234. The result will be Seq of:

US // Condition - if string contains "US"
India // Condition - if string contains "India"
234 // Condition - if string contains number and trim
US_India // One more condition to keep countries intact and so on

Code tried so far which I didn't work

val retSeq: Seq[String] = Seq.empty
if myStr contains "US" retSeq +: "US"

I have the conditions in place but adding to Seq is not possible and I do not want to create a var.

Body:
You could create a list of tuples containing predicates and functions to process your input you want to potentially apply and append to Seq:

val numberRegex = "([0-9]{4,})".r

val predicates = List[(String => Boolean, String => String)](
    (s => s.contains("US"), _  => "US"),
    (s => s.contains("India"), s => s.toUpperCase()),
    (s => numberRegex.findFirstIn(s).nonEmpty, s => numberRegex.findFirstIn(s).head)
 )

And then you need to just create a method to build up Seq:

def process(s: String): Seq[String] = predicates.collect{
   case (predicate, value) if predicate(s) => value(s)
}

process("00US_India0234") //List(US, 00US_INDIA0234, 0234)


问:
Javascript Tabs - How to add hashtags on URL?
My Tabs works fine, but I need to have a separate function which directs with a URL to the tab, so I can have a separate link for each tab.

How Can I achieve that?

url.com/#tab1

url.com/#tab2

I tried many ways but I keep getting undefined hashtag. I'd like advice please, I put together a demo, which shows the full working experience.

var boxLink = $( '.but' );
var box = $( '.tab' );

boxLink.click( function() {
 $('#but1').removeClass('active');

    var boxID = $(this).attr("data-target");
    var currentbox = $('.tab:not(.is-hidden)');
    var targetBox = $('.tab#' + boxID);

    if (!$(this).hasClass('active'))    {
        boxLink.removeClass('active');
        $(this).addClass('active');

        TweenMax.to( currentbox, 0.2, {ease:Power4.easeOut, className: '-=visible', autoAlpha: 0,  onComplete: boxIn, onCompleteParams: [targetBox] });
    }

    return false;
});

var boxIn = function( targetBox ) {
    box.addClass( 'is-hidden' );
    targetBox.removeClass( 'is-hidden' );

    TweenMax.to( targetBox, 0.2, {autoAlpha: 1,className: '+=visible', ease:Power4.easeIn});
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color:black;
 }
#tab01 {
background: white;
}

#tab02 {
background: red;
}

.tab {
width:100px;
height:100px;
font-size:30px;
line-height:100px;
text-align:center;
}
.is-hidden {
  display: none;
  opacity:0;
  visibility:hidden;
}

button {
  cursor:pointer;
  padding: 5px;
  margin-top: 10px;
}</code>```

one

two

<button  class="but active" id="but1" data-target="tab01">slide 1</button>
<button  class="but" id="but2" data-target="tab02">slide 2</button>```

答:
If I got you correctly, you want to show a specific tab on load in case a hash has been added to the page's URL, right? If so you should parse window.location.href and check for a hash tag in the URL. If it is present, the hash value e.g. '#tab2' should show the container with the same ID.

Updated code:

var currentUrl= window.location.href;
if (currentUrl.indexOf('#') > -1) {
  var hashTag= currentUrl.substring(currentUrl.indexOf('#')+1);
  var targetBox = $('.tab#' + hashTag);
  TweenMax.to( currentbox, 0.2, {ease:Power4.easeOut,
    className: '-=visible', autoAlpha: 0,  onComplete: boxIn, onCompleteParams: [targetBox] });

  // added: highlight the proper buttons and remove the default "active" element
  $('.active').removeClass('active');
  $('.' + hashTag + '-control').addClass('active');
}
```

<p>To also highlight the buttons, you need to give them a class (that's the easiest method as you can't use duplicate IDs so we identify the tab via ID and button via class):</p>

```<button  class="tab01-control but active" id="but1" data-target="tab01">slide 1</button>
<button  class="tab02-control but" id="but2" data-target="tab02">slide 2</button>
```

<p>Your <code>boxIn(targetBox)</code> method expects to receive a jQuery object as "targetBox" parameter and it was a string. Simply append "#tab02" to your URL when you test it locally to have the second tab show up.</p>

<p><strong>Side note:</strong></p>

<p>Your Code snippet is currently not working correctly, you should include ...</p>

```
```

<p>... to make your animation work as expected, otherwise you'll receive a JS error message when clicking one of the buttons.</p>

<p><strong>Edit 1</strong></p>

<p>As you asked how to use meaningful "hash names" instead of the control's IDs like <code>tab01</code>, this can be achieved with a simple switch-case:</p>

```let hashTag = window.location.hash;
if (hashTag !== '') {
    hashTag = hashTag.substring(1);

    let targetName = '';

    switch (hashTag) {
        case "home":
            targetName = 'tab01';
            break;
        case "profile":
            targetName = 'tab02';
            break;
    }
    if (targetName !== '') {
        var targetBox = $('.tab#' + targetName);
        ...
    }
```

Body:
My Tabs works fine, but I need to have a separate function which directs with a URL to the tab, so I can have a separate link for each tab.

How Can I achieve that?

url.com/#tab1

url.com/#tab2

I tried many ways but I keep getting undefined hashtag. I'd like advice please, I put together a demo, which shows the full working experience.

var boxLink = $( '.but' );
var box = $( '.tab' );

boxLink.click( function() {
 $('#but1').removeClass('active');

    var boxID = $(this).attr("data-target");
    var currentbox = $('.tab:not(.is-hidden)');
    var targetBox = $('.tab#' + boxID);

    if (!$(this).hasClass('active'))    {
        boxLink.removeClass('active');
        $(this).addClass('active');

        TweenMax.to( currentbox, 0.2, {ease:Power4.easeOut, className: '-=visible', autoAlpha: 0,  onComplete: boxIn, onCompleteParams: [targetBox] });
    }

    return false;
});

var boxIn = function( targetBox ) {
    box.addClass( 'is-hidden' );
    targetBox.removeClass( 'is-hidden' );

    TweenMax.to( targetBox, 0.2, {autoAlpha: 1,className: '+=visible', ease:Power4.easeIn});
}

body {
  background-color:black;
 }
#tab01 {
background: white;
}

#tab02 {
background: red;
}

.tab {
width:100px;
height:100px;
font-size:30px;
line-height:100px;
text-align:center;
}
.is-hidden {
  display: none;
  opacity:0;
  visibility:hidden;
}

button {
  cursor:pointer;
  padding: 5px;
  margin-top: 10px;
}

one

two

<button  class="but active" id="but1" data-target="tab01">slide 1</button>
<button  class="but" id="but2" data-target="tab02">slide 2</button>

Body:
If I got you correctly, you want to show a specific tab on load in case a hash has been added to the page's URL, right? If so you should parse window.location.href and check for a hash tag in the URL. If it is present, the hash value e.g. '#tab2' should show the container with the same ID.

Updated code:

var currentUrl= window.location.href;
if (currentUrl.indexOf('#') > -1) {
  var hashTag= currentUrl.substring(currentUrl.indexOf('#')+1);
  var targetBox = $('.tab#' + hashTag);
  TweenMax.to( currentbox, 0.2, {ease:Power4.easeOut,
    className: '-=visible', autoAlpha: 0,  onComplete: boxIn, onCompleteParams: [targetBox] });

  // added: highlight the proper buttons and remove the default "active" element
  $('.active').removeClass('active');
  $('.' + hashTag + '-control').addClass('active');
}

To also highlight the buttons, you need to give them a class (that's the easiest method as you can't use duplicate IDs so we identify the tab via ID and button via class):

<button  class="tab01-control but active" id="but1" data-target="tab01">slide 1</button>
<button  class="tab02-control but" id="but2" data-target="tab02">slide 2</button>

Your boxIn(targetBox) method expects to receive a jQuery object as "targetBox" parameter and it was a string. Simply append "#tab02" to your URL when you test it locally to have the second tab show up.

Side note:

Your Code snippet is currently not working correctly, you should include ...

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"></script>

... to make your animation work as expected, otherwise you'll receive a JS error message when clicking one of the buttons.

Edit 1

As you asked how to use meaningful "hash names" instead of the control's IDs like tab01, this can be achieved with a simple switch-case:

let hashTag = window.location.hash;
if (hashTag !== '') {
    hashTag = hashTag.substring(1);

    let targetName = '';

    switch (hashTag) {
        case "home":
            targetName = 'tab01';
            break;
        case "profile":
            targetName = 'tab02';
            break;
    }
    if (targetName !== '') {
        var targetBox = $('.tab#' + targetName);
        ...
    }


问:
How do I get the id of a element in a form?
I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.

```<code>var form = document.getElementById("myForm");
form.elements[i].value
</code>```

Those lines of code is what I tried but it doesn't seem to work.

Edit:

```<code>function initial(){
        if (localStorage.getItem("run") === null) {
                var form = document.getElementById("myForm").elements;

                for(var i = 0; i < 1 ; i++){
                    var id = form.elements[i].id;
                    sessionStorage.setItem(id,"false");
                }
            localStorage.setItem("run", true);
        }
    }
</code>```

So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.

Edit2:

```<code>function initial(){
        if (localStorage.getItem("run") === null) {
                var form = document.getElementById("myForm");
                var tot = document.getElementById("myForm").length;

                for(var i = 0; i < tot ; i++){
                    sessionStorage.setItem(form.elements[i].id,"false");
                }
            localStorage.setItem("run", true);
        }
    }
</code>```

This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.

```<code> function loader(){
        var form = document.getElementById("myForm");
        var tot = 5;

        for(var i = 0; i < 5 ; i++){
            if(sessionStorage.getItem(form.elements[i].id) === "true"){
                document.getElementById(form.elements[i].id).style.backgroundColor = "green";
                return ;
            }else{
                document.getElementById(form.elements[i].id).style.backgroundColor = "red";
                return false;
            }
        }
    }
</code>```

Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.

答:
You're already storing all the elements in the form so it must be :

```<code>var form = document.getElementById("myForm").elements;
var id = form[i].id;
</code>```

Or remove the elements part from the form variable like :

```<code>var form = document.getElementById("myForm");
var id = form.elements[i].id;
</code>```

Body:
I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.

var form = document.getElementById("myForm");
form.elements[i].value

Those lines of code is what I tried but it doesn't seem to work.

Edit:

function initial(){
        if (localStorage.getItem("run") === null) {
                var form = document.getElementById("myForm").elements;

                for(var i = 0; i < 1 ; i++){
                    var id = form.elements[i].id;
                    sessionStorage.setItem(id,"false");
                }
            localStorage.setItem("run", true);
        }
    }

So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.

Edit2:

function initial(){
        if (localStorage.getItem("run") === null) {
                var form = document.getElementById("myForm");
                var tot = document.getElementById("myForm").length;

                for(var i = 0; i < tot ; i++){
                    sessionStorage.setItem(form.elements[i].id,"false");
                }
            localStorage.setItem("run", true);
        }
    }

This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.

 function loader(){
        var form = document.getElementById("myForm");
        var tot = 5;

        for(var i = 0; i < 5 ; i++){
            if(sessionStorage.getItem(form.elements[i].id) === "true"){
                document.getElementById(form.elements[i].id).style.backgroundColor = "green";
                return ;
            }else{
                document.getElementById(form.elements[i].id).style.backgroundColor = "red";
                return false;
            }
        }
    }

Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.

Body:
You're already storing all the elements in the form so it must be :

var form = document.getElementById("myForm").elements;
var id = form[i].id;

Or remove the elements part from the form variable like :

var form = document.getElementById("myForm");
var id = form.elements[i].id;


问:
Is there a way to create borders around rectangles in ggplot2 with geom_raster?
I'm creating a visualization of missing data by slightly tweaking some of the code from the missmap function in the Amelia package. I want to draw borders around my rectangles, but I can't figure out a way to do that in ggplot2.

I found the function "borders()" but that appears to be related to map work. I also tried using geom_rect, but it seems like that would require me to specify mins and maxes. Geom_raster seems to be doing exactly what I need, but I can't figure out how to specify borders.

This example code creates the visualization that I'm imagining, but I have more variables in the "real" version and I'd like to be able to outline each variable (var1, var2, etc.) with a line (border).

```<code>#Dataset
missmap_data_test <- data.frame(var1 = c(11, 26, NA, NA, 15),
                                var2 = c(NA, NA, 0, NA, 1))

#Create Function
ggplot_missing <-

function(x){
  x %>%
    is.na %>%
    melt %>%
    ggplot(data = .,
           aes(x = Var2,
               y = Var1)) +
    geom_raster(aes(fill = value)) +
    scale_fill_grey(name = "",
                    labels = c("Present","Missing")) +
    theme_minimal() +
    theme(axis.text.x  = element_text(angle=90, hjust=1)) +
    labs(x = "Variables in Dataset",
         y = "Observations")
}

#Feed the function my new data
ggplot_missing(missmap_data_test)
</code>```

答:
As @Axeman suggests, geom_tile does the job. I've updated your code to give an example below. Here, colour defines the colour of the border, while size define the thickness.

#Dataset
missmap_data_test <- data.frame(var1 = c(11, 26, NA, NA, 15),
                                var2 = c(NA, NA, 0, NA, 1))

# Load libraries
library(dplyr)
library(ggplot2)
library(reshape2)

#Create Function
ggplot_missing <- function(x){
    x %>%
      is.na %>%
      melt %>%
      ggplot(data = .,
             aes(x = Var2,
                 y = Var1)) +
      geom_tile(aes(fill = value), colour = "#FF3300", size = 2) +
      scale_fill_grey(name = "",
                      labels = c("Present","Missing")) +
      theme_minimal() +
      theme(axis.text.x  = element_text(angle=90, hjust=1)) +
      labs(x = "Variables in Dataset",
           y = "Observations")
  }

#Feed the function my new data
ggplot_missing(missmap_data_test)
```
<p><img src="https://i.imgur.com/3xWLkJR.png" alt="" /></p>
<p><sup>Created on 2019-05-30 by the reprex package (v0.3.0)</sup></p>
<p>If you're getting notches in the top left corner (discussed here and apparent in the plot above), you may want to update to the development version of <code>ggplot2</code>. That is, <code>devtools::install_github("tidyverse/ggplot2")</code>. For example, compare the plot above with the plot below:</p>

<p><img src="https://i.imgur.com/lFMIFX7.png" alt="" /></p>
<hr />
<h1>Update</h1>
<p>I assume this is a toy example, so I've tried to come up with a generic solution. Here, I've created a function called <code>boxy</code> that will make a data frame for <code>geom_rect</code> based on the original data frame.</p>

<pre class="lang-r prettyprint-override"><code>#Dataset
missmap_data_test <- data.frame(var1 = c(11, 26, NA, NA, 15),
                                var2 = c(NA, NA, 0, NA, 1))

# Function for making box data frame
boxy <- function(df){
  data.frame(xmin = seq(0.5, ncol(df) - 0.5),
             xmax = seq(1.5, ncol(df) + 0.5),
             ymin = 0.5, ymax = nrow(df) + 0.5)
}

# Load libraries
library(dplyr)
library(ggplot2)
library(reshape2)

#Create Function
ggplot_missing <- function(x){
  df_box <- boxy(x)
  df_rast <- x %>% is.na %>% melt

  ggplot() +
  geom_raster(data = df_rast,
              aes(x = Var2,
                  y = Var1,
                  fill = value)) +
  geom_rect(data = df_box,
            aes(xmin = xmin, xmax = xmax,
                ymin = ymin, ymax = ymax),
            colour = "#FF3300", fill = NA, size = 3) +
  scale_fill_grey(name = "",
                  labels = c("Present","Missing")) +
  theme_minimal() +
  theme(axis.text.x  = element_text(angle = 90, hjust = 1)) +
  labs(x = "Variables in Dataset",
       y = "Observations")
}

#Feed the function my new data
ggplot_missing(missmap_data_test)
</code>```

Created on 2019-05-30 by the reprex package (v0.3.0)

If you add a third variable (i.e., column) to your data frame, you get something like this:

Body:
I'm creating a visualization of missing data by slightly tweaking some of the code from the missmap function in the Amelia package. I want to draw borders around my rectangles, but I can't figure out a way to do that in ggplot2.

I found the function "borders()" but that appears to be related to map work. I also tried using geom_rect, but it seems like that would require me to specify mins and maxes. Geom_raster seems to be doing exactly what I need, but I can't figure out how to specify borders.

This example code creates the visualization that I'm imagining, but I have more variables in the "real" version and I'd like to be able to outline each variable (var1, var2, etc.) with a line (border).

#Dataset
missmap_data_test <- data.frame(var1 = c(11, 26, NA, NA, 15),
                                var2 = c(NA, NA, 0, NA, 1))

#Create Function
ggplot_missing <-

function(x){
  x %>%
    is.na %>%
    melt %>%
    ggplot(data = .,
           aes(x = Var2,
               y = Var1)) +
    geom_raster(aes(fill = value)) +
    scale_fill_grey(name = "",
                    labels = c("Present","Missing")) +
    theme_minimal() +
    theme(axis.text.x  = element_text(angle=90, hjust=1)) +
    labs(x = "Variables in Dataset",
         y = "Observations")
}

#Feed the function my new data
ggplot_missing(missmap_data_test)

Body:
As @Axeman suggests, geom_tile does the job. I've updated your code to give an example below. Here, colour defines the colour of the border, while size define the thickness.

#Dataset
missmap_data_test <- data.frame(var1 = c(11, 26, NA, NA, 15),
                                var2 = c(NA, NA, 0, NA, 1))

# Load libraries
library(dplyr)
library(ggplot2)
library(reshape2)

#Create Function
ggplot_missing <- function(x){
    x %>%
      is.na %>%
      melt %>%
      ggplot(data = .,
             aes(x = Var2,
                 y = Var1)) +
      geom_tile(aes(fill = value), colour = "#FF3300", size = 2) +
      scale_fill_grey(name = "",
                      labels = c("Present","Missing")) +
      theme_minimal() +
      theme(axis.text.x  = element_text(angle=90, hjust=1)) +
      labs(x = "Variables in Dataset",
           y = "Observations")
  }

#Feed the function my new data
ggplot_missing(missmap_data_test)

Created on 2019-05-30 by the reprex package (v0.3.0)

If you're getting notches in the top left corner (discussed here and apparent in the plot above), you may want to update to the development version of ggplot2. That is, devtools::install_github("tidyverse/ggplot2"). For example, compare the plot above with the plot below:

Update

I assume this is a toy example, so I've tried to come up with a generic solution. Here, I've created a function called boxy that will make a data frame for geom_rect based on the original data frame.

#Dataset
missmap_data_test <- data.frame(var1 = c(11, 26, NA, NA, 15),
                                var2 = c(NA, NA, 0, NA, 1))

# Function for making box data frame
boxy <- function(df){
  data.frame(xmin = seq(0.5, ncol(df) - 0.5),
             xmax = seq(1.5, ncol(df) + 0.5),
             ymin = 0.5, ymax = nrow(df) + 0.5)
}

# Load libraries
library(dplyr)
library(ggplot2)
library(reshape2)

#Create Function
ggplot_missing <- function(x){
  df_box <- boxy(x)
  df_rast <- x %>% is.na %>% melt

  ggplot() +
  geom_raster(data = df_rast,
              aes(x = Var2,
                  y = Var1,
                  fill = value)) +
  geom_rect(data = df_box,
            aes(xmin = xmin, xmax = xmax,
                ymin = ymin, ymax = ymax),
            colour = "#FF3300", fill = NA, size = 3) +
  scale_fill_grey(name = "",
                  labels = c("Present","Missing")) +
  theme_minimal() +
  theme(axis.text.x  = element_text(angle = 90, hjust = 1)) +
  labs(x = "Variables in Dataset",
       y = "Observations")
}

#Feed the function my new data
ggplot_missing(missmap_data_test)

Created on 2019-05-30 by the reprex package (v0.3.0)

If you add a third variable (i.e., column) to your data frame, you get something like this:


问:
Object.fromEntries only available on iOS? (react native - NOT WEB)
The title is pretty self explanatory but still, consider this sample code:

```<code>import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  render() {
    return (
      <Text>
         {Object.fromEntries("test")}
      </Text>
    );
  }
}
</code>```

Check it out on Expo Snacks

By opening it on an Android device, I get the error that the fromEntries function does not exist on Object:

But on iOS, it does exist:

(bad parameter supplied to it, but it exists, nevertheless)

So what's happening here? Aren't JS engines supposed to be identical between the 2 platforms? What other known discrepancies like these exist?

答: Functions like .flat(), Object.fromEntries, and some new ones are not yet supported by most browsers and Javascript engines. Which means we might see it being supported in the next update of android or iOS Javascript engines. support chart

Body:
The title is pretty self explanatory but still, consider this sample code:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  render() {
    return (
      <Text>
         {Object.fromEntries("test")}
      </Text>
    );
  }
}

Check it out on Expo Snacks

By opening it on an Android device, I get the error that the fromEntries function does not exist on Object:

But on iOS, it does exist:

(bad parameter supplied to it, but it exists, nevertheless)

So what's happening here? Aren't JS engines supposed to be identical between the 2 platforms? What other known discrepancies like these exist?


问:
Updating state with timer does not return updated values
I'm new to unit testing with Jest. The project has a progress indicator component that uses setInterval as a timer. I need to unit test that the "completed" state variable is updating correctly on 20ms ticks in the "progress" function.

```<code>"react-dom": "^16.8.6",
"react-redux": "^6.0.1",
"react-scripts": "^2.1.3"
</code>```

progress.js

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import CircularProgress from '@material-ui/core/CircularProgress';

const styles = theme => ({
  progress: {
    margin: theme.spacing.unit * 2
  }
});

class CircularDeterminate extends React.Component {
  state = {
    completed: 0
  };

  componentDidMount() {
    this.timer = setInterval(this.progress, 20);
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  progress = () => {
    let be = this.state.completed;
    console.log('>>>>>> ', this.state.completed);
    const { completed } = this.state;
    this.setState({ completed: completed >= 100 ? 0 : completed + 1 });
    console.log('+++++ ', be, '  ', this.state.completed);
  };

  render() {
    const { classes } = this.props;
    if (!this.props.statusCode) {
      return (
        <div>
          <CircularProgress
            className={classes.progress}
            variant="determinate"
            value={this.state.completed}
          />
        </div>
      );
    } else {
      return null;
    }
  }
}

CircularDeterminate.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(CircularDeterminate);

</code>```

progressTest.js

```<code>import React from 'react';
import { shallow, mount } from 'enzyme';
import Progress from '../progress';

describe('Input Component', () => {
  it('update timer', () => {
    jest.useFakeTimers();
    const wrapper = mount(<Progress />);
    wrapper.instance().setState({ completed: 8 });

    jest.advanceTimersByTime(41);
    wrapper.update();

    expect(wrapper.instance().state.completed).toBe(10);
  });
});

</code>```

The above test fails with: Expected: 10, Received: 8. I would expect "completed" to be of value 10 after 2 ticks (~41 ms).

答:
One issue in the above code (which may or may not be the actual problem depending on how Jest's fake timers work, but is certainly a problem) is you're breaking one of the fundamental rules of React state: Since state updates are asynchronous, if you're setting new state based on existing state, you must use the calback form of setState. So this is incorrect:

```<code>const { completed } = this.state;
this.setState({ completed: completed >= 100 ? 0 : completed + 1 });
console.log('+++++ ', be, '  ', this.state.completed);
</code>```

this is the correct form:

```<code>this.setState(
    ({completed}) => ({
        completed: completed >= 100 ? 0 : completed + 1
    }),
    () => {
        console.log('+++++ ', be, '  ', this.state.completed);
    }
);
</code>```

Body:
I'm new to unit testing with Jest. The project has a progress indicator component that uses setInterval as a timer. I need to unit test that the "completed" state variable is updating correctly on 20ms ticks in the "progress" function.

"react-dom": "^16.8.6",
"react-redux": "^6.0.1",
"react-scripts": "^2.1.3"

progress.js

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import CircularProgress from '@material-ui/core/CircularProgress';

const styles = theme => ({
  progress: {
    margin: theme.spacing.unit * 2
  }
});

class CircularDeterminate extends React.Component {
  state = {
    completed: 0
  };

  componentDidMount() {
    this.timer = setInterval(this.progress, 20);
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  progress = () => {
    let be = this.state.completed;
    console.log('>>>>>> ', this.state.completed);
    const { completed } = this.state;
    this.setState({ completed: completed >= 100 ? 0 : completed + 1 });
    console.log('+++++ ', be, '  ', this.state.completed);
  };

  render() {
    const { classes } = this.props;
    if (!this.props.statusCode) {
      return (

          <CircularProgress
            className={classes.progress}
            variant="determinate"
            value={this.state.completed}
          />

      );
    } else {
      return null;
    }
  }
}

CircularDeterminate.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(CircularDeterminate);

progressTest.js

import React from 'react';
import { shallow, mount } from 'enzyme';
import Progress from '../progress';

describe('Input Component', () => {
  it('update timer', () => {
    jest.useFakeTimers();
    const wrapper = mount(<Progress />);
    wrapper.instance().setState({ completed: 8 });

    jest.advanceTimersByTime(41);
    wrapper.update();

    expect(wrapper.instance().state.completed).toBe(10);
  });
});

The above test fails with: Expected: 10, Received: 8. I would expect "completed" to be of value 10 after 2 ticks (~41 ms).

Body:
One issue in the above code (which may or may not be the actual problem depending on how Jest's fake timers work, but is certainly a problem) is you're breaking one of the fundamental rules of React state: Since state updates are asynchronous, if you're setting new state based on existing state, you must use the calback form of setState. So this is incorrect:

const { completed } = this.state;
this.setState({ completed: completed >= 100 ? 0 : completed + 1 });
console.log('+++++ ', be, '  ', this.state.completed);

this is the correct form:

this.setState(
    ({completed}) => ({
        completed: completed >= 100 ? 0 : completed + 1
    }),
    () => {
        console.log('+++++ ', be, '  ', this.state.completed);
    }
);


问:
SQL: Select dynamic column name based on variable
I have a Microsoft SQL stored procedure whose column name I want to set via a variable that is passed into it:

```<code>CREATE PROCEDURE [My_Procedure]
   @myDynamicColumn varchar(50)
AS BEGIN
   SELECT 'value' AS @myDynamicColumn
END
</code>```

This does not work ("Incorrect syntax").  If I wrap the column name with [ ]:

```<code>SELECT 'value' AS [@myDynamicColumn]
</code>```

The column name literally outputs as '@myDynamicColumn' instead of the actual value.  Is there any way to do this? I've looked into dynamic SQL articles but nothing is quite what I'm asking for.

答:
```<code>EXEC ('SELECT ''value'' AS ' + @myDynamicColumn)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Microsoft SQL stored procedure whose column name I want to set via a variable that is passed into it:

CREATE PROCEDURE [My_Procedure]
   @myDynamicColumn varchar(50)
AS BEGIN
   SELECT 'value' AS @myDynamicColumn
END

This does not work ("Incorrect syntax").  If I wrap the column name with [ ]:

SELECT 'value' AS [@myDynamicColumn]

The column name literally outputs as '@myDynamicColumn' instead of the actual value.  Is there any way to do this? I've looked into dynamic SQL articles but nothing is quite what I'm asking for.


问:
vim command to go to the start of a C function
Is there a command to jump to the start of a C function .
While in the body of a function , I would want to jump to the start of the function to see the function name. </p>

答:
I use [[, no matter how deep you are inside such function.
Use ]] to go to next starting block function.


问:
Java ExceptionInitializationError in static Block
I am trying to call the URL retrieving method inside the static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.

I am trying to get a WSDL url from the config file. this configuration data stored DB.

```<code>static
{
    URL url = null;
    WebServiceException e = null;
    try
{
    url = getVertexConfiguration();
    } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
    }

private static URL getVertexConfiguration() throws MalformedURLException
    {
        try {
            configuration = configurationDAO.getByRefName("tax/vertex",
                    SecureSession.getUser().getDataDomain() != null ?
                            SecureSession.getUser().getDataDomain() : "app.cantata");
        } catch (B2BTransactionFailed b2BTransactionFailed) {

        }

        Map<String, DynamicAttribute> vertexTaxConfig = configuration.getConfigs();
        vertexWsdlUrl = vertexTaxConfig.get("vertexWsdlUrl").getValue().toString();

        return new URL(vertexWsdlUrl);
    }

}
</code>```

I am getting static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.

答:
You get ExceptioninInitializerBlock if there are some errors in the static initializer block. You handle only MalformedURLException, however, there are may be others.

You should add another catch for all exceptions and see what happens there.

```<code>static {
    URL url = null;
    WebServiceException e = null;
    try {
        url = getVertexConfiguration();
    } catch (MalformedURLException ex) {
        e = new WebServiceException(ex);
    } catch (Exception e) {
        //real problem
    }
}
</code>```

Body:
I am trying to call the URL retrieving method inside the static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.

I am trying to get a WSDL url from the config file. this configuration data stored DB.

static
{
    URL url = null;
    WebServiceException e = null;
    try
{
    url = getVertexConfiguration();
    } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
    }

private static URL getVertexConfiguration() throws MalformedURLException
    {
        try {
            configuration = configurationDAO.getByRefName("tax/vertex",
                    SecureSession.getUser().getDataDomain() != null ?
                            SecureSession.getUser().getDataDomain() : "app.cantata");
        } catch (B2BTransactionFailed b2BTransactionFailed) {

        }

        Map<String, DynamicAttribute> vertexTaxConfig = configuration.getConfigs();
        vertexWsdlUrl = vertexTaxConfig.get("vertexWsdlUrl").getValue().toString();

        return new URL(vertexWsdlUrl);
    }

}

I am getting static block, the Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError.

Body:
You get ExceptioninInitializerBlock if there are some errors in the static initializer block. You handle only MalformedURLException, however, there are may be others.

You should add another catch for all exceptions and see what happens there.

static {
    URL url = null;
    WebServiceException e = null;
    try {
        url = getVertexConfiguration();
    } catch (MalformedURLException ex) {
        e = new WebServiceException(ex);
    } catch (Exception e) {
        //real problem
    }
}


问:
Problem with webpack not converting es6 properly
When I run npm run build in my directory, to get all my files bundled into bundle.js, I find this error: ERROR in ./bundle.js from UglifyJs \n Unexpected token name «key», expected punc «;» [./bundle.js:8141,13].

So I went to bundle.js line 8141 and found this: for (let key in val) {

And therein lies the problem: let. Uglify cannot deal with let and const

So I've looked through the entire bundle.js file and the ONLY time let appears is literally right there, and a couple lines down, and I know specifically what package that code comes from: npm install clone-deep

None of the other packages I'm using are having this issue, they are all correctly converted from es6 before uglify runs, and I use let and const in my own code all the time. This one package only is causing me the issue.

Here's my package.json

```<code>{
  "name": "jsx2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "autobind-decorator": "^2.1.0",
    "axios": "^0.18.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "classnames": "^2.2.5",
    "clone-deep": "^4.0.1",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-toastify": "^4.5.2",
    "webpack": "^3.11.0"
  },
  "scripts": {
    "dev": "webpack -d --watch",
    "build": "webpack -p --config webpack.build.config.js"
  }
}
</code>```

And here's my webpack.build.config.js

```<code>// https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'out/');
var APP_DIR = path.resolve(__dirname, 'src/');

var config = {
    entry: ['babel-polyfill', APP_DIR + '/App.jsx'],
    output: {
        path: BUILD_DIR,
        filename: './bundle.js'
        //https://cloud.githubusercontent.com/assets/593571/20785959/290f7fbc-b7b4-11e6-9ad2-7dafd7803552.png
        //https://github.com/babel/babel-loader/issues/93
    },

    module : {
        loaders : [
            {
                test : /\.jsx?/,
                include : APP_DIR,
                loader : 'babel-loader',
                options: {
                    "presets" : ["env", "react"],
                    "plugins": ["transform-decorators-legacy"]
                }
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx'],
    }
};

module.exports = config;
</code>```

-- edit

Just to confirm, I did actually go into clone-deep index.js and change the lets to vars, and it all worked and I got no errors. I don't really consider that as a solution, because... there's no reason why this one package should have this error and nothing else. But it is definitely this one package that is the source of the issue.

答:
Some npm packages have no es5 version. We have to accept this or use other packages.

If you want to continue to use clone-deep, you have to add this package to include property of your babel-loader config:

```<code>...
{
    test : /\.jsx?/,
    include : [APP_DIR, path.resolve(__dirname, 'node_modules', 'clone-deep')],
    loader : 'babel-loader',
    options: {
        "presets" : ["env", "react"],
        "plugins": ["transform-decorators-legacy"]
    }
};
...
</code>```

You can read more in this issue

Body:
When I run npm run build in my directory, to get all my files bundled into bundle.js, I find this error: ERROR in ./bundle.js from UglifyJs \n Unexpected token name «key», expected punc «;» [./bundle.js:8141,13].

So I went to bundle.js line 8141 and found this: for (let key in val) {

And therein lies the problem: let. Uglify cannot deal with let and const

So I've looked through the entire bundle.js file and the ONLY time let appears is literally right there, and a couple lines down, and I know specifically what package that code comes from: npm install clone-deep

None of the other packages I'm using are having this issue, they are all correctly converted from es6 before uglify runs, and I use let and const in my own code all the time. This one package only is causing me the issue.

Here's my package.json

{
  "name": "jsx2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "autobind-decorator": "^2.1.0",
    "axios": "^0.18.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "classnames": "^2.2.5",
    "clone-deep": "^4.0.1",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-toastify": "^4.5.2",
    "webpack": "^3.11.0"
  },
  "scripts": {
    "dev": "webpack -d --watch",
    "build": "webpack -p --config webpack.build.config.js"
  }
}

And here's my webpack.build.config.js

// https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'out/');
var APP_DIR = path.resolve(__dirname, 'src/');

var config = {
    entry: ['babel-polyfill', APP_DIR + '/App.jsx'],
    output: {
        path: BUILD_DIR,
        filename: './bundle.js'
        //https://cloud.githubusercontent.com/assets/593571/20785959/290f7fbc-b7b4-11e6-9ad2-7dafd7803552.png
        //https://github.com/babel/babel-loader/issues/93
    },

    module : {
        loaders : [
            {
                test : /\.jsx?/,
                include : APP_DIR,
                loader : 'babel-loader',
                options: {
                    "presets" : ["env", "react"],
                    "plugins": ["transform-decorators-legacy"]
                }
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx'],
    }
};

module.exports = config;

-- edit

Just to confirm, I did actually go into clone-deep index.js and change the lets to vars, and it all worked and I got no errors. I don't really consider that as a solution, because... there's no reason why this one package should have this error and nothing else. But it is definitely this one package that is the source of the issue.

Body:
Some npm packages have no es5 version. We have to accept this or use other packages.

If you want to continue to use clone-deep, you have to add this package to include property of your babel-loader config:

...
{
    test : /\.jsx?/,
    include : [APP_DIR, path.resolve(__dirname, 'node_modules', 'clone-deep')],
    loader : 'babel-loader',
    options: {
        "presets" : ["env", "react"],
        "plugins": ["transform-decorators-legacy"]
    }
};
...

You can read more in this issue


问:
Updated State not being retrieved by method
In this file, I'm pulling in a bunch of data from an API and assigning it to the array of "baseData". In another file, I have an onkeyup event calling the generateResults method. But then generateResults method is only getting the original, blank state of the array. I'm new to react so any help is appreciated. Thanks!

import React from 'react';
import axios from 'axios';

export class LINKS extends React.Component{

constructor(props){
    super(props);
    this.state={
        baseData: []
}}

    getBaseData(){

        axios.get("http://localhost:3000/api/links")
        .then(response => {
            this.setState({baseData: response.data});
        }).catch((error) => {
            console.error(error);
        });

 }

    componentDidMount(){
        this.getBaseData();
    }

    generateResults(){
        var linkInfo = this.state.baseData
        var searchBar = document.getElementById('searchBar')
        console.log(linkInfo)

        for(var i = 0; i < linkInfo.length; i ++){

        }

    }

render(){
    var linkInfo = this.state.baseData

    // console.log(linkInfo)

    if(linkInfo.length === 0){
        return(

 Loading...

)
    } else {

    return(

{linkInfo.map((info, i) =>

            {info['client']}
            {info.links.map((link, i) =>

 {link.linkTitle}

 {link.url}
) }

        )}

        )
}

}
}```
</div>
</div>
</p>

<p>Method in the other class calling the generateResults method.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>  handleSearch(){
    let links = new LINKS
    links.generateResults()
  }</code>```

答:
Because you should return any HTML into your arrow function map loop with double Parentheses like this :

                    {
                        this.props.items.map((item) => (

{item}

                        ))
                    }

```
</div>
</div>
</p>

<p>I've edited your code, try this :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
{
  linkInfo.map((info, i) => (
      <div>
      <u>{info['client']}</u>
      {
          info.links.map((link, i) => (
            <div> {link.linkTitle}
            <br/> {link.url} </div>
          ))
      }
      <hr/></div>
  ))
}
</div></code>```

Body:
In this file, I'm pulling in a bunch of data from an API and assigning it to the array of "baseData". In another file, I have an onkeyup event calling the generateResults method. But then generateResults method is only getting the original, blank state of the array. I'm new to react so any help is appreciated. Thanks!

import React from 'react';
import axios from 'axios';

export class LINKS extends React.Component{

constructor(props){
    super(props);
    this.state={
        baseData: []
}}

    getBaseData(){

        axios.get("http://localhost:3000/api/links")
        .then(response => {
            this.setState({baseData: response.data});
        }).catch((error) => {
            console.error(error);
        });

 }

    componentDidMount(){
        this.getBaseData();
    }

    generateResults(){
        var linkInfo = this.state.baseData
        var searchBar = document.getElementById('searchBar')
        console.log(linkInfo)

        for(var i = 0; i < linkInfo.length; i ++){

        }

    }

render(){
    var linkInfo = this.state.baseData

    // console.log(linkInfo)

    if(linkInfo.length === 0){
        return(

 Loading...

)
    } else {

    return(

{linkInfo.map((info, i) =>

            {info['client']}
            {info.links.map((link, i) =>

 {link.linkTitle}

 {link.url}
) }

        )}

        )
}

}
}

Method in the other class calling the generateResults method.

  handleSearch(){
    let links = new LINKS
    links.generateResults()
  }

Body:
Because you should return any HTML into your arrow function map loop with double Parentheses like this :

<ul>
                    {
                        this.props.items.map((item) => (
                            <li>{item}</li>
                        ))
                    }
</ul>

I've edited your code, try this :

<div>
{
  linkInfo.map((info, i) => (
      <div>
      <u>{info['client']}</u>
      {
          info.links.map((link, i) => (
            <div> {link.linkTitle}
            <br/> {link.url} </div>
          ))
      }
      <hr/></div>
  ))
}
</div>


问:
How to prevent pasting text in ember input helper?
I'm using ember input helper to get some value in the application. The text field should not allow any text to be pasted. (Something like re-enter some value)

I've just tried

```<code>{{input value=inputText onpaste="return false"}}
</code>```

This didn't work. But in normal html, The following works.

```<code><input value=inputText onpaste="return false">
</code>```

But the problem here is no two-way binding (which supports in ember input helper).

答:
You don't need two way binding:

```<code><input value={{inputText}} oninput={{action (mut inputText) value="target.value"}} onpaste="return false">
</code>```

Sidenote: Never do this! This can be horrible to accessibility and user experience. It also never really works. You can always have browser plugins disabling this, or in this simple case people pasting by right click.

Body:
I'm using ember input helper to get some value in the application. The text field should not allow any text to be pasted. (Something like re-enter some value)

I've just tried

{{input value=inputText onpaste="return false"}}

This didn't work. But in normal html, The following works.

<input value=inputText onpaste="return false">

But the problem here is no two-way binding (which supports in ember input helper).

Body:
You don't need two way binding:

<input value={{inputText}} oninput={{action (mut inputText) value="target.value"}} onpaste="return false">

Sidenote: Never do this! This can be horrible to accessibility and user experience. It also never really works. You can always have browser plugins disabling this, or in this simple case people pasting by right click.


问:
Could I use div and article inside section?
I have a section which is devided by 2 parts. Left side is only for image and right - only for article. Is my code correct?</p>

```<code><section>
  <h1>Section header</h1>
  <div style="float: left;">
    <img src="#" alt="somepic" />
  </div>
  <article style="float: right;">
    <h2>About me</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </article>
</section>
</code>```

答:
Yes, your markup structure is perfectly acceptable. An HTML5 section element can be used at your discretion to contain content related to a particular topic or activity. There are no specific rules about what elements it may include. You might use figure for your image wrapper as well. MDN

I recommend against using floats (which often lead to unpredictable or undesired behavior) and inline styles (which are just messy), though. Instead, set your elements to inline-block and give them explicit (percentage) widths using CSS classes in an embedded style tag or an external stylesheet.

Body:
I have a section which is devided by 2 parts. Left side is only for image and right - only for article. Is my code correct?

Section header

About me

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.


问:
Issues with Swing timers
I have 3 timers running on my application which takes care of different action. Timer 1 will deals with automatic logout of the application, timer 2 deals with updating a table, timer 3 deals with updating the color of swing buttons. First timer uses the calculation based on the variables and its values, second and third timers works out of MYSQL queries.

Now when i run this application on an average performance machine the application is not moving .I need to wait for few seconds to a normal click to happen or a window to open. Is it something to do with the timers ? If yes do I have any alternative suggestions to get rid of this timer problem?

答:
It could well be the timers, if they are performing considerable work when fired. It's not usually a good idea to use swing timers for long-running tasks, since they will block the EDT and freeze the UI.

Here are some suggestions to avoid this:

Use a java.util.Timer rather than the swing timer. This will run the database code on a background thread, avoiding blocking the event queue.

Continue to use the swing timer, but have the timer action simply start a SwingWorker to perform the task. This gives the benefit of background processing with the ability to post updates to your UI, if it's a operation that takes more than a second or so to execute.

The problem isn't how many timers you have, but how long each timer takes to do it's work, since the timer's actionPerformed method is run on the swing event thread, meaning that while a timer is doing it's thing, no UI updates can happen.

Title: Issues with Swing timers


问:
How can I transform this statement into a ternary?
I am trying to turn a simple if/else statement into a ternary for practice and I'm having trouble. From what I understand, the logic is:

```<code>condition ? (action to take if condition is true) : (action if false);
</code>```

My condition is if(result == 8).

I've already tried:

```<code>result == 8 ? return true : return false;
</code>```

and

```<code>result = 8 ? return true : return false;
</code>```

Here's my code, the end of which I would like to convert

```<code>public boolean sum28(int[] nums) {

    int result = 0;
    for(int i=0; i<nums.length; i++) {
        if(nums[i] == 2) {
            result+=2;
        }
    }
    if(result == 8) {
        return true;
    }
    return false;
}
</code>```

I'm getting a type mismatch: cannot convert from int to boolean when I use only 1 equals sign, and getting a invalid token "==" when using two.

答:
I've already tried: result == 8 ? return true : return false;

You're not too far off. == results in a boolean, so you just want:

```<code>return result == 8;
</code>```

That works because you already have the value (true or false) that you want to return; it's the result of result == 8.

Similarly, if your original were the other way around (if (result == 8) { return false; } else { return true; }), you'd use !=:

```<code>// If you wanted the opposite
return result != 8;
</code>```

In the more general case, suppose you wanted to return "A" if result == 8 and "B" otherwise. You'd do that like this:

```<code>// If you wanted to return "A" (if result == 8) or "B" (if not)
return result == 8 ? "A" : "B";
</code>```

Body:
I am trying to turn a simple if/else statement into a ternary for practice and I'm having trouble. From what I understand, the logic is:

condition ? (action to take if condition is true) : (action if false);

My condition is if(result == 8).

I've already tried:

result == 8 ? return true : return false;

and

result = 8 ? return true : return false;

Here's my code, the end of which I would like to convert

public boolean sum28(int[] nums) {

    int result = 0;
    for(int i=0; i<nums.length; i++) {
        if(nums[i] == 2) {
            result+=2;
        }
    }
    if(result == 8) {
        return true;
    }
    return false;
}

I'm getting a type mismatch: cannot convert from int to boolean when I use only 1 equals sign, and getting a invalid token "==" when using two.

Body:
I've already tried: result == 8 ? return true : return false;

You're not too far off. == results in a boolean, so you just want:

return result == 8;

That works because you already have the value (true or false) that you want to return; it's the result of result == 8.

Similarly, if your original were the other way around (if (result == 8) { return false; } else { return true; }), you'd use !=:

// If you wanted the opposite
return result != 8;

In the more general case, suppose you wanted to return "A" if result == 8 and "B" otherwise. You'd do that like this:

// If you wanted to return "A" (if result == 8) or "B" (if not)
return result == 8 ? "A" : "B";


问:
JQuery-UI tooltip: enable only for mouseover, disable for focusin
Is it possible to make JQuery-UI tooltip open only on onmouseover but not on focusin event, to make it behave more like a native browser tooltip?

I tried this solution, but it didn't work:

```<code>$(document).tooltip({
    items:".jquery-tooltip",
    track:true, show:false, hide:false,
    open: function(event, ui) {
        if(event.originalEvent.type == "focusin") {
            $(document).tooltip("close");
        }
    },
    content: function() {
        return "tooltip text here";
    }
});
</code>```

答:
This works:</p>

```<code>$(document).tooltip().off("focusin focusout");
</code>```

Body:
Is it possible to make JQuery-UI tooltip open only on onmouseover but not on focusin event, to make it behave more like a native browser tooltip?

I tried this solution, but it didn't work:

$(document).tooltip({
    items:".jquery-tooltip",
    track:true, show:false, hide:false,
    open: function(event, ui) {
        if(event.originalEvent.type == "focusin") {
            $(document).tooltip("close");
        }
    },
    content: function() {
        return "tooltip text here";
    }
});

Body:
This works:

$(document).tooltip().off("focusin focusout");


问:
How to test a react component that is dependent on useContext hook?
I have a component that uses useContext and then its output is dependent on the value in the context. A simple example:

```<code>import React, { useContext } from 'react';

const MyComponent = () => {
  const name = useContext(NameContext);

  return <div>{name}</div>;
};
</code>```

When testing this component with the shallow renderer from react and jest snapshots. How can I change the value of NameContext?

答:
I tried to use Enzyme + .dive, but when diving, it does not recognize the context props, it gets the default ones. Actually, it is a known issue by the Enzyme team.
Meanwhile, I came up with a simpler solution which consists in creating a custom hook just to return useContext with your context and mocking the return of this custom hook on the test:

AppContext.js - Creates the context.

```<code>import React, { useContext } from 'react';

export const useAppContext = () => useContext(AppContext);

const defaultValues = { color: 'green' };
const AppContext = React.createContext(defaultValues);

export default AppContext;
</code>```

App.js — Providing the context

```<code>import React from 'react';
import AppContext from './AppContext';
import Hello from './Hello';

export default function App() {
  return (
    <AppContext.Provider value={{ color: 'red' }}>
      <Hello />
    </AppContext.Provider>
  );
}
</code>```

Hello.js - Consuming the context

```<code>import React from 'react';
import { useAppContext } from './AppContext';

const Hello = props => {
  const { color } = useAppContext();
  return <h1 style={{ color: color }}>Hello {color}!</h1>;
};

export default Hello;
</code>```

Hello.test.js - Testing the useContext with Enzyme shallow

```<code>import React from 'react';
import { shallow } from 'enzyme';
import * as AppContext from './AppContext';

import Hello from './Hello';

describe('<Hello />', () => {
  test('it should mock the context', () => {
    const contextValues = { color: 'orange' };
    jest
      .spyOn(AppContext, 'useAppContext')
      .mockImplementation(() => contextValues);
    const wrapper = shallow(<Hello />);
    const h1 = wrapper.find('h1');

    expect(h1.text()).toBe('Hello orange!');
  });
});
</code>```

Check the full Medium article out https://medium.com/7shifts-engineering-blog/testing-usecontext-react-hook-with-enzyme-shallow-da062140fc83

Body:
I have a component that uses useContext and then its output is dependent on the value in the context. A simple example:

import React, { useContext } from 'react';

const MyComponent = () => {
  const name = useContext(NameContext);

  return
{name}
;
};

When testing this component with the shallow renderer from react and jest snapshots. How can I change the value of NameContext?

Body:
I tried to use Enzyme + .dive, but when diving, it does not recognize the context props, it gets the default ones. Actually, it is a known issue by the Enzyme team.
Meanwhile, I came up with a simpler solution which consists in creating a custom hook just to return useContext with your context and mocking the return of this custom hook on the test:

AppContext.js - Creates the context.

import React, { useContext } from 'react';

export const useAppContext = () => useContext(AppContext);

const defaultValues = { color: 'green' };
const AppContext = React.createContext(defaultValues);

export default AppContext;

App.js — Providing the context

import React from 'react';
import AppContext from './AppContext';
import Hello from './Hello';

export default function App() {
  return (
    <AppContext.Provider value={{ color: 'red' }}>
      <Hello />
    </AppContext.Provider>
  );
}

Hello.js - Consuming the context

import React from 'react';
import { useAppContext } from './AppContext';

const Hello = props => {
  const { color } = useAppContext();
  return <h1 style={{ color: color }}>Hello {color}!</h1>;
};

export default Hello;

Hello.test.js - Testing the useContext with Enzyme shallow

import React from 'react';
import { shallow } from 'enzyme';
import * as AppContext from './AppContext';

import Hello from './Hello';

describe('<Hello />', () => {
  test('it should mock the context', () => {
    const contextValues = { color: 'orange' };
    jest
      .spyOn(AppContext, 'useAppContext')
      .mockImplementation(() => contextValues);
    const wrapper = shallow(<Hello />);
    const h1 = wrapper.find('h1');

    expect(h1.text()).toBe('Hello orange!');
  });
});

Check the full Medium article out https://medium.com/7shifts-engineering-blog/testing-usecontext-react-hook-with-enzyme-shallow-da062140fc83


问:
How to make a loop that successively includes one more element of a numpy array in order to calculate the running variance?
I have numbers stored in an array like [1, 6, 12, 4...].  I want to do a calculation where each new iteration will use one more element of the array.

For example, the first iteration will use only the number 1.

The second iteration will use 1 and 6.

The third will use 1, 6, and 12, and so on.

More detail for anyone interested in statistics/variance in Python:

I want to calculate running variance on the data in the array. It seems straightforward to get variance on a whole array in Python. So I'll put my array up to element i inside the loop.  I will calculate variance on the array as looping progresses and the array "grows."  If anyone knows a better way to do this, I would be grateful to know.

答:
Depending on how efficient you want to be, you can do it different ways.

The most direct is to use sum up to the current value using slices:

```<code>ls = [1, 6, 12, 4]

for i in range(len(ls)):
    print(sum(ls[:i+1]))
</code>```

However you'll find that over time, an accumulator pattern will perform much better. The code below removes the call to sum, reducing the computational complexity of the loop to O(n). It should perform noticably faster on large datasets with hundreds of thousands of items:

```<code>ls = [1, 6, 12, 4]

total = 0
for item in ls:
    total += item
    print(total)
</code>```

This is such a common pattern that it can be convenient to create a reusable function. The code below lets you replace foo behaviour with other behaviour:

```<code>def accumulate(fn, iterable):
    total = 0
    for i, item in iterable:
        total = fn(i, item, total)

def foo(i, item, total):
    print(f'The running total is {total}.')
    return total + 2 * item - i

accumulate(foo, [1, 6, 12, 4])
</code>```

```<code>>>> The running total is 2.
>>> The running total is 13.
>>> The running total is 35.
>>> The running total is 40.
</code>```

Body:
Depending on how efficient you want to be, you can do it different ways.

The most direct is to use sum up to the current value using slices:

ls = [1, 6, 12, 4]

for i in range(len(ls)):
    print(sum(ls[:i+1]))

However you'll find that over time, an accumulator pattern will perform much better. The code below removes the call to sum, reducing the computational complexity of the loop to O(n). It should perform noticably faster on large datasets with hundreds of thousands of items:

ls = [1, 6, 12, 4]

total = 0
for item in ls:
    total += item
    print(total)

This is such a common pattern that it can be convenient to create a reusable function. The code below lets you replace foo behaviour with other behaviour:

def accumulate(fn, iterable):
    total = 0
    for i, item in iterable:
        total = fn(i, item, total)

def foo(i, item, total):
    print(f'The running total is {total}.')
    return total + 2 * item - i

accumulate(foo, [1, 6, 12, 4])

>>> The running total is 2.
>>> The running total is 13.
>>> The running total is 35.
>>> The running total is 40.


问:
How to debug an iOS app extension?
I'm trying to debug an iOS app extension and all I can do is to set breakpoints but it would be nice to be able to print to console.

Is this possible with Xcode 9?

Or at least read it somewhere, maybe a file?

I went to see my device's logs in "devices and simulators" but could't find what I printed from my iOS app extension.

答: You can use "placeholder"  variable to print some debug messages </p>

Title: How to debug an iOS app extension?


答:
You could build your query into a string and use exec</p>

```<code>CREATE PROCEDURE [My_Procedure]
   @myDynamicColumn varchar(50)
AS BEGIN
   EXEC('SELECT ''value'' AS ' + @myDynamicColumn)
END
</code>```

Title: SQL: Select dynamic column name based on variable

Body:
I have a Microsoft SQL stored procedure whose column name I want to set via a variable that is passed into it:

CREATE PROCEDURE [My_Procedure]
   @myDynamicColumn varchar(50)
AS BEGIN
   SELECT 'value' AS @myDynamicColumn
END

This does not work ("Incorrect syntax").  If I wrap the column name with [ ]:

SELECT 'value' AS [@myDynamicColumn]

The column name literally outputs as '@myDynamicColumn' instead of the actual value.  Is there any way to do this? I've looked into dynamic SQL articles but nothing is quite what I'm asking for.

Body:
You could build your query into a string and use exec

CREATE PROCEDURE [My_Procedure]
   @myDynamicColumn varchar(50)
AS BEGIN
   EXEC('SELECT ''value'' AS ' + @myDynamicColumn)
END


答:
The correct syntax would be

```<code>return (result == 8) ? true : false;
</code>```

but here you can just

```<code>return result == 8;
</code>```

Title: How can I transform this statement into a ternary?

Body:
The correct syntax would be

return (result == 8) ? true : false;

but here you can just

return result == 8;


问:
Writing an iterative function
I'm writing a program that solves a system of lineair equations. I need to run some iterations in order to see my objective value improving. I first wrote the program with writing print functions at the bottom of my file. So I did the iterations myself basically. I now want to write the number of iterations as an imput argument for the function.

I tried working with while and for loops but that did not seem to work for me. So now I tried the format as you can see below. I have not put my entire program here, but just the basic structure of what it does.

def function(A,x,c,iter):
    if iter == 0:
        return x
    else:
        A = 1/2 * A
        c = 1/2 * c
        x1 = 1/2 * x

        iter = iter - 1

        function(A,x1,c,iter)
```

When I have iter = 0, it gives me the immediate value of x. But when iter > 0 I get 'None' back... Can anyone explain why it does this and help me fix my program? Thanks!

答:
As a for loop it would look like:

```<code>def function(A,x,c,iterN):
    for _ in range(iterN)
        A = 1/2 * A
        c = 1/2 * c
        x = 1/2 * x
    return x
</code>```

As a note, do not use iter for variable naming since it is a built-in python function.

Title: Writing an iterative function

Body:
I'm writing a program that solves a system of lineair equations. I need to run some iterations in order to see my objective value improving. I first wrote the program with writing print functions at the bottom of my file. So I did the iterations myself basically. I now want to write the number of iterations as an imput argument for the function.

I tried working with while and for loops but that did not seem to work for me. So now I tried the format as you can see below. I have not put my entire program here, but just the basic structure of what it does.

def function(A,x,c,iter):
    if iter == 0:
        return x
    else:
        A = 1/2 * A
        c = 1/2 * c
        x1 = 1/2 * x

        iter = iter - 1

        function(A,x1,c,iter)

When I have iter = 0, it gives me the immediate value of x. But when iter > 0 I get 'None' back... Can anyone explain why it does this and help me fix my program? Thanks!

Body:
As a for loop it would look like:

def function(A,x,c,iterN):
    for _ in range(iterN)
        A = 1/2 * A
        c = 1/2 * c
        x = 1/2 * x
    return x

As a note, do not use iter for variable naming since it is a built-in python function.


问:
Declared a const outside a react component to use it in different places
I have to use ABC in different places, I use to have the same definition in this two places but the I extract it outside the component.

Is this a react way to do this or are there better ways?

```<code> const ABC = {
    jane: 0,
    john: 1
  };

 class ProjectPage extends React.Component {
    constructor(props) {
      super(props);
      resetIdCounter();
    }

   static async getInitialProps({ query }) {
      return { query, variable:ABC[query.name] };
   }

  render() {
    //code that use ABC
  }
}
</code>```

答:
Add a parallel file in you project, ex myConfig.js. Inside this file, export this const like

```<code>export const ABC = {
    jane: 0,
    john: 1,
 };
</code>```

Then import this newly created myConfig.js in your above said react file (ProjectPage) like:

```<code>import * as myConfig from './myConfig';
// or import only what you need directly
import { ABC } from './myConfig';
</code>```

Now, just use wherever you want in this file like myConfig.ABC;

Body:
I have to use ABC in different places, I use to have the same definition in this two places but the I extract it outside the component.

Is this a react way to do this or are there better ways?

 const ABC = {
    jane: 0,
    john: 1
  };

 class ProjectPage extends React.Component {
    constructor(props) {
      super(props);
      resetIdCounter();
    }

   static async getInitialProps({ query }) {
      return { query, variable:ABC[query.name] };
   }

  render() {
    //code that use ABC
  }
}

Body:
Add a parallel file in you project, ex myConfig.js. Inside this file, export this const like

export const ABC = {
    jane: 0,
    john: 1,
 };

Then import this newly created myConfig.js in your above said react file (ProjectPage) like:

import * as myConfig from './myConfig';
// or import only what you need directly
import { ABC } from './myConfig';

Now, just use wherever you want in this file like myConfig.ABC;


问:
Insert into boost::program_options::variables_map by index operator
I have a boost::program_options::variables_map args. Now I want to insert into this map manually like a key-value pair.
Example:

```<code>boost::program_options::variables_map args

args["document"] = "A";

args["flag"] = true;
</code>```

The problem is that I already have these 2 options

```<code>desc.add_options()
    ("document", po::value<std::string>())
    ("flag", po::value<bool>());
</code>```

but they are given empty input from the command line sometimes. So if they are empty, then I have to update them inside the po::variables_map args itself

答:
Since it publicly inherits from std::map<std::string, variable_value> it should be relatively safe to cast it to std::map and use as such:

```<code>(*static_cast<std::map<std::string, variable_value>*>(my_variable_map))[name] = value;
</code>```

There's no guarantee that this is enough to make variable_map use it, but currently it seems to be: cpp, h.

It's annoying that this is needed.

Body:
I have a boost::program_options::variables_map args. Now I want to insert into this map manually like a key-value pair.
Example:

boost::program_options::variables_map args

args["document"] = "A";

args["flag"] = true;

The problem is that I already have these 2 options

desc.add_options()
    ("document", po::value<std::string>())
    ("flag", po::value<bool>());

but they are given empty input from the command line sometimes. So if they are empty, then I have to update them inside the po::variables_map args itself

Body:
Since it publicly inherits from std::map<std::string, variable_value> it should be relatively safe to cast it to std::map and use as such:

(*static_cast<std::map<std::string, variable_value>*>(my_variable_map))[name] = value;

There's no guarantee that this is enough to make variable_map use it, but currently it seems to be: cpp, h.

It's annoying that this is needed.


问:
TypeError: GetSize() missing 1 required positional argument: 'self'
I am getting the following error iwht below code:

TypeError: GetSize() missing 1 required positional argument: 'self'

```<code>import PySpin

system = PySpin.System.GetInstance()
cam_list = system.GetCameras()

# This works:

numCams  = cam_list.GetSize()

# this fails:

numCams  = PySpin.CameraList.GetSize()

print ("No. of cams: ", numCams)
</code>```

Why?

Edit:

```<code>class myMain(object):
    def main(self):
        numCams  = PySpin.CameraList.GetSize()
        print ("No. of cams: ", numCams)
</code>```

答:
Try initializing it before you call it</p>

```<code>cams = PySpin.CameraList()
numCams = cams.GetSize()
print ("No. of cams: ", numCams)
</code>```

Body:
I am getting the following error iwht below code:

TypeError: GetSize() missing 1 required positional argument: 'self'

import PySpin

system = PySpin.System.GetInstance()
cam_list = system.GetCameras()

# This works:

numCams  = cam_list.GetSize()

# this fails:

numCams  = PySpin.CameraList.GetSize()

print ("No. of cams: ", numCams)

Why?

Edit:

class myMain(object):
    def main(self):
        numCams  = PySpin.CameraList.GetSize()
        print ("No. of cams: ", numCams)

Body:
Try initializing it before you call it

cams = PySpin.CameraList()
numCams = cams.GetSize()
print ("No. of cams: ", numCams)


问:
How do I auto-reload a Chrome extension I'm developing?
I'd like for my chrome extension to reload every time I save a file in the extension folder, without having to explicitly click "reload" in chrome://extensions/. Is this possible?

Edit: I'm aware I can update the interval at which Chrome reloads extensions, which is a half-way solution, but I'd rather either making my editor (emacs or textmate) trigger on-save a reload or asking Chrome to monitor the directory for changes.

答:
I am using a shortcut to reload. I don't want to reload all the time when I save a file

So my approach is lightweight, and you can leave the reload function in

manifest.json

```<code>{
    ...
    "background": {
        "scripts": [
            "src/bg/background.js"
        ],
        "persistent": true
    },
    "commands": {
        "Ctrl+M": {
            "suggested_key": {
                "default": "Ctrl+M",
                "mac": "Command+M"
            },
            "description": "Ctrl+M."
        }
    },
    ...
}
</code>```

src/bg/background.js

```<code>chrome.commands.onCommand.addListener((shortcut) => {
    console.log('lets reload');
    console.log(shortcut);
    if(shortcut.includes("+M")) {
        chrome.runtime.reload();
    }
})
</code>```

Now press Ctrl + M in the chrome browser to reload

Body:
I am using a shortcut to reload. I don't want to reload all the time when I save a file

So my approach is lightweight, and you can leave the reload function in

manifest.json

{
    ...
    "background": {
        "scripts": [
            "src/bg/background.js"
        ],
        "persistent": true
    },
    "commands": {
        "Ctrl+M": {
            "suggested_key": {
                "default": "Ctrl+M",
                "mac": "Command+M"
            },
            "description": "Ctrl+M."
        }
    },
    ...
}

src/bg/background.js

chrome.commands.onCommand.addListener((shortcut) => {
    console.log('lets reload');
    console.log(shortcut);
    if(shortcut.includes("+M")) {
        chrome.runtime.reload();
    }
})

Now press Ctrl + M in the chrome browser to reload


问:
Will Android ListView load faster than Customized View?
I need to display a complicated list in my app. On each row there will be a checkbox and some TextView.

I know this could be done via ListView/Adapter, but I was worried it requires too much tweaking to make it fits my specific requirement, so I just created my own customized MyListView inheriting LinearLayout. On initiating, it adds MyListViewItem (inherited from RelativeLayout) dynamically.

The customized view functions fine. However, I notice that the rendering speed of MyListView is a little too slow, so I wondered will it be faster if I use ListView/Adapter instead?

Thanks,

答: The benefit of using ListView rather than a great big LinearLayout is that the OS can do a better job of optimizing when views are inflated, and the recycling of views, based on what is actually visible to the user. It also makes it easier to perform common actions such as scrolling to a particular row. </p>


问:
What's the difference between booting a linux kernel and a standalone application?
I have a MIPS based board (MediaTek mt7620) with a proprietary and closed bootloader (u-boot) with cut off a lot of functionality, like booting a standalone application. (I'm not allowed to change/reflash this bootloader, 'cause a lot of customers use this board and if we were updating the bootloader and it failed we would faced with a lot of bricks :) (bootloader supports a boot over tftp protocol) )

I'm trying to change a boot sequence provided by a board manufacturer: ROM bootloader --> flash bootloader (u-boot) --> linux kernel to a: ROM bootloader --> flash bootloader (u-boot) --> boot trap --> linux kernel. For another board (mt7621) with a u-boot which supports a booting a standalone application I was able to create some boot trap u-boot image (standalone app) and put it into the flash instead of a linux kernel (I moved linux kernel down). (this boot trap makes some work, loads and boots the linux kernel by using a ranand_read/do_bootm functions provided by the u-boot via a jump table.

As I mentioned, a u-boot for an mt7620-based board doesn't support booting a standalone application, so I decided to create a boot trap as a u-boot linux image (not as a u-boot standalone app image) keeping code of boot trap almost the same (I changed only function signature: for a standalone app u-boot image 2 args get passed, for a linux u-boot image - 4; and load/entry addresses).

This is a log from a serial port,
   for an mt7621-based board:

```<code>## Booting image at bc140000 ...
   Image Name:   Boot trap
   Image Type:   MIPS U-Boot Standalone Program (uncompressed)
   Data Size:    524 Bytes =  0.5 kB
   Load Address: a0600000
   Entry Point:  a0600000
   Verifying Checksum ... OK
OK
boot trap: got a control
boot trap: load a real kernel...
.......................
boot trap: boot a real kernel...
## Booting image at 88000000 ...
   Image Name:   OpenWrt Linux-3.10.14
   Image Type:   MIPS Linux Kernel Image (lzma compressed)
   Data Size:    1494179 Bytes =  1.4 MB
   Load Address: 80001000
   Entry Point:  80001000
   Verifying Checksum ... OK
   Uncompressing Kernel Image ... OK
No initrd
## Transferring control to Linux (at address 80001000) ...
## Giving linux memsize in MB, 256

Starting kernel ...

LINUX started...
</code>```

and for an mt7620-based board:

```<code>## Booting image at bc140000 ...
   Image Name:   Boot trap
   Image Type:   MIPS Linux Kernel Image (lzma compressed)
   Data Size:    345 Bytes =  0.3 kB
   Load Address: 80001000
   Entry Point:  80001000
   Verifying Checksum ... OK
   Uncompressing Kernel Image ... OK
No initrd
## Transferring control to Linux (at address 80001000) ...
## Giving linux memsize in MB, 256

Starting kernel ...
</code>```

As you can see, code in the 'boot trap' (as a linux u-boot image) got stuck, I have no JTAG debugger, so I can only guess that some exception happend and board stuck in an infinity loop inside that exception handler.

I see in u-boot sources for an mt7621-based board (I have them :)) such lines of code:

```<code>int do_bootm (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
...
    switch (hdr->ih_type) {
case IH_TYPE_STANDALONE:
    appl = (int (*)(int, char *[]))ntohl(hdr->ih_ep);
    (*appl)(argc-1, &argv[1]); // <--- pass a control to a standalone app
    return 0;
    ...

switch (hdr->ih_os) {
default:
case IH_OS_LINUX:
    do_bootm_linux  (cmdtp, flag, argc, argv,
             addr, len_ptr, verify);
    break;
    ...
</code>```

and next lines:

```<code>void do_bootm_linux (cmd_tbl_t * cmdtp, int flag, int argc, char *argv[],
         ulong addr, ulong * len_ptr, int verify)
{
    ...
    void (*theKernel) (int, char **, char **, int *);
    theKernel = (void (*)(int, char **, char **, int *)) ntohl (hdr->ih_ep);

    ...
    theKernel (linux_argc, linux_argv, linux_env, 0); // <--- pass a control to a linux kernel
}
</code>```

So the question is what's a difference between booting a linux kernel and a standalone app? Why linux has to setup a stack pointer after it gets a control (linux/arch/mips/kernel/head.S) if we have a valid C environment already? Why linux has to do so much work before it passes a control to itself first C function (in a standalone app we're able to place a C function code directly into an addres, u-boot passes control to)?

Why it's impossible to place a code in an address a u-boot passes a control to and just let it run as I made for standalone app?

答:
The Linux kernel is designed to run on thousands of different systems ranging from small embedded devices to large servers. It would not be practical to include the code for each possible architecture, board, or configuration in the kernel, so instead the kernel defines a set of boot requirements that must be met before it can run. It is normally the task of the boot loader to setup a proper environment and fulfil these requirements.

A "standalone application" in contrast is normally written for a specific target system (architecture, board, configuration) and takes care of setting up mostly everything by itself.

That's why u-boot handles both cases differently. If you are booting a Linux kernel, then u-boot sets everything up the way the kernel expects. If you are booting a standalone application, then it is assumed that the application will do whatever is needed.

Body:
I have a MIPS based board (MediaTek mt7620) with a proprietary and closed bootloader (u-boot) with cut off a lot of functionality, like booting a standalone application. (I'm not allowed to change/reflash this bootloader, 'cause a lot of customers use this board and if we were updating the bootloader and it failed we would faced with a lot of bricks :) (bootloader supports a boot over tftp protocol) )

I'm trying to change a boot sequence provided by a board manufacturer: ROM bootloader --> flash bootloader (u-boot) --> linux kernel to a: ROM bootloader --> flash bootloader (u-boot) --> boot trap --> linux kernel. For another board (mt7621) with a u-boot which supports a booting a standalone application I was able to create some boot trap u-boot image (standalone app) and put it into the flash instead of a linux kernel (I moved linux kernel down). (this boot trap makes some work, loads and boots the linux kernel by using a ranand_read/do_bootm functions provided by the u-boot via a jump table.

As I mentioned, a u-boot for an mt7620-based board doesn't support booting a standalone application, so I decided to create a boot trap as a u-boot linux image (not as a u-boot standalone app image) keeping code of boot trap almost the same (I changed only function signature: for a standalone app u-boot image 2 args get passed, for a linux u-boot image - 4; and load/entry addresses).

This is a log from a serial port,
   for an mt7621-based board:

## Booting image at bc140000 ...
   Image Name:   Boot trap
   Image Type:   MIPS U-Boot Standalone Program (uncompressed)
   Data Size:    524 Bytes =  0.5 kB
   Load Address: a0600000
   Entry Point:  a0600000
   Verifying Checksum ... OK
OK
boot trap: got a control
boot trap: load a real kernel...
.......................
boot trap: boot a real kernel...
## Booting image at 88000000 ...
   Image Name:   OpenWrt Linux-3.10.14
   Image Type:   MIPS Linux Kernel Image (lzma compressed)
   Data Size:    1494179 Bytes =  1.4 MB
   Load Address: 80001000
   Entry Point:  80001000
   Verifying Checksum ... OK
   Uncompressing Kernel Image ... OK
No initrd
## Transferring control to Linux (at address 80001000) ...
## Giving linux memsize in MB, 256

Starting kernel ...

LINUX started...

and for an mt7620-based board:

## Booting image at bc140000 ...
   Image Name:   Boot trap
   Image Type:   MIPS Linux Kernel Image (lzma compressed)
   Data Size:    345 Bytes =  0.3 kB
   Load Address: 80001000
   Entry Point:  80001000
   Verifying Checksum ... OK
   Uncompressing Kernel Image ... OK
No initrd
## Transferring control to Linux (at address 80001000) ...
## Giving linux memsize in MB, 256

Starting kernel ...

As you can see, code in the 'boot trap' (as a linux u-boot image) got stuck, I have no JTAG debugger, so I can only guess that some exception happend and board stuck in an infinity loop inside that exception handler.

I see in u-boot sources for an mt7621-based board (I have them :)) such lines of code:

int do_bootm (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
...
    switch (hdr->ih_type) {
case IH_TYPE_STANDALONE:
    appl = (int (*)(int, char *[]))ntohl(hdr->ih_ep);
    (*appl)(argc-1, &argv[1]); // <--- pass a control to a standalone app
    return 0;
    ...

switch (hdr->ih_os) {
default:
case IH_OS_LINUX:
    do_bootm_linux  (cmdtp, flag, argc, argv,
             addr, len_ptr, verify);
    break;
    ...

and next lines:

void do_bootm_linux (cmd_tbl_t * cmdtp, int flag, int argc, char *argv[],
         ulong addr, ulong * len_ptr, int verify)
{
    ...
    void (*theKernel) (int, char **, char **, int *);
    theKernel = (void (*)(int, char **, char **, int *)) ntohl (hdr->ih_ep);

    ...
    theKernel (linux_argc, linux_argv, linux_env, 0); // <--- pass a control to a linux kernel
}

So the question is what's a difference between booting a linux kernel and a standalone app? Why linux has to setup a stack pointer after it gets a control (linux/arch/mips/kernel/head.S) if we have a valid C environment already? Why linux has to do so much work before it passes a control to itself first C function (in a standalone app we're able to place a C function code directly into an addres, u-boot passes control to)?

Why it's impossible to place a code in an address a u-boot passes a control to and just let it run as I made for standalone app?


答:
```<code>condition ? (action to take if condition is true) : (action if false);
</code>```

The ternary operator isn't a full blown replacement for if/else. The two alternatives must be expressions, not statements. Better to think of it as:

```<code>condition ? (result if true) : (result if false)
</code>```

The result of the operator is a value which can then be used in a larger statement. To use it in a return statement you need to put the return up front.

```<code>return result == 8 ? true : false;
</code>```

Note that this is more simply written without the ternary operator.

```<code>return result == 8;
</code>```

Body:
I am trying to turn a simple if/else statement into a ternary for practice and I'm having trouble. From what I understand, the logic is:

condition ? (action to take if condition is true) : (action if false);

My condition is if(result == 8).

I've already tried:

result == 8 ? return true : return false;

and

result = 8 ? return true : return false;

Here's my code, the end of which I would like to convert

public boolean sum28(int[] nums) {

    int result = 0;
    for(int i=0; i<nums.length; i++) {
        if(nums[i] == 2) {
            result+=2;
        }
    }
    if(result == 8) {
        return true;
    }
    return false;
}

I'm getting a type mismatch: cannot convert from int to boolean when I use only 1 equals sign, and getting a invalid token "==" when using two.

Body:
condition ? (action to take if condition is true) : (action if false);

The ternary operator isn't a full blown replacement for if/else. The two alternatives must be expressions, not statements. Better to think of it as:

condition ? (result if true) : (result if false)

The result of the operator is a value which can then be used in a larger statement. To use it in a return statement you need to put the return up front.

return result == 8 ? true : false;

Note that this is more simply written without the ternary operator.

return result == 8;


问:
How to prevent PaginationComponent in Angular 2 event to work?
I'm using pagination component that comes from ngx-bootstrap/pagination. Like this:

```<code><pagination *ngIf="returnedArray"
    [totalItems]="contentArray.length"
    (pageChanged)="pageChanged($event)"
    [itemsPerPage]="1"
    [boundaryLinks]="false"></pagination>
</code>```

I want the pager to not navigate to the next page until some conditions are met, but can't find how to achieve that.

I tried several things:

Remove the (pageChanged)="pageChanged($event)" from the pagination component. But navigation is still firing.

Tried to make something like event.preventDefault() but it doesn't exist here

答:
The pageChange is an EventEmitter, so you can execute a function when the user changed the page using the paginator. So it already changed the page at that moment.

Looking at the source code of the pagination component on GitHub, I see there is a disabled Input-option.

Maybe you can do something like:

```<code><pagination *ngIf="returnedArray"
    [totalItems]="contentArray.length"
    (pageChanged)="pageChanged($event)"
    [disabled]="methodWithYourConditions()"
    [itemsPerPage]="1"
    [boundaryLinks]="false"></pagination>
</code>```

Then the function you're referring to in this disabled attribute, can check for multiple conditions.

Body:
I'm using pagination component that comes from ngx-bootstrap/pagination. Like this:

<pagination *ngIf="returnedArray"
    [totalItems]="contentArray.length"
    (pageChanged)="pageChanged($event)"
    [itemsPerPage]="1"
    [boundaryLinks]="false"></pagination>

I want the pager to not navigate to the next page until some conditions are met, but can't find how to achieve that.

I tried several things:

Remove the (pageChanged)="pageChanged($event)" from the pagination component. But navigation is still firing.

Tried to make something like event.preventDefault() but it doesn't exist here

Body:
The pageChange is an EventEmitter, so you can execute a function when the user changed the page using the paginator. So it already changed the page at that moment.

Looking at the source code of the pagination component on GitHub, I see there is a disabled Input-option.

Maybe you can do something like:

<pagination *ngIf="returnedArray"
    [totalItems]="contentArray.length"
    (pageChanged)="pageChanged($event)"
    [disabled]="methodWithYourConditions()"
    [itemsPerPage]="1"
    [boundaryLinks]="false"></pagination>

Then the function you're referring to in this disabled attribute, can check for multiple conditions.