问:
How can I collapse multiple columns and to generate new variables from the different levels/values that were collapsed?
I have a dataset (df) similar to this one:

```<code>df <- data.frame("ID"=c(1, 1, 1, 2, 2),
                 "Method of payment"=c("cash","liabilities",
                                       "shares", "cash", NA),
                 "USD"=c(110, 130, 200, 100, NA),
                 "var3"=c(1500, NA, NA, "ab", "bc"))
df
#   ID Method.of.payment USD var3
# 1  1              cash 110 1500
# 2  1       liabilities 130 <NA>
# 3  1            shares 200 <NA>
# 4  2              cash 100   ab
# 5  2              <NA>  NA   bc
</code>```

And I would like to have:

```<code>data.frame("ID"=c(1, 2),
           "Method of payment"=c("cash, liabilities, shares", "cash"),
           "Cash"=c(110, 100),
           "Liabilities"=c(130, 0),
           "Shares"=c(200, 0),
           "var3"=c(1500, "ab,bc"))

#   ID         Method.of.payment Cash Liabilities Shares  var3
# 1  1 cash, liabilities, shares  110         130    200  1500
# 2  2                      cash  100           0      0 ab,bc
</code>```

Therefore, I would like to

collapse the variables "method of payment" and "var3" in order to have only one row per ID, having all the levels/values linked to an ID pasted in one row;

generate new variables from existing levels of the factor variable method of payment ("cash", "liabilities", "shares") whose values should be the corresponding values of the variable USD or 0 if there is no corresponding value.

I am working with a very large dataset, so I am looking for something that works also on large data. I hope it is clear.

答:
Error message says

Keys are shared for 2 rows:
  * 6, 7

which can be seen in row 6 and 7 in the following output, i.e. Method is the same in row 6 and 7, so how spread will assign them to different column

```<code>df %>% group_by(ID) %>%
       mutate(MofP=paste(Method, collapse = ','),var3=paste(var3[!is.na(var3)], collapse = ','))

# A tibble: 7 x 5
# Groups:   ID [3]
     ID Method        USD var3  MofP
   <dbl> <fct>       <dbl> <chr> <chr>
1     1 cash          110 1500  cash,liabilities,shares
2     1 liabilities   130 1500  cash,liabilities,shares
3     1 shares        200 1500  cash,liabilities,shares
4     2 cash          100 ab,bc cash,NA
5     2 NA             NA ab,bc cash,NA
6     3 NA             NA 10    NA,NA
7     3 NA             NA 10    NA,NA
</code>```

To solve this we can do:

```<code>#Option 1. Select groups where Method is unique among the group, then do spread as usual
df %>% group_by(ID) %>%
       mutate(MofP=paste(Method, collapse = ','),var3=paste(var3[!is.na(var3)], collapse = ',')) %>%
       filter(n_distinct(Method)==n())

#Option 2. Follow dplyr erro msg Do you need to create unique ID with tibble::rowid_to_column()?,
#but create our own id
df %>% group_by(ID) %>% mutate(MofP=paste(Method, collapse = ','),var3=paste(var3[!is.na(var3)], collapse = ','),
                               rid=if(n_distinct(Method)!=n()) row_number() else 1) %>%
      spread(key=Method, value=USD, fill = 0)

# A tibble: 4 x 8
# Groups:   ID [3]
     ID var3  MofP                      rid  cash liabilities shares `<NA>`
   <dbl> <chr> <chr>                   <dbl> <dbl>       <dbl>  <dbl>  <dbl>
1     1 1500  cash,liabilities,shares     1   110         130    200      0
2     2 ab,bc cash,NA                     1   100           0      0      0
3     3 10    NA,NA                       1     0           0      0      0
4     3 10    NA,NA                       2     0           0      0      0
</code>```

Body:
I have a dataset (df) similar to this one:

df <- data.frame("ID"=c(1, 1, 1, 2, 2),
                 "Method of payment"=c("cash","liabilities",
                                       "shares", "cash", NA),
                 "USD"=c(110, 130, 200, 100, NA),
                 "var3"=c(1500, NA, NA, "ab", "bc"))
df
#   ID Method.of.payment USD var3
# 1  1              cash 110 1500
# 2  1       liabilities 130 <NA>
# 3  1            shares 200 <NA>
# 4  2              cash 100   ab
# 5  2              <NA>  NA   bc

And I would like to have:

data.frame("ID"=c(1, 2),
           "Method of payment"=c("cash, liabilities, shares", "cash"),
           "Cash"=c(110, 100),
           "Liabilities"=c(130, 0),
           "Shares"=c(200, 0),
           "var3"=c(1500, "ab,bc"))

#   ID         Method.of.payment Cash Liabilities Shares  var3
# 1  1 cash, liabilities, shares  110         130    200  1500
# 2  2                      cash  100           0      0 ab,bc

Therefore, I would like to

collapse the variables "method of payment" and "var3" in order to have only one row per ID, having all the levels/values linked to an ID pasted in one row;

generate new variables from existing levels of the factor variable method of payment ("cash", "liabilities", "shares") whose values should be the corresponding values of the variable USD or 0 if there is no corresponding value.

I am working with a very large dataset, so I am looking for something that works also on large data. I hope it is clear.

Body:
Error message says

Keys are shared for 2 rows:
  * 6, 7

which can be seen in row 6 and 7 in the following output, i.e. Method is the same in row 6 and 7, so how spread will assign them to different column

df %>% group_by(ID) %>%
       mutate(MofP=paste(Method, collapse = ','),var3=paste(var3[!is.na(var3)], collapse = ','))

# A tibble: 7 x 5
# Groups:   ID [3]
     ID Method        USD var3  MofP
   <dbl> <fct>       <dbl> <chr> <chr>
1     1 cash          110 1500  cash,liabilities,shares
2     1 liabilities   130 1500  cash,liabilities,shares
3     1 shares        200 1500  cash,liabilities,shares
4     2 cash          100 ab,bc cash,NA
5     2 NA             NA ab,bc cash,NA
6     3 NA             NA 10    NA,NA
7     3 NA             NA 10    NA,NA

To solve this we can do:

#Option 1. Select groups where Method is unique among the group, then do spread as usual
df %>% group_by(ID) %>%
       mutate(MofP=paste(Method, collapse = ','),var3=paste(var3[!is.na(var3)], collapse = ',')) %>%
       filter(n_distinct(Method)==n())

#Option 2. Follow dplyr erro msg Do you need to create unique ID with tibble::rowid_to_column()?,
#but create our own id
df %>% group_by(ID) %>% mutate(MofP=paste(Method, collapse = ','),var3=paste(var3[!is.na(var3)], collapse = ','),
                               rid=if(n_distinct(Method)!=n()) row_number() else 1) %>%
      spread(key=Method, value=USD, fill = 0)

# A tibble: 4 x 8
# Groups:   ID [3]
     ID var3  MofP                      rid  cash liabilities shares `<NA>`
   <dbl> <chr> <chr>                   <dbl> <dbl>       <dbl>  <dbl>  <dbl>
1     1 1500  cash,liabilities,shares     1   110         130    200      0
2     2 ab,bc cash,NA                     1   100           0      0      0
3     3 10    NA,NA                       1     0           0      0      0
4     3 10    NA,NA                       2     0           0      0      0


来源: stackexchange

问:
@Autowired @Service Bean is null although set up properly
I get this error during start of my Spring Boot 2.1.4 based application:

```<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [test.services.AlmConnectivity]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1295) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 22 common frames omitted
Caused by: java.lang.NullPointerException: null
    at test.services.AlmConnectivity.initProxyBean(AlmConnectivity.java:43) ~[classes/:na]
    at test.services.AlmConnectivity.<init>(AlmConnectivity.java:30) ~[classes/:na]
</code>```

The mentioned line 43 is the one that starts with proxy =:

```<code>@DependsOn({ "config", "cfg" })
private void initProxyBean() {
    System.err.println("Config: " + config);
    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));
}
</code>```

System.err prints null too. As you can see I tried to signal dependencies using @DependsOn.

These are the (I guess) other relevant parts of the class:

```<code>@Service
public class AlmConnectivity {
    Logger log = LoggerFactory.getLogger(AlmConnectivity.class);

    @Autowired
    @Qualifier("config")
    Config config;

    private Proxy proxy;

    private OkHttpClient client;

    public AlmConnectivity() {
        initProxyBean();
        initClientBean(proxy);
    }
</code>```

Because I prefer shorter names I used @Qualifier, but even if I skip this and take the bean with its full name config it doesn't work and config stays null.

This is the config class:

```<code>@Component
public class Config {

    @NotNull
    @NotEmpty
    @Value("${proxy.host}")
    private String proxyHost = "i.am.desparate";

    @NotNull
    @NotEmpty
    @Value("${proxy.port}")
    private int proxyPort = 8090;

    public String getProxyHost() {
        return proxyHost;
    }

    public int getProxyPort() {
        return proxyPort;
    }
}
</code>```

My main class carries these annotations:

```<code>@SpringBootApplication
@EnableScheduling
@Configuration
@ComponentScan
@EnableAutoConfiguration
</code>```

(The latter three were added during my attempts to get this running)

答:
You might want to change your behaviour from being called in the constructor to a

```<code>javax.annotation.PostConstruct
</code>```

annotated method:

```<code>@Service
public class AlmConnectivity {

    Logger log = LoggerFactory.getLogger(AlmConnectivity.class);

    @Autowired
    @Qualifier("config")
    Config config;

    private Proxy proxy;

    private OkHttpClient client;

    @PostConstruct
    private void initProxyBean() {
        System.err.println("Config: " + config);
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I get this error during start of my Spring Boot 2.1.4 based application:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [test.services.AlmConnectivity]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1295) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 22 common frames omitted
Caused by: java.lang.NullPointerException: null
    at test.services.AlmConnectivity.initProxyBean(AlmConnectivity.java:43) ~[classes/:na]
    at test.services.AlmConnectivity.<init>(AlmConnectivity.java:30) ~[classes/:na]

The mentioned line 43 is the one that starts with proxy =:

@DependsOn({ "config", "cfg" })
private void initProxyBean() {
    System.err.println("Config: " + config);
    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));
}

System.err prints null too. As you can see I tried to signal dependencies using @DependsOn.

These are the (I guess) other relevant parts of the class:

@Service
public class AlmConnectivity {
    Logger log = LoggerFactory.getLogger(AlmConnectivity.class);

    @Autowired
    @Qualifier("config")
    Config config;

    private Proxy proxy;

    private OkHttpClient client;

    public AlmConnectivity() {
        initProxyBean();
        initClientBean(proxy);
    }

Because I prefer shorter names I used @Qualifier, but even if I skip this and take the bean with its full name config it doesn't work and config stays null.

This is the config class:

@Component
public class Config {

    @NotNull
    @NotEmpty
    @Value("${proxy.host}")
    private String proxyHost = "i.am.desparate";

    @NotNull
    @NotEmpty
    @Value("${proxy.port}")
    private int proxyPort = 8090;

    public String getProxyHost() {
        return proxyHost;
    }

    public int getProxyPort() {
        return proxyPort;
    }
}

My main class carries these annotations:

@SpringBootApplication
@EnableScheduling
@Configuration
@ComponentScan
@EnableAutoConfiguration

(The latter three were added during my attempts to get this running)

Body:
You might want to change your behaviour from being called in the constructor to a

javax.annotation.PostConstruct

annotated method:

@Service
public class AlmConnectivity {

    Logger log = LoggerFactory.getLogger(AlmConnectivity.class);

    @Autowired
    @Qualifier("config")
    Config config;

    private Proxy proxy;

    private OkHttpClient client;

    @PostConstruct
    private void initProxyBean() {
        System.err.println("Config: " + config);
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));
    }
}


问:
How to apply an existing sonarQube rule for only given class type
Please help me to solve these problems. Simply I want to apply an existing sonarqube rule for only certain type of classes. As far as I know, we can use class tree to get the classes and identify the target class. The thing I want t know is how can I enable or disable existing sonar rule within a custom rule?.

The next question is to identify the base class which is child class is extended. As an example class A extend class B, B extend class C and now I want to identify all the classes that is extended from the class C(The base class).

Even a small guide, link, tip will be really appreciate.

答:
I think you canot disable existing rule from default java plugin within your custom plugin. You could disable the rule in your profile and replace the default rule with custom one. (Actually there may be way with creating custom issue filter in your plugin )

The rule is  implemented like this.

@Rule(key = "S1948")
    public class SerializableFieldInSerializableClassCheck extends IssuableSubscriptionVisitor

```<code> public List<Tree.Kind> nodesToVisit() {
    return ImmutableList.of(Tree.Kind.CLASS);
  }

  public void visitNode(Tree tree) {
    if(!hasSemantic()) {
      return;
    }
   ... rule logic
  }
</code>```

just copy (and change the rule key and etc.)  the existing rule into your custom plugin and add a check for class supertype

```<code>if(!classTree.symbol().type().isSubtypeOf("your.supertype.C")) || !hasSemantic()) {
  return;
}
</code>```

Body:
I think you canot disable existing rule from default java plugin within your custom plugin. You could disable the rule in your profile and replace the default rule with custom one. (Actually there may be way with creating custom issue filter in your plugin )

The rule is  implemented like this.

@Rule(key = "S1948")
    public class SerializableFieldInSerializableClassCheck extends IssuableSubscriptionVisitor

 public List<Tree.Kind> nodesToVisit() {
    return ImmutableList.of(Tree.Kind.CLASS);
  }

  public void visitNode(Tree tree) {
    if(!hasSemantic()) {
      return;
    }
   ... rule logic
  }

just copy (and change the rule key and etc.)  the existing rule into your custom plugin and add a check for class supertype

if(!classTree.symbol().type().isSubtypeOf("your.supertype.C")) || !hasSemantic()) {
  return;
}


问:
How to group text being typed into an array and wrap every 20 chars in a div
I am attempting to wrap every 20 chars in a new div container.  I keep getting undefined I assume from the array results that do not exist yet.  How can I wrap every 20 chars as the user types and reaches char 20, 40, 60,and 80 and place it into a div container with the max allowed chars being 80, and is there a better way of doing this than writing out the array groups manually by 20's.

function creaeTextField(clicked_id) {
  var dropArea = document.getElementById('headarea');
  var myArea = document.createElement('div');
  var myAreaOuter = document.createElement('div');

  myArea.className = "areaClass";
  myAreaOuter.className = "areaClassOuter";

  myArea.id = "areaClass";
  myAreaOuter.id = "areaClassOuter";

  myArea.contentEditable = "true";

  if (clicked_id == 'text') {
    myAreaOuter.appendChild(myArea);
    dropArea.appendChild(myAreaOuter);

    myArea.addEventListener("keydown", findLimitb);
    myArea.addEventListener("keyup", findLimitb);

    var style = window.getComputedStyle(myArea, null).getPropertyValue('font-size');
    var fontSize = parseFloat(style);

    function findLimitb() {
      if (myArea.offsetHeight <= fontSize * 4) {
        myArea.addEventListener("keydown", breaker);
      } else {
        if (event.keyCode === 8 || event.keyCode === 46 || event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) {
          myArea.focus();
        } else {
          myArea.removeEventListener("keydown", breaker);
          event.preventDefault();
          myArea.style.height = fontSize * 4 + "px";
        }
      }
    }

    function breaker() {
      var myAr = myArea.innerHTML.split("");
      var divCon = document.createElement('div');
      myArea.appendChild(divCon);
      if (myArea.innerHTML.length > 20) {
        divCon.innerHTML = myAr[0] + myAr[1] + myAr[2] + myAr[3] + myAr[4] + myAr[5] + myAr[6] + myAr[7] + myAr[8] + myAr[9] + myAr[10] + myAr[11] + myAr[12] + myAr[13] + myAr[14] + myAr[15] + myAr[16] + myAr[17] + myAr[18] + myAr[19] + myAr[20];
      }
    }

  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.headarea {
  width: 100%;
  height: 130px;
  float: left;
}

.buttonStyle {
  width: 60px;
  height: 25px;
  float: left;
}

.areaClassOuter {
  float: left;
  padding: 10px;
  position: relative;
  z-index: 29;
  border: 1px #000000 solid;
}

.areaClass {
  min-width: 100px;
  max-width: 310px;
  min-height: 60px;
  max-height: 100px;
  float: left;
  padding: 7px;
  position: relative;
  z-index: 30;
  border: 1px #000000 solid;
  overflow: hidden;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 24pt;
  text-align: center;
}</code>```

<button class="buttonStyle" id="text" type="button" onclick="creaeTextField(this.id)"></button>```

答:
You could just listen for the keydown-event like you did in your question and then work with substring to get and remove the first part of the string. The first part can then be appended to an container and the rest of the string (in most cases only 1 char) can be set as content of the input-element.

you should also consider using textContent instead of innerHtml, so that the user is able input safely characters that are used by html.

let textOutput = document.getElementById('textOutput');
let textInput = document.getElementById('textInput');
let maxInputLength = 20;
let maxOutputElement = 4; // 4*20 = 80 Chars

textInput.addEventListener('keydown', function(event) {
  if (textOutput.children.length >= maxOutputElement) {
    event.preventDefault();
    textInput.textContent = '';
  }
  let textChanged = false;
  let text = textInput.textContent;
  while (text.length >= maxInputLength) {
    let firstPart = text.substring(0, maxInputLength);
    let textElement = document.createElement('div');
    textElement.textContent = firstPart;
    textElement.contentEditable = true;
    textElement.addEventListener('keyup', function(event) {
      let editText = event.currentTarget.textContent;
      if (editText.length >= maxInputLength) {
        event.currentTarget.textContent = editText.substring(0, maxInputLength);
      }
    });
    textOutput.appendChild(textElement);
    text = text.substring(maxInputLength);
    textChanged = true;
  }
  if (textChanged) textInput.textContent = text;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#textOutput div {
  display: inline-block;
  margin: 5px;
  background-color: #EEE;
}

#textInput {
  display: block;
  width: 160px;
  height: 20px;
  background: #EEE;
  border: 1px dashed #CCC;
}</code>```

```

Body:
I am attempting to wrap every 20 chars in a new div container.  I keep getting undefined I assume from the array results that do not exist yet.  How can I wrap every 20 chars as the user types and reaches char 20, 40, 60,and 80 and place it into a div container with the max allowed chars being 80, and is there a better way of doing this than writing out the array groups manually by 20's.

function creaeTextField(clicked_id) {
  var dropArea = document.getElementById('headarea');
  var myArea = document.createElement('div');
  var myAreaOuter = document.createElement('div');

  myArea.className = "areaClass";
  myAreaOuter.className = "areaClassOuter";

  myArea.id = "areaClass";
  myAreaOuter.id = "areaClassOuter";

  myArea.contentEditable = "true";

  if (clicked_id == 'text') {
    myAreaOuter.appendChild(myArea);
    dropArea.appendChild(myAreaOuter);

    myArea.addEventListener("keydown", findLimitb);
    myArea.addEventListener("keyup", findLimitb);

    var style = window.getComputedStyle(myArea, null).getPropertyValue('font-size');
    var fontSize = parseFloat(style);

    function findLimitb() {
      if (myArea.offsetHeight <= fontSize * 4) {
        myArea.addEventListener("keydown", breaker);
      } else {
        if (event.keyCode === 8 || event.keyCode === 46 || event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40) {
          myArea.focus();
        } else {
          myArea.removeEventListener("keydown", breaker);
          event.preventDefault();
          myArea.style.height = fontSize * 4 + "px";
        }
      }
    }

    function breaker() {
      var myAr = myArea.innerHTML.split("");
      var divCon = document.createElement('div');
      myArea.appendChild(divCon);
      if (myArea.innerHTML.length > 20) {
        divCon.innerHTML = myAr[0] + myAr[1] + myAr[2] + myAr[3] + myAr[4] + myAr[5] + myAr[6] + myAr[7] + myAr[8] + myAr[9] + myAr[10] + myAr[11] + myAr[12] + myAr[13] + myAr[14] + myAr[15] + myAr[16] + myAr[17] + myAr[18] + myAr[19] + myAr[20];
      }
    }

  }
}

.headarea {
  width: 100%;
  height: 130px;
  float: left;
}

.buttonStyle {
  width: 60px;
  height: 25px;
  float: left;
}

.areaClassOuter {
  float: left;
  padding: 10px;
  position: relative;
  z-index: 29;
  border: 1px #000000 solid;
}

.areaClass {
  min-width: 100px;
  max-width: 310px;
  min-height: 60px;
  max-height: 100px;
  float: left;
  padding: 7px;
  position: relative;
  z-index: 30;
  border: 1px #000000 solid;
  overflow: hidden;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 24pt;
  text-align: center;
}

<button class="buttonStyle" id="text" type="button" onclick="creaeTextField(this.id)"></button>

Body:
You could just listen for the keydown-event like you did in your question and then work with substring to get and remove the first part of the string. The first part can then be appended to an container and the rest of the string (in most cases only 1 char) can be set as content of the input-element.

you should also consider using textContent instead of innerHtml, so that the user is able input safely characters that are used by html.

let textOutput = document.getElementById('textOutput');
let textInput = document.getElementById('textInput');
let maxInputLength = 20;
let maxOutputElement = 4; // 4*20 = 80 Chars

textInput.addEventListener('keydown', function(event) {
  if (textOutput.children.length >= maxOutputElement) {
    event.preventDefault();
    textInput.textContent = '';
  }
  let textChanged = false;
  let text = textInput.textContent;
  while (text.length >= maxInputLength) {
    let firstPart = text.substring(0, maxInputLength);
    let textElement = document.createElement('div');
    textElement.textContent = firstPart;
    textElement.contentEditable = true;
    textElement.addEventListener('keyup', function(event) {
      let editText = event.currentTarget.textContent;
      if (editText.length >= maxInputLength) {
        event.currentTarget.textContent = editText.substring(0, maxInputLength);
      }
    });
    textOutput.appendChild(textElement);
    text = text.substring(maxInputLength);
    textChanged = true;
  }
  if (textChanged) textInput.textContent = text;
});

#textOutput div {
  display: inline-block;
  margin: 5px;
  background-color: #EEE;
}

#textInput {
  display: block;
  width: 160px;
  height: 20px;
  background: #EEE;
  border: 1px dashed #CCC;
}

<div id="textOutput"></div>
<div id="textInput" contenteditable="true"></div>


问:
Adapting code from one-sided p-values to two sided
I have some code from Rapach, Strauss and Zhou (2013), Journal of finance.

It computes bootstrapping p-values for one-sided hypothesis tests,

```<code>H0: B=0 against H1: B>0
</code>```

Is it possible for me to adapt this code to compute the hypothesis test:

```<code>H0: B=0 against H1: B\=0
</code>```

```<code>%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Computing statistics for wild bootstrapped pseudo samples
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

stats_boot=zeros(N+1,N,B);
for b=1:B;
    for j=1:N;
        [results_j_star,R_squared_j_star]=...
            Estimate_Granger_pairwise_GMM(Y_star(:,:,b),...
            Y_star(:,:,b),X_1_star(:,:,b),X_2_star(:,:,b),j);
        for i=1:(N-1);
            if j==1;
                stats_boot(i+1,j,b)=results_j_star(i,2);
            else
                if i<j;
                    stats_boot(i,j,b)=results_j_star(i,2);
                else
                    stats_boot(i+1,j,b)=results_j_star(i,2);
                end;
            end;
        end;
        stats_boot(N+1,j,b)=results_j_star(end,2);
        disp([b j]);
    end;
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Computing wild bootstrapped p-values
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for j=1:N;
    for i=1:N+1;
        stats_boot_i_j=stats_boot(i,j,:);
        stats_p_i_j=stats_boot_i_j>results_all(2,j,i);
        results_all(3,j,i)=sum(stats_p_i_j)/B;
    end;
end;
</code>```

答:
I believe the original answer is incorrect.

If we think of the hypothesis test for a two-tailed is:

```<code>H0: b=0, HA:b\=0
</code>```

Then the above answer only tells us when the t does not equal the critical value, which will be basically all the time.

But think about a t-test,

A two-tailed should be,

```<code>Reject H0 is |t|>t_(alpha/2)
</code>```

So the OP needs to change the code to account for this.

This should be a comment not an answer but I have rep less than 50!

Body:
I have some code from Rapach, Strauss and Zhou (2013), Journal of finance.

It computes bootstrapping p-values for one-sided hypothesis tests,

H0: B=0 against H1: B>0

Is it possible for me to adapt this code to compute the hypothesis test:

H0: B=0 against H1: B\=0

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Computing statistics for wild bootstrapped pseudo samples
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

stats_boot=zeros(N+1,N,B);
for b=1:B;
    for j=1:N;
        [results_j_star,R_squared_j_star]=...
            Estimate_Granger_pairwise_GMM(Y_star(:,:,b),...
            Y_star(:,:,b),X_1_star(:,:,b),X_2_star(:,:,b),j);
        for i=1:(N-1);
            if j==1;
                stats_boot(i+1,j,b)=results_j_star(i,2);
            else
                if i<j;
                    stats_boot(i,j,b)=results_j_star(i,2);
                else
                    stats_boot(i+1,j,b)=results_j_star(i,2);
                end;
            end;
        end;
        stats_boot(N+1,j,b)=results_j_star(end,2);
        disp([b j]);
    end;
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Computing wild bootstrapped p-values
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for j=1:N;
    for i=1:N+1;
        stats_boot_i_j=stats_boot(i,j,:);
        stats_p_i_j=stats_boot_i_j>results_all(2,j,i);
        results_all(3,j,i)=sum(stats_p_i_j)/B;
    end;
end;

Body:
I believe the original answer is incorrect.

If we think of the hypothesis test for a two-tailed is:

H0: b=0, HA:b\=0

Then the above answer only tells us when the t does not equal the critical value, which will be basically all the time.

But think about a t-test,

A two-tailed should be,

Reject H0 is |t|>t_(alpha/2)

So the OP needs to change the code to account for this.

This should be a comment not an answer but I have rep less than 50!


问:
Why is a named rvalue reference an lvalue expression?
I know that a named reference is an lvalue:

```<code>int x = 1;
int& ref1 = x;
int&& ref2 = std::move(x);
</code>```

I've read the explanation — that is because we can take the address of those ref1 and ref2.

But when we take the address of a reference we actually take the address of the referenced object, don't we? So this explanation doesn't seem to be correct.

So why a named reference is an lvalue?

答:
Here is an explanation from Scott Meyers's book "Effective Modern C++":

In fact, T&& has two different meanings. One is rvalue reference, of course. Such references behave exactly the way you expect: they bind only to rvalues, and their primary raison d’être is to identify objects that may be moved from.

```<code>void f(Widget&& param); // rvalue reference

Widget&& var1 = Widget(); // rvalue reference

auto&& var2 = var1; // not rvalue reference

template<typename T>
void f(std::vector<T>&& param); // rvalue reference

template<typename T>
void f(T&& param); // not rvalue reference
</code>```

The other meaning for T&& is either rvalue reference or lvalue reference. Such references look like rvalue references in the source code (i.e., T&&), but they can behave as if they were lvalue references (i.e., T&). Their dual nature permits them to bind to rvalues (like rvalue references) as well as lvalues (like lvalue references). Furthermore, they can bind to const or non-const objects, to volatile or non-volatile objects, even to objects that are both const and volatile. They can bind to virtually anything. Such unprecedentedly flexible references deserve a name of their own. I call them universal references.

Body:
I know that a named reference is an lvalue:

int x = 1;
int& ref1 = x;
int&& ref2 = std::move(x);

I've read the explanation — that is because we can take the address of those ref1 and ref2.

But when we take the address of a reference we actually take the address of the referenced object, don't we? So this explanation doesn't seem to be correct.

So why a named reference is an lvalue?

Body:
Here is an explanation from Scott Meyers's book "Effective Modern C++":

In fact, T&& has two different meanings. One is rvalue reference, of course. Such references behave exactly the way you expect: they bind only to rvalues, and their primary raison d’être is to identify objects that may be moved from.

void f(Widget&& param); // rvalue reference

Widget&& var1 = Widget(); // rvalue reference

auto&& var2 = var1; // not rvalue reference

template<typename T>
void f(std::vector<T>&& param); // rvalue reference

template<typename T>
void f(T&& param); // not rvalue reference

The other meaning for T&& is either rvalue reference or lvalue reference. Such references look like rvalue references in the source code (i.e., T&&), but they can behave as if they were lvalue references (i.e., T&). Their dual nature permits them to bind to rvalues (like rvalue references) as well as lvalues (like lvalue references). Furthermore, they can bind to const or non-const objects, to volatile or non-volatile objects, even to objects that are both const and volatile. They can bind to virtually anything. Such unprecedentedly flexible references deserve a name of their own. I call them universal references.


答:
Per [expr.prim.id.unqual] (8.1.4.1 Unqualified names):

[...] The expression is an lvalue if the entity is a function,
  variable, or data member and a prvalue otherwise; it is a bit-field if
  the identifier designates a bit-field ([dcl.struct.bind]).

Per [basic]/6:

A variable is introduced by the declaration of a reference other
  than a non-static data member or of an object. The variable's name, if
  any, denotes the reference or object.

The declaration

```<code>int&& ref2 = std::move(x);
</code>```

is a "declaration of a reference other than a non-static data member." Therefore, the entity denoted by ref2 is a variable. So the expression ref2 is an lvalue.

Title: Why is a named rvalue reference an lvalue expression?

Body:
Per [expr.prim.id.unqual] (8.1.4.1 Unqualified names):

[...] The expression is an lvalue if the entity is a function,
  variable, or data member and a prvalue otherwise; it is a bit-field if
  the identifier designates a bit-field ([dcl.struct.bind]).

Per [basic]/6:

A variable is introduced by the declaration of a reference other
  than a non-static data member or of an object. The variable's name, if
  any, denotes the reference or object.

The declaration

int&& ref2 = std::move(x);

is a "declaration of a reference other than a non-static data member." Therefore, the entity denoted by ref2 is a variable. So the expression ref2 is an lvalue.


问:
Can i send java object in a json response
For example i have java class post:

```<code>public class Post{
String title;
String text;
}
</code>```

If i create an instance of this class and convert it into ajax response in my servlet controller

```<code>@RestController
public class AjaxNewsController {
 @JsonView(Views.Public.class)
    @PostMapping(value = "/getPost")
    public AjaxResponseBody getSearchResultViaAjax(@RequestBody AjaxPostResponse postId) {
        AjaxResponseBody result = new AjaxResponseBody();
        result.setCode("200");
        result.setMsg("found POST");
        result.setResult(post);
        return result;

    }
}
</code>```

My question is: can i retrieve post fields title and text with javascript on a client side and if i can then how?

Here is an example of console with my response in browse
console

but how can i extract my post with fields in ajax and jquery?

UPD

after some reaserach i found that somehow my serlvet doesn't convert my java pojo into json. How should i do it?

UPD2

my request sends normaly but serlvet doesn't convert POST class into json.

here is my javascript :

```<code>function likePost(postId,ratingElem, ratingChange) {

    var search = {}
    search["postId"] = postId;
    search["rating"] = ratingChange;

    $.ajax({
        type : "POST",
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        url : "likePost",
        data : JSON.stringify(search),
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);
            changeRating(ratingElem,data.post.getTopic());
        },
        error : function(e) {
            console.log("ERROR: ", e);
            changeRating(ratingElem,'error');
        },
        done : function(e) {
            console.log("DONE");
            enableSearchButton(true);
        }
    });

}
</code>```

status and message is fine but result is empty.

答:
try it:

```<code>var req = new XMLHttpRequest();
req.open('POST', 'your_url', false);
req.send(null);
if(req.status == 200)
dump(req.responseText);
</code>```

and if you want to get data from another domain please read cors

Body:
For example i have java class post:

public class Post{
String title;
String text;
}

If i create an instance of this class and convert it into ajax response in my servlet controller

@RestController
public class AjaxNewsController {
 @JsonView(Views.Public.class)
    @PostMapping(value = "/getPost")
    public AjaxResponseBody getSearchResultViaAjax(@RequestBody AjaxPostResponse postId) {
        AjaxResponseBody result = new AjaxResponseBody();
        result.setCode("200");
        result.setMsg("found POST");
        result.setResult(post);
        return result;

    }
}

My question is: can i retrieve post fields title and text with javascript on a client side and if i can then how?

Here is an example of console with my response in browse
console

but how can i extract my post with fields in ajax and jquery?

UPD

after some reaserach i found that somehow my serlvet doesn't convert my java pojo into json. How should i do it?

UPD2

my request sends normaly but serlvet doesn't convert POST class into json.

here is my javascript :

function likePost(postId,ratingElem, ratingChange) {

    var search = {}
    search["postId"] = postId;
    search["rating"] = ratingChange;

    $.ajax({
        type : "POST",
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        url : "likePost",
        data : JSON.stringify(search),
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);
            changeRating(ratingElem,data.post.getTopic());
        },
        error : function(e) {
            console.log("ERROR: ", e);
            changeRating(ratingElem,'error');
        },
        done : function(e) {
            console.log("DONE");
            enableSearchButton(true);
        }
    });

}

status and message is fine but result is empty.

Body:
try it:

var req = new XMLHttpRequest();
req.open('POST', 'your_url', false);
req.send(null);
if(req.status == 200)
dump(req.responseText);

and if you want to get data from another domain please read cors


问:
API endpoint to check latest .NET Core SDK version
I'm about to write a script to remove all .NET Core SDKs, except the latest one, from the local machine , thus I was curious whether there is any RESTful API endpoint which I could call to check the latest .NET Core SDK version available

答: The .NET Github repo contains the list of all releases. Probably you can use the Github's get-latest-release API to obtain the info </p>


问:
Detecting whether or not text is English (in bulk)
I'm looking for a simple way to detect whether a short excerpt of text, a few sentences, is English or not. Seems to me that this problem is much easier than trying to detect an arbitrary language. Is there any software out there that can do this? I'm writing in python, and would prefer a python library, but something else would be fine too. I've tried google, but then realized the TOS didn't allow automated queries.</p>

答:
Google Translate API v2 allows automated queries but it requires the use of an API key that you can freely get at Google APIs console.

To detect whether text is English you could use detect_language_v2() function (that uses that API) from my answer to the question Python - can I detect unicode string language code?:

```<code> if all(lang == 'en' for lang in detect_language_v2(['some text', 'more text'])):
    # all text fragments are in English
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Google Translate API v2 allows automated queries but it requires the use of an API key that you can freely get at Google APIs console.

To detect whether text is English you could use detect_language_v2() function (that uses that API) from my answer to the question Python - can I detect unicode string language code?:

 if all(lang == 'en' for lang in detect_language_v2(['some text', 'more text'])):
    # all text fragments are in English

ContentLicense: CC BY-SA 3.0


问:
SQL server Exception failed when converting the nvarchar value '2018-10-03' to data type int
Getting error while executing SQL query in java
"SQL server Exception :com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value '2018-10-03' to data type int"

SQL query

```<code>String MemberId = “103113213”;
String StartDate = ”2019-05-20”;

    select distinct BLRC_CREATE_DTM,BLRC_AMT
    FROM CMC_BLRC_BILL_RCPT D,CMC_SBSB_SUBSC A,CMC_GRGR_GROUP C,CDS_INID_INVOICE B
WHERE A.GRGR_CK = C.GRGR_CK
AND A.SBSB_CK = B.SBSB_CK
AND B.BLEI_CK = D.BLEI_CK
AND A.SBSB_ID IN ('"+MemberId+"')
AND FORMAT(BLRC_CREATE_DTM, 'yyyy-MM-dd') ="+StartDate+"";
</code>```

答:
```<code>String MemberId = “103113213”;
String StartDate = ”2019-05-20”;

    select distinct BLRC_CREATE_DTM,BLRC_AMT
    FROM CMC_BLRC_BILL_RCPT D,CMC_SBSB_SUBSC A,CMC_GRGR_GROUP C,CDS_INID_INVOICE B
WHERE A.GRGR_CK = C.GRGR_CK
AND A.SBSB_CK = B.SBSB_CK
AND B.BLEI_CK = D.BLEI_CK
AND A.SBSB_ID IN ('"+MemberId+"')
AND FORMAT(BLRC_CREATE_DTM, 'yyyy-MM-dd') = CONVERT(date, StartDate);
</code>```

Please make sure you are provide input just date and saving date as well.

Body:
Getting error while executing SQL query in java
"SQL server Exception :com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value '2018-10-03' to data type int"

SQL query

String MemberId = “103113213”;
String StartDate = ”2019-05-20”;

    select distinct BLRC_CREATE_DTM,BLRC_AMT
    FROM CMC_BLRC_BILL_RCPT D,CMC_SBSB_SUBSC A,CMC_GRGR_GROUP C,CDS_INID_INVOICE B
WHERE A.GRGR_CK = C.GRGR_CK
AND A.SBSB_CK = B.SBSB_CK
AND B.BLEI_CK = D.BLEI_CK
AND A.SBSB_ID IN ('"+MemberId+"')
AND FORMAT(BLRC_CREATE_DTM, 'yyyy-MM-dd') ="+StartDate+"";

Body:
String MemberId = “103113213”;
String StartDate = ”2019-05-20”;

    select distinct BLRC_CREATE_DTM,BLRC_AMT
    FROM CMC_BLRC_BILL_RCPT D,CMC_SBSB_SUBSC A,CMC_GRGR_GROUP C,CDS_INID_INVOICE B
WHERE A.GRGR_CK = C.GRGR_CK
AND A.SBSB_CK = B.SBSB_CK
AND B.BLEI_CK = D.BLEI_CK
AND A.SBSB_ID IN ('"+MemberId+"')
AND FORMAT(BLRC_CREATE_DTM, 'yyyy-MM-dd') = CONVERT(date, StartDate);

Please make sure you are provide input just date and saving date as well.


问:
Build flat array from tree array in node js
I have the same array with unlimited level, it's not limited to three levels - it's n level array.

Last parent_id = null;

Input Array:

```<code>{
  parent_id: {
    parent_id: {
      parent_id: null,
      _id: 5cdfcc1fb214df2da06bd0dc,
      title: 'Home & Kitchen'
    },
    _id: 5cdfcc45b214df2da06bd0dd,
    title: 'Furniture'
  },
  _id: 5cdfcc74b214df2da06bd0de,
  title: 'Sofas'
}
</code>```

Expected Output Array:

```<code>[
  {
      _id: 5cdfcc74b214df2da06bd0de,
      title: 'Sofas'
  },
  {
      _id: 5cdfcc45b214df2da06bd0dd,
      title: 'Furniture'
  },
  {
      _id: 5cdfcc1fb214df2da06bd0dc,
      title: 'Home & Kitchen'
  }
]
</code>```

答:
function getResult(input) {
  const result = [];
  let curr = input;
  while(curr){
     result.push({
         _id: curr._id,
         title: curr.title
     });
     curr = curr.parent_id; // if there is no parent_id inside, cycle will stop
  }
  return result;
}

let testInput = {
  parent_id: {
    parent_id: {
      parent_id: null,
      _id: '5cdfcc1fb214df2da06bd0dc',
      title: 'Home & Kitchen'
    },
    _id: '5cdfcc45b214df2da06bd0dd',
    title: 'Furniture'
  },
  _id: '5cdfcc74b214df2da06bd0de',
  title: 'Sofas'
};

console.log(getResult(testInput));```

Body:
I have the same array with unlimited level, it's not limited to three levels - it's n level array.

Last parent_id = null;

Input Array:

{
  parent_id: {
    parent_id: {
      parent_id: null,
      _id: 5cdfcc1fb214df2da06bd0dc,
      title: 'Home & Kitchen'
    },
    _id: 5cdfcc45b214df2da06bd0dd,
    title: 'Furniture'
  },
  _id: 5cdfcc74b214df2da06bd0de,
  title: 'Sofas'
}

Expected Output Array:

[
  {
      _id: 5cdfcc74b214df2da06bd0de,
      title: 'Sofas'
  },
  {
      _id: 5cdfcc45b214df2da06bd0dd,
      title: 'Furniture'
  },
  {
      _id: 5cdfcc1fb214df2da06bd0dc,
      title: 'Home & Kitchen'
  }
]


问:
Correct way to format input and output of TimeField in Django Rest Famework?
models.py

```<code>class DemoA(models.Model):
    my_time = models.TimeField()
</code>```

serializers.py

```<code>class DemoASerializer(serializer.ModelSerializer):
    class Meta:
        model = DemoA
        fields = ('my_time', )
</code>```

By default, for my_time field, it gives the format as 10:30:00, (%H:%M:%S). What is want is the serialized format as 10:30, (%H:%M).

Is there any default way to specify format for such cases, like specifying extra_kwargs in serializer Meta?

答:
You can specify how the field should format the data by specifying a TimeField [drf-doc] (this is not the TimeField [Django-doc] of the Django model):

```<code>class DemoASerializer(serializers.ModelSerializer):

    <b>my_time = serializers.TimeField(format='%H:%M')</b>

    class Meta:
        model = DemoA
        fields = ('my_time', )</code>```

or with extra_kwargs [drf-doc]:

```<code>class DemoASerializer(serializers.ModelSerializer):

    class Meta:
        model = DemoA
        fields = ('my_time', )
        extra_kwargs = {<b>'my_time': {'format': '%H:%M'}</b>}</code>```

Body:
models.py

class DemoA(models.Model):
    my_time = models.TimeField()

serializers.py

class DemoASerializer(serializer.ModelSerializer):
    class Meta:
        model = DemoA
        fields = ('my_time', )

By default, for my_time field, it gives the format as 10:30:00, (%H:%M:%S). What is want is the serialized format as 10:30, (%H:%M).

Is there any default way to specify format for such cases, like specifying extra_kwargs in serializer Meta?

Body:
You can specify how the field should format the data by specifying a TimeField [drf-doc] (this is not the TimeField [Django-doc] of the Django model):

class DemoASerializer(serializers.ModelSerializer):

    my_time = serializers.TimeField(format='%H:%M')

    class Meta:
        model = DemoA
        fields = ('my_time', )

or with extra_kwargs [drf-doc]:

class DemoASerializer(serializers.ModelSerializer):

    class Meta:
        model = DemoA
        fields = ('my_time', )
        extra_kwargs = {'my_time': {'format': '%H:%M'}}


问:
How to list docker image repositories using registry http api v2?
I am trying to fetch the list of repositry inside a docker registry using api version 2.

My target is to fetch the repositories from docker hub which is owned by me.

First I used basic authentication to get bearer token from authentication server "https://auth.docker.io/token?service=registry.docker.io"

Then i made a call to get the list of repo using this bearer token "https://index.docker.io/v2/_catalog" . But i am getting unauthorised error. Any idea whay could be the reason.

答:
Went thru the GOLang code and found the API follows RFC 2616 section 14.8. The security uses HTTP Authorization header with 'Basic' authentication token.

Example using PowerShell to list repostories.

Use docker CLI to make the credentials

docker login --username myuseraccount --password secretpassword

cat ([IO.Path]::Combine($env:USERPROFILE,  '.docker\config.json'))

Copy the basic token from the config.json to clipboard.

List Your Azure respositories. The space between Basic and base64 encoded token is needed.

Invoke-RestMethod -Uri https://YOURAZUREREGISTY.azurecr.io/v2/_catalog -Method Get -Headers @{'Authorization'='Basic PASTEBASE64BASICTOKENFROM2'}


问:
Transform Dataframe
I would like to reformat a generated dataframe so that I can add more information afterwards.

So lets say I have this df:

```<code>testdf <- data.frame(replicate(5,sample(1:50,5,rep=TRUE)))
testdf

  X1 X2 X3 X4 X5
1 38 20 47 43 39
2 25 27 25 45  9
3  9  1 44 12  8
4 48 19 21 46 13
5 26 50 26 35 38
</code>```

With an additional column at the beginning:

```<code>new_column = c(100, 101, 102, 103, 104)
finaldf <- cbind(new_column, testdf)
colnames(finaldf) <- c("ID", "Article1", "Article2", "Article3", "Article4", "Article5")
finaldf

   ID Article1 Article2 Article3 Article4 Article5
1 100       34       22       23       22       19
2 101       43       19       43       14       11
3 102       32       40        5       12        9
4 103       37        5       37       15        2
5 104       41       19       30       42       49
</code>```

Now I would like to transform this df in something like this:

```<code>   ID Article
  100       34
  100       22
  100       23
  100       22
  100       19
  101       43
  101       19
  101       43
  101       14
  101       11
  102       32
  102       40
  102        5
  102       12
  102        9
  103       37
  103        5
  103       37
  103       15
  103        2
  104       41
  104       19
  104       30
  104       42
  104       49
</code>```

Does anyone know how I can solve this elegantly?

答:
You can reshape from wide to long like this:

```<code>longdf <- reshape(finaldf, varying = c(2:6), direction = "long", idvar = "ID", sep = "", timevar = "Article")

> head(longdf)
       ID Article
100.1 100      16
101.1 101      43
102.1 102      28
103.1 103      44
104.1 104      26
100.2 100      44
</code>```

Title: Transform Dataframe

Body:
I would like to reformat a generated dataframe so that I can add more information afterwards.

So lets say I have this df:

testdf <- data.frame(replicate(5,sample(1:50,5,rep=TRUE)))
testdf

  X1 X2 X3 X4 X5
1 38 20 47 43 39
2 25 27 25 45  9
3  9  1 44 12  8
4 48 19 21 46 13
5 26 50 26 35 38

With an additional column at the beginning:

new_column = c(100, 101, 102, 103, 104)
finaldf <- cbind(new_column, testdf)
colnames(finaldf) <- c("ID", "Article1", "Article2", "Article3", "Article4", "Article5")
finaldf

   ID Article1 Article2 Article3 Article4 Article5
1 100       34       22       23       22       19
2 101       43       19       43       14       11
3 102       32       40        5       12        9
4 103       37        5       37       15        2
5 104       41       19       30       42       49

Now I would like to transform this df in something like this:

   ID Article
  100       34
  100       22
  100       23
  100       22
  100       19
  101       43
  101       19
  101       43
  101       14
  101       11
  102       32
  102       40
  102        5
  102       12
  102        9
  103       37
  103        5
  103       37
  103       15
  103        2
  104       41
  104       19
  104       30
  104       42
  104       49

Does anyone know how I can solve this elegantly?

Body:
You can reshape from wide to long like this:

longdf <- reshape(finaldf, varying = c(2:6), direction = "long", idvar = "ID", sep = "", timevar = "Article")

> head(longdf)
       ID Article
100.1 100      16
101.1 101      43
102.1 102      28
103.1 103      44
104.1 104      26
100.2 100      44


问:
Problem getting JQuery BBQ to work
I'm still new to javascript/jquery, and I want to learn how to utilize a seemingly nice plugin.

I have linked to both jquery and bbq like this:

```<code><script src="lib/js/jquery.ba-bbq.min.js"></script>
<script src="lib/js/jquery.min.js"></script>
</code>```

I have inserted this code, that was given in the examples of a simple implementation on Ben Alman's site.

Can anyone explain to me, where I need to edit? And what kind of divs/tags/classes I would need to test this?

Would be much appreciated.

```<code>$(function(){

  // Keep a mapping of url-to-container for caching purposes.
  var cache = {
    // If url is '' (no fragment), display this div's content.
    '': $('.bbq-default')
  };

  // Bind an event to window.onhashchange that, when the history state changes,
  // gets the url from the hash and displays either our cached content or fetches
  // new content to be displayed.
  $(window).bind( 'hashchange', function(e) {

    // Get the hash (fragment) as a string, with any leading # removed. Note that
    // in jQuery 1.4, you should use e.fragment instead of $.param.fragment().
    var url = $.param.fragment();

    // Remove .bbq-current class from any previously "current" link(s).
    $( 'a.bbq-current' ).removeClass( 'bbq-current' );

    // Hide any visible ajax content.
    $( '.bbq-content' ).children( ':visible' ).hide();

    // Add .bbq-current class to "current" nav link(s), only if url isn't empty.
    url && $( 'a[href="#' + url + '"]' ).addClass( 'bbq-current' );

    if ( cache[ url ] ) {
      // Since the element is already in the cache, it doesn't need to be
      // created, so instead of creating it again, let's just show it!
      cache[ url ].show();

    } else {
      // Show "loading" content while AJAX content loads.
      $( '.bbq-loading' ).show();

      // Create container for this url's content and store a reference to it in
      // the cache.
      cache[ url ] = $( '<div class="bbq-item"/>' )

        // Append the content container to the parent container.
        .appendTo( '.bbq-content' )

        // Load external content via AJAX. Note that in order to keep this
        // example streamlined, only the content in .infobox is shown. You'll
        // want to change this based on your needs.
        .load( url, function(){
          // Content loaded, hide "loading" content.
          $( '.bbq-loading' ).hide();
        });
    }
  })

  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).trigger( 'hashchange' );

});
</code>```

答:
Firstly - you should reference jQuery before the bbq plugin.

```<code><script src="lib/js/jquery.min.js"></script>
<script src="lib/js/jquery.ba-bbq.min.js"></script>
</code>```

The main thing to remember when using the bbq plugin is that instead of manipulating the DOM directly (eg show/hide things/ ajax loading etc), you change the browser url fragment instead and then make the DOM changes in the hashchange event. For example:

```<code>// Hook up a click handler to and anchor
$("#myLink").click(function(){
    $.bbq.pushState("show", true);
});
</code>```

Then in the hashchange event, you would check for the show url fragment, $.bbq.getState("show"), and take the appropriate action.

Title: Problem getting JQuery BBQ to work

Body:
I'm still new to javascript/jquery, and I want to learn how to utilize a seemingly nice plugin.

I have linked to both jquery and bbq like this:

I have inserted this code, that was given in the examples of a simple implementation on Ben Alman's site.

Can anyone explain to me, where I need to edit? And what kind of divs/tags/classes I would need to test this?

Would be much appreciated.

$(function(){

  // Keep a mapping of url-to-container for caching purposes.
  var cache = {
    // If url is '' (no fragment), display this div's content.
    '': $('.bbq-default')
  };

  // Bind an event to window.onhashchange that, when the history state changes,
  // gets the url from the hash and displays either our cached content or fetches
  // new content to be displayed.
  $(window).bind( 'hashchange', function(e) {

    // Get the hash (fragment) as a string, with any leading # removed. Note that
    // in jQuery 1.4, you should use e.fragment instead of $.param.fragment().
    var url = $.param.fragment();

    // Remove .bbq-current class from any previously "current" link(s).
    $( 'a.bbq-current' ).removeClass( 'bbq-current' );

    // Hide any visible ajax content.
    $( '.bbq-content' ).children( ':visible' ).hide();

    // Add .bbq-current class to "current" nav link(s), only if url isn't empty.
    url && $( 'a[href="#' + url + '"]' ).addClass( 'bbq-current' );

    if ( cache[ url ] ) {
      // Since the element is already in the cache, it doesn't need to be
      // created, so instead of creating it again, let's just show it!
      cache[ url ].show();

    } else {
      // Show "loading" content while AJAX content loads.
      $( '.bbq-loading' ).show();

      // Create container for this url's content and store a reference to it in
      // the cache.
      cache[ url ] = $( '
' )

        // Append the content container to the parent container.
        .appendTo( '.bbq-content' )

        // Load external content via AJAX. Note that in order to keep this
        // example streamlined, only the content in .infobox is shown. You'll
        // want to change this based on your needs.
        .load( url, function(){
          // Content loaded, hide "loading" content.
          $( '.bbq-loading' ).hide();
        });
    }
  })

  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).trigger( 'hashchange' );

});

Body:
Firstly - you should reference jQuery before the bbq plugin.

<script src="lib/js/jquery.min.js"></script>
<script src="lib/js/jquery.ba-bbq.min.js"></script>

The main thing to remember when using the bbq plugin is that instead of manipulating the DOM directly (eg show/hide things/ ajax loading etc), you change the browser url fragment instead and then make the DOM changes in the hashchange event. For example:

// Hook up a click handler to and anchor
$("#myLink").click(function(){
    $.bbq.pushState("show", true);
});

Then in the hashchange event, you would check for the show url fragment, $.bbq.getState("show"), and take the appropriate action.


问:
How to disable and hide the pagination footer for react-table?
I'm new to react-table. Currently, I have a 5 rows table to render on react-table, and I don't need the pagination function. I understand turning pagination off, it can be done by "pagination={false}". However, the pagination control still showing, is there a way to hide it?

答:
I just found prop showPagination={false}. Try that.

https://github.com/tannerlinsley/react-table/tree/v6#props


问:
How to implement event sender - event receiver game objects in unity?
I have class "A", which will send event "a". Classes that are subscribing to event "a" will react to this event. Other classes can subscribe to event "a" without changing anything in class "A";

Now, what is the most reasonable way to do this in unity? Is there some messaging system that can already do that?

If not, should I make something like EventManager class that will store subscriber classes in array and call their methods?

答:
There are probably many ways to do this.

Public static List

```<code>public class A : MonoBehaviour
{
    public static List<A> AvailableAs = new List<A>();

    private void Awake()
    {
        if(!AvailableAs.Contains(this)) AvailableAs.Add(this);
    }

    private void OnDestroy()
    {
        if(AvailableAs.Contains(this)) AvailableAs.Remove(this);
    }

    public void SomePublicMethod()
    {
        // magic
    }
}
</code>```

and use it e.g. like

```<code>public class B : MonoBehaviour
{
    // run the method on all currently registered A instances
    public void DoIt()
    {
        foreach(var a in A.AvailableAs)
        {
            a.SomePublicMethod();
        }
    }
}
</code>```

Global EventHandler

Or if you rather want to go for encapsulation have as you mentioned a global event handler for all A's like

```<code>namespace ANamespace
{
    public static class AEventHandler
    {
        internal static event Action OnInvokeA;

        public static void InvokeAEvent()
        {
            if(OnInvokeA != null) OnInvokeA.Invoke();
        }
    }
}
</code>```

and in A have

```<code>namespace ANamespace
{
    public class A : MonoBehaviour {

        private void Awake()
        {
            // it is save to remove a callback first even
            // if it was not added yet. This makes sure it is
            // added only once always
            AEventHandler.OnIvokeA -= SomePrivateMethod;
            AEventHandler.OnIvokeA += SomePrivateMethod;
        }

        private void OnDestroy()
        {
            AEventHandler.OnIvokeA -= SomePrivateMethod;
        }

        private void SomePrivateMethod()
        {
            // magic
        }

    }
}
</code>```

Now in B you would rather simply do

```<code>// invoke the event and whoever is added as listener will do
// whatever he registered
// in this case all A instances execute their method
AEventHandler.InvokeAEvent();
</code>```

Unity Event

If you have however only one class A which throws an event and you want others to react to it simply use a UnityEvent like

```<code>public class A : MonoBehaviour
{
    public UnityEvent OnSomethingHappened = new UnityEvent();

    private void SomeMethodIWillRun()
    {
        //...
        OnSomethingHappened.Invoke();
    }
}
</code>```

Now you cann easily add callbacks to that event in the Unity Inspector by dragging in GameObjects/Components and select the method to call. (Exactly the same thing is used for the onClick event of the Button component btw. ;) )

And you could still add callbacks via script on runtime like

```<code>public class B : MonoBehaviour
{
    public A referenceToA;

    private void Start()
    {
        referenceToA.OnSomethingHappened.AddCallback(OnASomethingHappened);
    }

    private void OnDestroy()
    {
        referenceToA.OnSomethingHappened.RemoveCallback(OnASomethingHappened)
    }

    private void OnASomethingHappened()
    {
        //
    }
}
</code>```

Note: Typed on smartphone so no warranty but I hope the idea gets clear.

Body:
There are probably many ways to do this.

Public static List

public class A : MonoBehaviour
{
    public static List<A> AvailableAs = new List<A>();

    private void Awake()
    {
        if(!AvailableAs.Contains(this)) AvailableAs.Add(this);
    }

    private void OnDestroy()
    {
        if(AvailableAs.Contains(this)) AvailableAs.Remove(this);
    }

    public void SomePublicMethod()
    {
        // magic
    }
}

and use it e.g. like

public class B : MonoBehaviour
{
    // run the method on all currently registered A instances
    public void DoIt()
    {
        foreach(var a in A.AvailableAs)
        {
            a.SomePublicMethod();
        }
    }
}

Global EventHandler

Or if you rather want to go for encapsulation have as you mentioned a global event handler for all A's like

namespace ANamespace
{
    public static class AEventHandler
    {
        internal static event Action OnInvokeA;

        public static void InvokeAEvent()
        {
            if(OnInvokeA != null) OnInvokeA.Invoke();
        }
    }
}

and in A have

namespace ANamespace
{
    public class A : MonoBehaviour {

        private void Awake()
        {
            // it is save to remove a callback first even
            // if it was not added yet. This makes sure it is
            // added only once always
            AEventHandler.OnIvokeA -= SomePrivateMethod;
            AEventHandler.OnIvokeA += SomePrivateMethod;
        }

        private void OnDestroy()
        {
            AEventHandler.OnIvokeA -= SomePrivateMethod;
        }

        private void SomePrivateMethod()
        {
            // magic
        }

    }
}

Now in B you would rather simply do

// invoke the event and whoever is added as listener will do
// whatever he registered
// in this case all A instances execute their method
AEventHandler.InvokeAEvent();

Unity Event

If you have however only one class A which throws an event and you want others to react to it simply use a UnityEvent like

public class A : MonoBehaviour
{
    public UnityEvent OnSomethingHappened = new UnityEvent();

    private void SomeMethodIWillRun()
    {
        //...
        OnSomethingHappened.Invoke();
    }
}

Now you cann easily add callbacks to that event in the Unity Inspector by dragging in GameObjects/Components and select the method to call. (Exactly the same thing is used for the onClick event of the Button component btw. ;) )

And you could still add callbacks via script on runtime like

public class B : MonoBehaviour
{
    public A referenceToA;

    private void Start()
    {
        referenceToA.OnSomethingHappened.AddCallback(OnASomethingHappened);
    }

    private void OnDestroy()
    {
        referenceToA.OnSomethingHappened.RemoveCallback(OnASomethingHappened)
    }

    private void OnASomethingHappened()
    {
        //
    }
}

Note: Typed on smartphone so no warranty but I hope the idea gets clear.


问:
Can I safely use observeForever in my repository?
I follow the architecture pattern laid out in Android Room with a View - Kotlin. My app displays N stacks and every of those stacks can be displayed with a closed cover or an open cover. The number of stacks can change at run time. The information about whether or not the cover is closed is not permanent and I have to react in the UI when it changes. I therefore thought about making it a LiveData object.

```<code>class ContentRepository(private  val contentDao: ContentDao) {
    val allStacks : LiveData<List<Stack>> = contentDao.getStacks()
    val showCover = HashMap<Int, LiveData<Boolean>>()

    init {
        allStacks.observeForever { stacks ->
            stacks.filter { !showCover.containsKey(it.number) }
                .map { showCover.put(
                    it.number,
                    MutableLiveData<Boolean>(false)) }
        }
    }
}
</code>```

Given that I don't have access to a LifeCycleOwner from within the repository, can I use observeForever here, or will it result in data leaks?

答:
Use should Transformations in such case. For example:</p>

```<code>val allStacks : LiveData<List<Stack>> = contentDao.getStacks()
private val mShowCover = HashMap<Int, Boolean>()

val showCover = Transformations.map(allStacks) { stacks ->
    stacks.filter { !mShowCover.containsKey(it.number) }
                .map { mShowCover.put(
                        it.number,
                        false
                      )
                    }

    mShowCover
}
</code>```

Body:
I follow the architecture pattern laid out in Android Room with a View - Kotlin. My app displays N stacks and every of those stacks can be displayed with a closed cover or an open cover. The number of stacks can change at run time. The information about whether or not the cover is closed is not permanent and I have to react in the UI when it changes. I therefore thought about making it a LiveData object.

class ContentRepository(private  val contentDao: ContentDao) {
    val allStacks : LiveData<List<Stack>> = contentDao.getStacks()
    val showCover = HashMap<Int, LiveData<Boolean>>()

    init {
        allStacks.observeForever { stacks ->
            stacks.filter { !showCover.containsKey(it.number) }
                .map { showCover.put(
                    it.number,
                    MutableLiveData<Boolean>(false)) }
        }
    }
}

Given that I don't have access to a LifeCycleOwner from within the repository, can I use observeForever here, or will it result in data leaks?

Body:
Use should Transformations in such case. For example:

val allStacks : LiveData<List<Stack>> = contentDao.getStacks()
private val mShowCover = HashMap<Int, Boolean>()

val showCover = Transformations.map(allStacks) { stacks ->
    stacks.filter { !mShowCover.containsKey(it.number) }
                .map { mShowCover.put(
                        it.number,
                        false
                      )
                    }

    mShowCover
}


问:
Running 2 commands in npm script(nodemon && sass --watch)
I have a package.json file looks like this.

```<code>
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/app.js",
    "dev": "nodemon src/app.js -e js,hbs ",
    "scss": "sass --watch public/scss:public/css",
    "both": "nodemon src/app.js -e js,hbs && sass --watch public/scss:public/css",
    "both2" : "npm run dev && npm run scss"
  },
</code>```

I wonder why I cannot run these 2 commands:

"both": "nodemon src/app.js -e js,hbs && sass --watch public/scss:public/css"

by

```<code>npm run both
</code>```

When I try to run it, only the first command is working.

Github repository is below, just in case you need some testing.

https://github.com/tuanphanfi/weather-app-nodejs/

答:
Use a package called concurrently.

```<code>npm install concurrently
</code>```

Then you can make a script called both

```<code>"both": "concurrently \"nodemon src/app.js -e js,hbs\" \"sass --watch public/scss:public/css\""
</code>```

See javascript - How can I run multiple npm scripts in parallel?

Body:
I have a package.json file looks like this.

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node src/app.js",
    "dev": "nodemon src/app.js -e js,hbs ",
    "scss": "sass --watch public/scss:public/css",
    "both": "nodemon src/app.js -e js,hbs && sass --watch public/scss:public/css",
    "both2" : "npm run dev && npm run scss"
  },

I wonder why I cannot run these 2 commands:

"both": "nodemon src/app.js -e js,hbs && sass --watch public/scss:public/css"

by

npm run both

When I try to run it, only the first command is working.

Github repository is below, just in case you need some testing.

https://github.com/tuanphanfi/weather-app-nodejs/

Body:
Use a package called concurrently.

npm install concurrently

Then you can make a script called both

"both": "concurrently \"nodemon src/app.js -e js,hbs\" \"sass --watch public/scss:public/css\""

See javascript - How can I run multiple npm scripts in parallel?


问:
Initializing a subclass with an existing superclass instance in python3
I am writing my own version of the socket class in python.
I was wondering if there is a way to not initialize the subclass using it's __init__ method, but rather initialize it using an existing instance of the socket class.

Basically, what I am trying to do, is inherit from the socket class, and overwrite the accept() method to return an object of my own class instead of the socket class.

To get around this problem I want to implement the possibility to set a base socket in my __init__ method in my custom socket class, which takes the instance of a socket as argument and creates a new instance of my custom socket class using an existing instance of the socket class, or do the same using a fromSocket() classmethod.

My question now is how do I set an existing instance of the socket class as superclass for my own socket without using an attribute to contain the socket object? (Is that even possible in python?)

All the other related questions I found were more on how to change a superclass at runtime. I may have overlooked the answer somewhere, but I couldn't find it.

My code looks something like this:

```<code>import socket
class MySocket(socket.socket):
    def __init__(self, sock:socket.socket=None):
        if sock != None:
            # initialize using existing instance contained in sock
            # How? (My question)
        else:
            super().__init__() # Default conf is enough for now
    def accept(self):
        s, addr = super().accept()
        return MySocket(sock=s) # <= This is what I want to do
</code>```

and I want to call it like this:

```<code>s = MySocket()
# Call bind and listen, left out because it doesn't matter here
client, addr = s.accept()
# Client is an instance of socket.socket, but it should be MySocket
</code>```

答:
So you want something like the equivalent of a copy constructor.

Although there are some things that indicate an XY Problem, there's a simple alternative (If I got things right).

According to [Python 3.Docs]: socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):

If fileno is specified, the values for family, type, and proto are auto-detected from the specified file descriptor.

This seems to do exactly what you need.

Note: bear in mind that accept returns a tuple, while your override doesn't, so your class API is not compatible with its ancestor's.

Here's a piece of code that should do what you want:

class CustomSocket(socket.socket):
    def accept(self):
        conn, addr = super().accept()
        custom_conn = CustomSocket(conn.family, conn.type, conn.proto, conn.fileno())
        return custom_conn, addr
```

Body:
I am writing my own version of the socket class in python.
I was wondering if there is a way to not initialize the subclass using it's __init__ method, but rather initialize it using an existing instance of the socket class.

Basically, what I am trying to do, is inherit from the socket class, and overwrite the accept() method to return an object of my own class instead of the socket class.

To get around this problem I want to implement the possibility to set a base socket in my __init__ method in my custom socket class, which takes the instance of a socket as argument and creates a new instance of my custom socket class using an existing instance of the socket class, or do the same using a fromSocket() classmethod.

My question now is how do I set an existing instance of the socket class as superclass for my own socket without using an attribute to contain the socket object? (Is that even possible in python?)

All the other related questions I found were more on how to change a superclass at runtime. I may have overlooked the answer somewhere, but I couldn't find it.

My code looks something like this:

import socket
class MySocket(socket.socket):
    def __init__(self, sock:socket.socket=None):
        if sock != None:
            # initialize using existing instance contained in sock
            # How? (My question)
        else:
            super().__init__() # Default conf is enough for now
    def accept(self):
        s, addr = super().accept()
        return MySocket(sock=s) # <= This is what I want to do

and I want to call it like this:

s = MySocket()
# Call bind and listen, left out because it doesn't matter here
client, addr = s.accept()
# Client is an instance of socket.socket, but it should be MySocket


问:
using click function with ngb-accordion
accordion image
I am new to angular. I want use a click function inside accordion so that when the panel title is clicked, the student name mapped to it is passed to my function in the component. can anybody help me out.

I tried putting click with ngb-panel as well as ng-template, but both failed. Also i tried to wrap the template inside a span and linking click function to it, but it also didn't worked out. I am able to get the panel ID in my component but i need the data object also.

```<code>Info Array

    [{
    "firstName": "Sagar",
    "middleName": "Alias",
    "lastName": "jacky",
    "statusCode": {
            "ResultCode": "ERR",
            "Messages": [{
                    "code": "E0501",
                    "text": "tripNameAM is not present in our records",
                    "data": "tripNameAM"
                },
                {
                    "code": "E05012",
                    "text": "tripNamePM is not present in our records"
                    "data": "tripNamePM"
                }
                           ]
        }
    }
]

<div id="collapseExample" [ngbCollapse]="isCollapsed" class="accordion">
        <div class="card">
            <div class="card-body">
                <ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0" (panelChange)="test($event)">
                    <ngb-panel *ngFor="let data of info" title="{{data.firstName+' '+data.middleName+' '+data.lastName}}">
                        <ng-template ngbPanelContent *ngFor="let message of data.statusCode.Messages">
                                {{message.text}}
                        </ng-template>
                    </ngb-panel>
                </ngb-accordion>
            </div>
        </div>
    </div>
</code>```

below is what i tried,

```<code><div id="collapseExample" [ngbCollapse]="isCollapsed" class="accordion">
        <div class="card">
            <div class="card-body">
                <ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0" (panelChange)="test($event)">
                    <ngb-panel *ngFor="let data of info" title="{{data.firstName+' '+data.middleName+' '+data.lastName}}" (click)="getStudentname(data)">
                        <ng-template ngbPanelContent *ngFor="let message of data.statusCode.Messages">
                                {{message.text}}
                        </ng-template>
                    </ngb-panel>
                </ngb-accordion>
            </div>
        </div>
    </div>
</code>```

component

```<code>//imports..

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css', './mdb.scss']
})

export class AppComponent implements OnDestroy, OnInit {

constructor(private http: Http){}
...
...
getStudentname(data){

console.log(data);

}

}
</code>```

i want to get the student name mapped to a panel when it's title is clicked. Can anybody point me to the right direction.

答:
According to the documentation, you can customise the header also. Wrap the header inside an element, and place click element on it. Also, you create several ng-template element, which is probably not what you want to do, also put that into a container element:

```<code><ngb-panel *ngFor="let data of info" title="{{data.firstName+' '+data.middleName+' '+data.lastName}}" (click)="getStudentname(data)">
  <ng-template ngbPanelContent >
    <span *ngFor="let message of data.statusCode.Messages">
       {{message.text}}
    </span>
  </ng-template>
  <ng-template ngbPanelHeader>
    <div (click)="getStudentName(data)">
      {{data.firstName+' '+data.middleName+' '+data.lastName}}
    </div>
  </ng-template>
</ngb-panel>
</code>```

Title: using click function with ngb-accordion

Body:
accordion image
I am new to angular. I want use a click function inside accordion so that when the panel title is clicked, the student name mapped to it is passed to my function in the component. can anybody help me out.

I tried putting click with ngb-panel as well as ng-template, but both failed. Also i tried to wrap the template inside a span and linking click function to it, but it also didn't worked out. I am able to get the panel ID in my component but i need the data object also.

Info Array

    [{
    "firstName": "Sagar",
    "middleName": "Alias",
    "lastName": "jacky",
    "statusCode": {
            "ResultCode": "ERR",
            "Messages": [{
                    "code": "E0501",
                    "text": "tripNameAM is not present in our records",
                    "data": "tripNameAM"
                },
                {
                    "code": "E05012",
                    "text": "tripNamePM is not present in our records"
                    "data": "tripNamePM"
                }
                           ]
        }
    }
]

                <ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0" (panelChange)="test($event)">
                    <ngb-panel *ngFor="let data of info" title="{{data.firstName+' '+data.middleName+' '+data.lastName}}">
                        <ng-template ngbPanelContent *ngFor="let message of data.statusCode.Messages">
                                {{message.text}}
                        </ng-template>
                    </ngb-panel>
                </ngb-accordion>

below is what i tried,

                <ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0" (panelChange)="test($event)">
                    <ngb-panel *ngFor="let data of info" title="{{data.firstName+' '+data.middleName+' '+data.lastName}}" (click)="getStudentname(data)">
                        <ng-template ngbPanelContent *ngFor="let message of data.statusCode.Messages">
                                {{message.text}}
                        </ng-template>
                    </ngb-panel>
                </ngb-accordion>

component

//imports..

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css', './mdb.scss']
})

export class AppComponent implements OnDestroy, OnInit {

constructor(private http: Http){}
...
...
getStudentname(data){

console.log(data);

}

}

i want to get the student name mapped to a panel when it's title is clicked. Can anybody point me to the right direction.

Body:
According to the documentation, you can customise the header also. Wrap the header inside an element, and place click element on it. Also, you create several ng-template element, which is probably not what you want to do, also put that into a container element:

<ngb-panel *ngFor="let data of info" title="{{data.firstName+' '+data.middleName+' '+data.lastName}}" (click)="getStudentname(data)">
  <ng-template ngbPanelContent >
    <span *ngFor="let message of data.statusCode.Messages">
       {{message.text}}
    </span>
  </ng-template>
  <ng-template ngbPanelHeader>
    <div (click)="getStudentName(data)">
      {{data.firstName+' '+data.middleName+' '+data.lastName}}
    </div>
  </ng-template>
</ngb-panel>


问:
Vertically center in viewport using CSS
I am looking to vertically center a
 in the viewport (browser window) without resorting to Javascript (pure HTML and CSS only).  I have several constraints:

The div must be centered vertically in the viewport.  Methods I have seen only support centering inside another
, which is not what I want.

The height of the div is not known.

Other constraints:

The div must be aligned to the right.

The div has a constant width.

The div must support padding.

Other elements will be placed on the web page.  The div acts as a menu.

The div must support a background colour/image.

This gets me close to what I want, but not exactly:

```<code>#nav {
    position: fixed;
    right: 0;
    top: 50%;
}
</code>```

However, the top of the nav is in the middle, not the middle of the nav.

Is there some technique which allows me to center my div with these constraints?

答:
If the item is set to position: fixed or position: absolute:

```<code>top: 50%; left: 50%; transform: translate(-50%, -50%)
</code>```

If the item is set to position: relative, use:

```<code>margin-top: 50%; margin-left: 50%; transform: translate(-50%, -50%)
</code>```

(More info at the source.)

Example:

Run the snippet and then resize this page (or rotate device). The box stays centered in the "snippet viewport".

.myContainer {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 5px solid RebeccaPurple;
}

.myThing {
  width: 100px;
  height: 100px;
  background-color: CornflowerBlue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myContainer">
  <div class="myThing myContents">
  </div>
</div></code>```

OwnerDisplayName: strager

Title: Vertically center in viewport using CSS

Body:
I am looking to vertically center a
 in the viewport (browser window) without resorting to Javascript (pure HTML and CSS only).  I have several constraints:

The div must be centered vertically in the viewport.  Methods I have seen only support centering inside another
, which is not what I want.

The height of the div is not known.

Other constraints:

The div must be aligned to the right.

The div has a constant width.

The div must support padding.

Other elements will be placed on the web page.  The div acts as a menu.

The div must support a background colour/image.

This gets me close to what I want, but not exactly:

#nav {
    position: fixed;
    right: 0;
    top: 50%;
}

However, the top of the nav is in the middle, not the middle of the nav.

Is there some technique which allows me to center my div with these constraints?

LastEditorDisplayName: strager

Body:
If the item is set to position: fixed or position: absolute:

top: 50%; left: 50%; transform: translate(-50%, -50%)

If the item is set to position: relative, use:

margin-top: 50%; margin-left: 50%; transform: translate(-50%, -50%)

(More info at the source.)

Example:

Run the snippet and then resize this page (or rotate device). The box stays centered in the "snippet viewport".

.myContainer {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 5px solid RebeccaPurple;
}

.myThing {
  width: 100px;
  height: 100px;
  background-color: CornflowerBlue;
}

<div class="myContainer">
  <div class="myThing myContents">
  </div>
</div>


问:
Download large data directly from url to google cloud storage Bucket
I want to download a large dataset from URL "https" directly to google cloud storage(Bucket).

I have used gsutil stream command. via google cloud shell

curl -L https://../../..velodyne.zip | gsutil cp - gs://###/##/velodyne.zip

the result is

We've detected excessive egress network traffic in your Google Cloud Shell session. Discontinue or decrease this traffic or your session will be terminated.

答:
Install the SDK in your local machine

Then run the command from there

It will download the file from your local machine then use that as input to your gsutil command. You won't be able to do it using Cloud Shell, you would probably hit a "No Space left on device" if your file is too large.

You also mentioned in comment to Jofre's post that you've tried the Storage Transfer Service but it failed. Please share the error so we can see how it failed then maybe we can help you.


问:
Callback for task, why does the UI thread block
I have the following piece of code:

```<code>public static async Task<SqlConnection> OpenSqlConnectionAsync()
{
    if (_SqlConnection == default(SqlConnection))
    {
        _SqlConnection = new SqlConnection();
    }
    if (_SqlConnection.State == ConnectionState.Closed || _SqlConnection.State == ConnectionState.Broken)
    {
        _SqlConnection.ConnectionString = SqlConnectionStuff.GetConnectionString;
        Task ConnectionTask = _SqlConnection.OpenAsync();
        await ConnectionTask.ContinueWith((PreviousTask) =>
       {

       }
        );
        if (_SqlConnection.State == ConnectionState.Open)
        {
            MainWindow.Instance.lblCursorPosition.Dispatcher.Invoke(() => { MainWindow.Instance.lblCursorPosition.Text = "Connection opened!"; });
        }
        else
        {
            MainWindow.Instance.lblCursorPosition.Dispatcher.Invoke(() => { MainWindow.Instance.lblCursorPosition.Text = "Connection not opened!"; });
        }
    }
    return GetSqlConnection;
}
</code>```

In a separate class with the hopefully describing name SqlConnectionStuff... (no worries it will get changed soon ;P)

And down in my Window code there's is written the following:

```<code>private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SqlConnectionStuff.OpenSqlConnectionAsync().Wait();
}
</code>```

So when Invoking this using the Wait method behind the Task, stops the execution at the ContinueWith callback @ the OpenSqlConnectionAsync method.
The window freezes. It doesn't seem to finish and it looks like the UI thread is getting blocked, which makes sense from my rudimentary insights into the behaviour of the threads. It is not necessary for it to block at all but this method has to be executed before anything else will work so it won't matter at all if the user input is locked as long as the connection is established.

My interest now would be, why if I remove the Wait() instruction, the await on the callback seems to be executed flawlessly without getting stuck (as it is an empty instruction which can't fail obv.), and afterwards the information for the user is displayed in the UI.

答:
This code:

```<code>private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SqlConnectionStuff.OpenSqlConnectionAsync().Wait();
}
</code>```

...specifically the Wait() blocks the UI thread from executing.  By the way, calling an async method then explicitly blocking on it by calling Wait defeats the purpose of async/await by the way.  It's like spinning up a thread only to Join on it.  There are times when its ok to do so like when the signature of the method can't be changed to async (as in console apps Main methods prior to C# 7)

Meanwhile the following code attempts to synchonously thread marshal from whatever is the current thread to the UI thread in order to have the UI thread update the lblCursorPosition.Text property.

```<code>MainWindow.Instance.lblCursorPosition.Dispatcher.Invoke(() =>
       { MainWindow.Instance.lblCursorPosition.Text = "Connection opened!"; });
</code>```

Unforunately as we already mentioned, the UI thread is already busy waiting for OpenSqlConnectionAsync to complete.  So now you have a case of both ends waiting on the other.  You have a deadlock.

A fix would be to change the method signature like so and call await:

```<code>private async void Window_Loaded(object sender, RoutedEventArgs e) // <-- note async
{
    // await synchronously
    await SqlConnectionStuff.OpenSqlConnectionAsync(); // await here. No Wait()
}
</code>```

You could fix it another way by changing Invoke to BeginInvoke.  The latter posts the action asynchronously to the UI thread.  The net effect would be OpenSqlConnectionAsync would return the GetSqlConnection; the UI thread would resume following the Wait(); and later process the updating of the Label.

```<code>MainWindow.Instance.lblCursorPosition.Dispatcher.BeginInvoke(() =>
      { MainWindow.Instance.lblCursorPosition.Text = "Connection opened!"; });
</code>```

Body:
I have the following piece of code:

public static async Task<SqlConnection> OpenSqlConnectionAsync()
{
    if (_SqlConnection == default(SqlConnection))
    {
        _SqlConnection = new SqlConnection();
    }
    if (_SqlConnection.State == ConnectionState.Closed || _SqlConnection.State == ConnectionState.Broken)
    {
        _SqlConnection.ConnectionString = SqlConnectionStuff.GetConnectionString;
        Task ConnectionTask = _SqlConnection.OpenAsync();
        await ConnectionTask.ContinueWith((PreviousTask) =>
       {

       }
        );
        if (_SqlConnection.State == ConnectionState.Open)
        {
            MainWindow.Instance.lblCursorPosition.Dispatcher.Invoke(() => { MainWindow.Instance.lblCursorPosition.Text = "Connection opened!"; });
        }
        else
        {
            MainWindow.Instance.lblCursorPosition.Dispatcher.Invoke(() => { MainWindow.Instance.lblCursorPosition.Text = "Connection not opened!"; });
        }
    }
    return GetSqlConnection;
}

In a separate class with the hopefully describing name SqlConnectionStuff... (no worries it will get changed soon ;P)

And down in my Window code there's is written the following:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SqlConnectionStuff.OpenSqlConnectionAsync().Wait();
}

So when Invoking this using the Wait method behind the Task, stops the execution at the ContinueWith callback @ the OpenSqlConnectionAsync method.
The window freezes. It doesn't seem to finish and it looks like the UI thread is getting blocked, which makes sense from my rudimentary insights into the behaviour of the threads. It is not necessary for it to block at all but this method has to be executed before anything else will work so it won't matter at all if the user input is locked as long as the connection is established.

My interest now would be, why if I remove the Wait() instruction, the await on the callback seems to be executed flawlessly without getting stuck (as it is an empty instruction which can't fail obv.), and afterwards the information for the user is displayed in the UI.

Body:
This code:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SqlConnectionStuff.OpenSqlConnectionAsync().Wait();
}

...specifically the Wait() blocks the UI thread from executing.  By the way, calling an async method then explicitly blocking on it by calling Wait defeats the purpose of async/await by the way.  It's like spinning up a thread only to Join on it.  There are times when its ok to do so like when the signature of the method can't be changed to async (as in console apps Main methods prior to C# 7)

Meanwhile the following code attempts to synchonously thread marshal from whatever is the current thread to the UI thread in order to have the UI thread update the lblCursorPosition.Text property.

MainWindow.Instance.lblCursorPosition.Dispatcher.Invoke(() =>
       { MainWindow.Instance.lblCursorPosition.Text = "Connection opened!"; });

Unforunately as we already mentioned, the UI thread is already busy waiting for OpenSqlConnectionAsync to complete.  So now you have a case of both ends waiting on the other.  You have a deadlock.

A fix would be to change the method signature like so and call await:

private async void Window_Loaded(object sender, RoutedEventArgs e) // <-- note async
{
    // await synchronously
    await SqlConnectionStuff.OpenSqlConnectionAsync(); // await here. No Wait()
}

You could fix it another way by changing Invoke to BeginInvoke.  The latter posts the action asynchronously to the UI thread.  The net effect would be OpenSqlConnectionAsync would return the GetSqlConnection; the UI thread would resume following the Wait(); and later process the updating of the Label.

MainWindow.Instance.lblCursorPosition.Dispatcher.BeginInvoke(() =>
      { MainWindow.Instance.lblCursorPosition.Text = "Connection opened!"; });


问:
back button with jasonett/iOS
I am trying to create a back button that when the user clicks on it, it will take them to the previous page.

I found this code of a medium post by the author of Jasonett but it doesn't work for me. It creates the label but I can't click on it

"layers": [{
        "type": "label",
        "text": "",
        "style": {
          "top": "10",
          "right": "10",
          "width": "100",
          "height": "100"
        },
        "action": {
          "type": "$back"
        }
      }]```

答:
Source: The documentation

The element label is clickable or you can attach an action on a label only if it is at the item level.

So, for example, the following code will accept touch and the action set there would work fine.

```<code>{
  "items": [{
    "type": "label",
    "text": "Submit",
    "action": { SOME_ACTION }
  }]
}
</code>```

Where as the following won't accept a click.

```<code>{
  "items": [{
    "type": "vertical",
    "components": [{
      "type": "label",
      "text": "touch me",
      "action": { ... }
    }]
  }]
}
</code>```

In your example, label is defined inside layers. Thus it is not accepting a click.

Basically you have two options here.

Implement a click handler in JasonLabelComponent.m so regardless of their position labels always respond to action if it is provided in JSON.

Take the label out and make it a button, which by default would have action enabled.

Title: back button with jasonett/iOS

Body:
Source: The documentation

The element label is clickable or you can attach an action on a label only if it is at the item level.

So, for example, the following code will accept touch and the action set there would work fine.

{
  "items": [{
    "type": "label",
    "text": "Submit",
    "action": { SOME_ACTION }
  }]
}

Where as the following won't accept a click.

{
  "items": [{
    "type": "vertical",
    "components": [{
      "type": "label",
      "text": "touch me",
      "action": { ... }
    }]
  }]
}

In your example, label is defined inside layers. Thus it is not accepting a click.

Basically you have two options here.

Implement a click handler in JasonLabelComponent.m so regardless of their position labels always respond to action if it is provided in JSON.

Take the label out and make it a button, which by default would have action enabled.


问:
How to make obseravble array notify its dependencies when a property of an object inside the observable array gets updated?
I have the below array bound to a template

```<code>function Customer(id, name){
   this.Id = ko.obserable(id);
   this.Name = ko.obserable(name);
}

var customer1 = new Customer(1, "a");
var customer2 = new Customer(2, "b");

var customers = [customer1, customer2];

var oa = ko.observableArray(customers);

oa.subscribe(function(newValues){
   //How to force trigger this when a customer property gets updated?
});
</code>```

When I update a customer name on the view, the array has the updated data, but it does not notify it's subscribers. How do I get around that and force notify its subscribers?

答:
You can use computed values to automatically track changes in a list of values. Every observable you unwrap inside the computed function will create a dependency.

The only downside: you won't know which change caused the update. If that's what you need, you need to subscribe to the individual Name observables.

Here's an example that uses a custom equality comparer to keep things tidy. You can also only have hash return a string and unwrap oa inside the subscriber method manually.

function Customer(id, name){
   this.Id = ko.observable(id);
   this.Name = ko.observable(name);
   this.toString = () => `(${this.Id()}) ${this.Name()}`;
}

var customer1 = new Customer(1, "a");
var customer2 = new Customer(2, "b");

var customers = [customer1, customer2];

var oa = ko.observableArray(customers);

var oaHash = ko.pureComputed(() => ({
  hash: oa().map(c => c.Name()).join("||"),
  newValues: oa()
}));

oaHash.equalityComparer = (a, b) => a === b || a && b && a.hash === b.hash;

oaHash.subscribe(function ({ newValues }) {
  console.log(
    "Something changed, I now contain:",
    newValues.map(c => c.toString()).join(", ")
  );
});

customer1.Name("Jane");
oa.push(new Customer(3, "c"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

Body:
I have the below array bound to a template

function Customer(id, name){
   this.Id = ko.obserable(id);
   this.Name = ko.obserable(name);
}

var customer1 = new Customer(1, "a");
var customer2 = new Customer(2, "b");

var customers = [customer1, customer2];

var oa = ko.observableArray(customers);

oa.subscribe(function(newValues){
   //How to force trigger this when a customer property gets updated?
});

When I update a customer name on the view, the array has the updated data, but it does not notify it's subscribers. How do I get around that and force notify its subscribers?

Body:
You can use computed values to automatically track changes in a list of values. Every observable you unwrap inside the computed function will create a dependency.

The only downside: you won't know which change caused the update. If that's what you need, you need to subscribe to the individual Name observables.

Here's an example that uses a custom equality comparer to keep things tidy. You can also only have hash return a string and unwrap oa inside the subscriber method manually.

function Customer(id, name){
   this.Id = ko.observable(id);
   this.Name = ko.observable(name);
   this.toString = () => `(${this.Id()}) ${this.Name()}`;
}

var customer1 = new Customer(1, "a");
var customer2 = new Customer(2, "b");

var customers = [customer1, customer2];

var oa = ko.observableArray(customers);

var oaHash = ko.pureComputed(() => ({
  hash: oa().map(c => c.Name()).join("||"),
  newValues: oa()
}));

oaHash.equalityComparer = (a, b) => a === b || a && b && a.hash === b.hash;

oaHash.subscribe(function ({ newValues }) {
  console.log(
    "Something changed, I now contain:",
    newValues.map(c => c.toString()).join(", ")
  );
});

customer1.Name("Jane");
oa.push(new Customer(3, "c"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>