问:
Spring Convert enity manager getResultList results to JSON
I'm quite new to spring and I'm using spring entitymanager.createquery to make query and get the result from database.

So when make a http get this method executes to get all the patient name

```<code>    public List<PatientModel> fetchallpatients (){
        Query q = entityManager.createNativeQuery("select * from patient p ");
       List <PatientModel> patientList=q.getResultList();
        System.out.println(patientList);
        return patientList;
    }
</code>```

it is returning

```<code>[[
    1,
    "patientname",
    "patientphone",
    "patientgender",
    "patientinsurance",
    "patientage",
    "patientdiagnosis",
    "patientaddreq",
    "patientemr"
],
[
    2,
    "test",
    "patientphone",
    "patientgender",
    "patientinsurance",
    "patientage",
    "patientdiagnosis",
    "patientaddreq",
    "patientemr"
],
[
    3,
    "react",
    "12312",
    "male",
    "react",
    "56",
    "dsa",
    "ads",
    "das"
],
[
    4,
    "sign",
    "asd",
    "male",
    "react",
    "56",
    "Diagnose 2",
    "Ventilator",
    "on"
],
[
    5,
    "good",
    "3213",
    "male",
    "react",
    "56",
    "Diagnose 3",
    "ICU",
    "on"
] ]
</code>```

Front end I'm using react and I need this data to be in JSON format.

I have a POJO class for corresponding table:

```<code>package io.login.model;

import java.io.Serializable;

public class PatientModel  {

    String patientname;
    String patientage;
    String patientgender;
    String patientinsurance;
    String patientphone;
    String patientaddreq;
    String patientemr;

    public String getPatientname() {
        return patientname;
    }

    public void setPatientname(String patientname) {
        this.patientname = patientname;
    }

    public String getPatientage() {
        return patientage;
    }

    public void setPatientage(String patientage) {
        this.patientage = patientage;
    }

    public String getPatientgender() {
        return patientgender;
    }

    public void setPatientgender(String patientgender) {
        this.patientgender = patientgender;
    }

    public String getPatientinsurance() {
        return patientinsurance;
    }

    public void setPatientinsurance(String patientinsurance) {
        this.patientinsurance = patientinsurance;
    }

    public String getPatientphone() {
        return patientphone;
    }

    public void setPatientphone(String patientphone) {
        this.patientphone = patientphone;
    }

    public String getPatientdiagnosis() {
        return patientdiagnosis;
    }

    public void setPatientdiagnosis(String patientdiagnosis) {
        this.patientdiagnosis = patientdiagnosis;
    }

    public String getPatientaddreq() {
        return patientaddreq;
    }

    public void setPatientaddreq(String patientaddreq) {
        this.patientaddreq = patientaddreq;
    }

    public String getPatientemr() {
        return patientemr;
    }

    public void setPatientemr(String patientemr) {
        this.patientemr = patientemr;
    }

    String patientdiagnosis;

    public PatientModel(String patientname, String patientage, String patientgender, String patientinsurance, String patientphone, String patientdiagnosis, String patientaddreq, String patientemr) {
        this.patientname = patientname;
        this.patientage = patientage;
        this.patientgender = patientgender;
        this.patientinsurance = patientinsurance;
        this.patientphone = patientphone;
        this.patientdiagnosis = patientdiagnosis;
        this.patientaddreq = patientaddreq;
        this.patientemr = patientemr;
    }

}
</code>```

But I need the result like

```<code>    { { "patientname":"xyz"
"patientphone":"xyz"
"patientinsurance":"xyz"
"patientgender":"xyz"
"patientdiagnosis":"xyz"
"patientaddreq":"xyz" ... so on

    }
    }
</code>```

答:
you are returning List<String[]> and expect it to be a JSON list of your POJO?

change your method to return what is expected, like:

```<code>  @Transactional
  public List<PatientModel> fetchallpatients () {
      Query q = entityManager.createNativeQuery("select * from patient p ");
      List <PatientModel> patientList = q.getResultList();
      System.out.println(patientList);
      return patientList;
  }
</code>```

Body:
I'm quite new to spring and I'm using spring entitymanager.createquery to make query and get the result from database.

So when make a http get this method executes to get all the patient name

    public List<PatientModel> fetchallpatients (){
        Query q = entityManager.createNativeQuery("select * from patient p ");
       List <PatientModel> patientList=q.getResultList();
        System.out.println(patientList);
        return patientList;
    }

it is returning

[[
    1,
    "patientname",
    "patientphone",
    "patientgender",
    "patientinsurance",
    "patientage",
    "patientdiagnosis",
    "patientaddreq",
    "patientemr"
],
[
    2,
    "test",
    "patientphone",
    "patientgender",
    "patientinsurance",
    "patientage",
    "patientdiagnosis",
    "patientaddreq",
    "patientemr"
],
[
    3,
    "react",
    "12312",
    "male",
    "react",
    "56",
    "dsa",
    "ads",
    "das"
],
[
    4,
    "sign",
    "asd",
    "male",
    "react",
    "56",
    "Diagnose 2",
    "Ventilator",
    "on"
],
[
    5,
    "good",
    "3213",
    "male",
    "react",
    "56",
    "Diagnose 3",
    "ICU",
    "on"
] ]

Front end I'm using react and I need this data to be in JSON format.

I have a POJO class for corresponding table:

package io.login.model;

import java.io.Serializable;

public class PatientModel  {

    String patientname;
    String patientage;
    String patientgender;
    String patientinsurance;
    String patientphone;
    String patientaddreq;
    String patientemr;

    public String getPatientname() {
        return patientname;
    }

    public void setPatientname(String patientname) {
        this.patientname = patientname;
    }

    public String getPatientage() {
        return patientage;
    }

    public void setPatientage(String patientage) {
        this.patientage = patientage;
    }

    public String getPatientgender() {
        return patientgender;
    }

    public void setPatientgender(String patientgender) {
        this.patientgender = patientgender;
    }

    public String getPatientinsurance() {
        return patientinsurance;
    }

    public void setPatientinsurance(String patientinsurance) {
        this.patientinsurance = patientinsurance;
    }

    public String getPatientphone() {
        return patientphone;
    }

    public void setPatientphone(String patientphone) {
        this.patientphone = patientphone;
    }

    public String getPatientdiagnosis() {
        return patientdiagnosis;
    }

    public void setPatientdiagnosis(String patientdiagnosis) {
        this.patientdiagnosis = patientdiagnosis;
    }

    public String getPatientaddreq() {
        return patientaddreq;
    }

    public void setPatientaddreq(String patientaddreq) {
        this.patientaddreq = patientaddreq;
    }

    public String getPatientemr() {
        return patientemr;
    }

    public void setPatientemr(String patientemr) {
        this.patientemr = patientemr;
    }

    String patientdiagnosis;

    public PatientModel(String patientname, String patientage, String patientgender, String patientinsurance, String patientphone, String patientdiagnosis, String patientaddreq, String patientemr) {
        this.patientname = patientname;
        this.patientage = patientage;
        this.patientgender = patientgender;
        this.patientinsurance = patientinsurance;
        this.patientphone = patientphone;
        this.patientdiagnosis = patientdiagnosis;
        this.patientaddreq = patientaddreq;
        this.patientemr = patientemr;
    }

}

But I need the result like

    { { "patientname":"xyz"
"patientphone":"xyz"
"patientinsurance":"xyz"
"patientgender":"xyz"
"patientdiagnosis":"xyz"
"patientaddreq":"xyz" ... so on

    }
    }

Body:
you are returning List<String[]> and expect it to be a JSON list of your POJO?

change your method to return what is expected, like:

  @Transactional
  public List<PatientModel> fetchallpatients () {
      Query q = entityManager.createNativeQuery("select * from patient p ");
      List <PatientModel> patientList = q.getResultList();
      System.out.println(patientList);
      return patientList;
  }


来源: stackexchange

问:
I want to add a forgotten password page to my login page, but I can't jump to it after I update the code
I want to add a forgotten password page to my login page,

but I can't jump to it after I update the code.

The website error message：

[vue-router] uncaught error during route navigation

Uncaught (in promise) undefined

Maximum call stack size exceeded

old code

```<code>router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem("token") == "ImLogin";
  var role = localStorage.getItem('roles');
  if (isLogin) {
    if (to.matched.every(item => item.meta.indexOf(role) > -1)) {
      next();
    } else {
      next('/tips');
    }
  } else {
    if (to.path !== "/login") next("/login");
    else next();
  }
});
</code>```

new code

```<code><v-btn
  class="font-weight-bold"
  style="color:#FF7D52"
  href
  @click.prevent="forgetPassword"
  text
  >forgetPassword
</v-btn>

forgetPassword() {
      this.$router.push("/forgetPassword");
    },
</code>```

```<code>router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem("token") == "ImLogin";
  var role = localStorage.getItem('roles');
  if (isLogin) {
    if (to.matched.every(item => item.meta.indexOf(role) > -1)) {
      next();
    } else {
      next('/tips');
    }
  } else {
    if (to.path === "/forgetPassword") {
      next("/forgetPassword");
    } else {
      if (to.path !== "/login") next("/login");
      else next();
    }
  }
});
</code>```

答:
```<code>if (to.path === "/forgetPassword") {
      next("/forgetPassword");
}
</code>```

As Matt Ellen user suggested, this will create an infinite loop, since navigating to "/forgetpassword" triggers the router beforeEach hook again.

Simply next(); should solve this problem.

ContentLicense: CC BY-SA 4.0

Body:
I want to add a forgotten password page to my login page,

but I can't jump to it after I update the code.

The website error message：

[vue-router] uncaught error during route navigation

Uncaught (in promise) undefined

Maximum call stack size exceeded

old code

router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem("token") == "ImLogin";
  var role = localStorage.getItem('roles');
  if (isLogin) {
    if (to.matched.every(item => item.meta.indexOf(role) > -1)) {
      next();
    } else {
      next('/tips');
    }
  } else {
    if (to.path !== "/login") next("/login");
    else next();
  }
});

new code

<v-btn
  class="font-weight-bold"
  style="color:#FF7D52"
  href
  @click.prevent="forgetPassword"
  text
  >forgetPassword
</v-btn>

forgetPassword() {
      this.$router.push("/forgetPassword");
    },

router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem("token") == "ImLogin";
  var role = localStorage.getItem('roles');
  if (isLogin) {
    if (to.matched.every(item => item.meta.indexOf(role) > -1)) {
      next();
    } else {
      next('/tips');
    }
  } else {
    if (to.path === "/forgetPassword") {
      next("/forgetPassword");
    } else {
      if (to.path !== "/login") next("/login");
      else next();
    }
  }
});

Body:
if (to.path === "/forgetPassword") {
      next("/forgetPassword");
}

As Matt Ellen user suggested, this will create an infinite loop, since navigating to "/forgetpassword" triggers the router beforeEach hook again.

Simply next(); should solve this problem.


问:
How can I change the width attribute of an element but cannot no matter what I do
I have the following code:

```<code>if(this.commentContainer.style.width !== "0") {
  console.log("Greater than 0: " + this.commentContainer.scrollWidth);
  this.commentContainer.setAttribute("width","0");
  console.log("New Greater than 0: " + this.commentContainer.scrollWidth);

  this.commentContainer.animate({
    scrollWidth: 0
  })
} else {
  console.log("Equal to 0");

  console.log("Equal to 0: " + this.commentContainer.scrollWidth);
  this.commentContainer.setAttribute("width","285");
  console.log("New Equal to 0: " + this.commentContainer.scrollWidth);

  this.commentContainer.animate({
    scrollWidth: 285
  })
}
</code>```

No matter what I do to change the width, I cannot.

This is what I'm trying to do... which led me to the above

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery slideLeft and slideRight Effect</title>
<style>
    .box{
        float:left;
        overflow: hidden;
        background: #f0e68c;
    }
    /* Add padding and border to inner content
    for better animation effect */
    .box-inner{
        width: 395px;
        padding: 10px;
        border: 1px solid #a29415;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        var boxWidth = $(".box").width();
        $(".slide-both").click(function() {
          // alert("Width" + $(".box").width());
                if($(".box").width() === 0) {
                        $(".box").animate({
                        width: boxWidth
                });
                } else {
                        $(".box").animate({
                        width: 0
                });
            }
        });

    });
</script>
</head>
<body>
    <button type="button" class="slide-both">Slide Both</button>
    <hr>
    <div class="box">
        <div class="box-inner">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl bibendum scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet elementum vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla. Vivamus nisl leo, blandit at bibendum eu, tristique eget risus. Integer aliquet quam ut elit suscipit, id interdum neque porttitor. Integer faucibus ligula.</div>
    </div>
</body>
</html>
</code>```

I want to be able to actually convert the JQUERY code to Typescript:

```<code>        $(".slide-both").click(function() {
          // alert("Width" + $(".box").width());
                if($(".box").width() === 0) {
                        $(".box").animate({
                        width: boxWidth
                });
                } else {
                        $(".box").animate({
                        width: 0
                });
            }
        });
</code>```

If I can do that, this my size question is moot.

I've found that the scrollWidth and width are not the same: one is a string the other is a number.

How can I check the width of something if I cannot change it?

This is null: console.log("Current Width: " + this.commentContainer.getAttribute("width"));

So, any assistance would be appreciated.

UPDATE

So all the code comes down to this... I think I found the issue:

```<code>const textArea = e.currentTarget;
    console.log("Height before: ", textArea.style.height);
    textArea.style.height = "auto";
    if(textArea.style.height === "51px") {
      textArea.style.height = textArea.scrollHeight + "px";
    } else {
      textArea.style.height = textArea.scrollHeight + 25 + "px";
    }
    console.log("Height after: ", textArea.style.height);
 }
</code>```

If you notice: Kamil, the code: Works but, when I implement it, I get text over my icons. The 25 pushes the icons DOWN 25px.  When I delete, the icons are still PUSHED down, 25 px, and the final Height After is 51px.

This is BEFORE with text in the area:

This is AFTER:

I need to DUMP the extra PX to get it back to original configuration like this:

答:
Here's the SOLUTION!

```<code>  const textArea = e.currentTarget;
    console.log("OffsetHeight before: ", textArea.offsetHeight);
    textArea.style.height = "auto";
    console.log("Height before: ", textArea.style.height);
    if(textArea.style.height === "auto") {
       console.log("Inside if: ", textArea.style.height);
       textArea.style.height = textArea.scrollHeight + "px";
       this.iconscontainer.style.marginTop = "0px";
    }

    if(textArea.style.height === "26px") {
       console.log("Inside else: ", textArea.style.height);
       textArea.style.height = textArea.scrollHeight + "px";
       this.iconscontainer.style.marginTop = "-23px";
    }
    console.log("Height after: ", textArea.style.height);
  }
</code>```

Body:
I have the following code:

if(this.commentContainer.style.width !== "0") {
  console.log("Greater than 0: " + this.commentContainer.scrollWidth);
  this.commentContainer.setAttribute("width","0");
  console.log("New Greater than 0: " + this.commentContainer.scrollWidth);

  this.commentContainer.animate({
    scrollWidth: 0
  })
} else {
  console.log("Equal to 0");

  console.log("Equal to 0: " + this.commentContainer.scrollWidth);
  this.commentContainer.setAttribute("width","285");
  console.log("New Equal to 0: " + this.commentContainer.scrollWidth);

  this.commentContainer.animate({
    scrollWidth: 285
  })
}

No matter what I do to change the width, I cannot.

This is what I'm trying to do... which led me to the above

<!DOCTYPE html>

<meta charset="utf-8">
<title>jQuery slideLeft and slideRight Effect</title>

    <button type="button" class="slide-both">Slide Both</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl bibendum scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet elementum vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla. Vivamus nisl leo, blandit at bibendum eu, tristique eget risus. Integer aliquet quam ut elit suscipit, id interdum neque porttitor. Integer faucibus ligula.

I want to be able to actually convert the JQUERY code to Typescript:

        $(".slide-both").click(function() {
          // alert("Width" + $(".box").width());
                if($(".box").width() === 0) {
                        $(".box").animate({
                        width: boxWidth
                });
                } else {
                        $(".box").animate({
                        width: 0
                });
            }
        });

If I can do that, this my size question is moot.

I've found that the scrollWidth and width are not the same: one is a string the other is a number.

How can I check the width of something if I cannot change it?

This is null: console.log("Current Width: " + this.commentContainer.getAttribute("width"));

So, any assistance would be appreciated.

UPDATE

So all the code comes down to this... I think I found the issue:

const textArea = e.currentTarget;
    console.log("Height before: ", textArea.style.height);
    textArea.style.height = "auto";
    if(textArea.style.height === "51px") {
      textArea.style.height = textArea.scrollHeight + "px";
    } else {
      textArea.style.height = textArea.scrollHeight + 25 + "px";
    }
    console.log("Height after: ", textArea.style.height);
 }

If you notice: Kamil, the code: Works but, when I implement it, I get text over my icons. The 25 pushes the icons DOWN 25px.  When I delete, the icons are still PUSHED down, 25 px, and the final Height After is 51px.

This is BEFORE with text in the area:

This is AFTER:

I need to DUMP the extra PX to get it back to original configuration like this:

Body:
Here's the SOLUTION!

  const textArea = e.currentTarget;
    console.log("OffsetHeight before: ", textArea.offsetHeight);
    textArea.style.height = "auto";
    console.log("Height before: ", textArea.style.height);
    if(textArea.style.height === "auto") {
       console.log("Inside if: ", textArea.style.height);
       textArea.style.height = textArea.scrollHeight + "px";
       this.iconscontainer.style.marginTop = "0px";
    }

    if(textArea.style.height === "26px") {
       console.log("Inside else: ", textArea.style.height);
       textArea.style.height = textArea.scrollHeight + "px";
       this.iconscontainer.style.marginTop = "-23px";
    }
    console.log("Height after: ", textArea.style.height);
  }


问:
assigning the returning function
I'm new to javascript, and I saw code like this.

```<code><button onclick="this.onClickDoSmth">Click me</button>

onClickDoSmth = () => {
let a = this.clicked();
a();
}

clicked = () => {
console.log("test");
}
</code>```

What's the difference of replacing the expression for "a" to

```<code>onClickDoSmth = () => {
this.clicked();
}
</code>```

答:
The difference is that the former version received something from the function while the latter one doesn't.

This means the value of a receive what this.clicked function return. this.clicked must return a function so that it can be called by a() afterward

```<code>onClickDoSmth = () => {
    let a = this.clicked();
    a();
}
</code>```

This means onClickDoSmth is a function. After it has been executed, run this.clicked

```<code>onClickDoSmth = () => {
   this.clicked();
}
</code>```

Title: assigning the returning function

Body:
I'm new to javascript, and I saw code like this.

<button onclick="this.onClickDoSmth">Click me</button>

onClickDoSmth = () => {
let a = this.clicked();
a();
}

clicked = () => {
console.log("test");
}

What's the difference of replacing the expression for "a" to

onClickDoSmth = () => {
this.clicked();
}

Body:
The difference is that the former version received something from the function while the latter one doesn't.

This means the value of a receive what this.clicked function return. this.clicked must return a function so that it can be called by a() afterward

onClickDoSmth = () => {
    let a = this.clicked();
    a();
}

This means onClickDoSmth is a function. After it has been executed, run this.clicked

onClickDoSmth = () => {
   this.clicked();
}


问:
How is the conditional operator parsed?
So, the cppreference claims:

The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored.

However, it appears to me that the part of the expression after the ':' operator is also parsed as if it were between parentheses. I've tried to implement the ternary operator in my programming language (and you can see the results of parsing expressions here), and my parser pretends that the part of the expression after ':' is also parenthesized. For example, for the expression (1?1:0?2:0)-1, the interpreter for my programming language outputs 0, and this appears to be compatible with C. For instance, the C program:

```<code>#include <stdio.h>

int main() {
    printf("%d\n",(1?1:0?2:0)-1);
}
</code>```

Outputs 0.

Had I programmed the parser of my programming language that, when parsing the ternary operators, simply take the first already parsed node after ':' and take it as the third operand to '?:', it would output the same as ((1?1:0)?2:0)-1, that is 1.

My question is whether this would (pretending that the expression after the ':' is parenthesized) always be compatible with C?

答:
"Pretends that it is parenthesised" is some kind of description of operator parenthesis. But of course that has to be interpreted relative to precedence relations (including associativity). So in a-b*c and a*b-c, the subtraction effectively acts as though its arguments are parenthesised, only the left-hand argument is treated that way in a-b-c and it is the comparison operator which causes grouping in a<b-c and a-b<c.

I'm sure you know all that since your parser seems to work for all these cases, but I say that because the ternary operator is right-associative and of lower precedence than any other operator [Note 1]. That means that the pseudo-parentheses imposed by operator precedence surround the right-hand argument (regardless of its dominating operator, since all operators have higher precedence), and also the left-hand argument unless its dominating operator is another conditional operator. But that wouldn't be the case in C, where the comma operator has lower precedence and would not be enclosed by the imaginary parentheses following the :.

It's important to understand what is meant by the precedence of a complex operator. In effect, to compute the precedence relations we first collapse the operator to a simple ?: which includes the enclosed (second) argument. This is not "as if the expression were parenthesized", because it is parenthesized. It is parenthesized between ? and :, which in this context are syntactically parenthetic.

In this sense, it is very similar to the usual analysis of the subscript operator as a postfix operator, although the brackets of the subscript operator enclose a second argument. The precedence of the subscript operator is logically what would result from considering it to be a single [], abstracting away the expression contained inside. This is also the same as the function call operator. That happens to be written with parentheses, but the precise symbols are not important: it is possible to imagine an alternative language in which function calls are written with different symbols, perhaps { and }. That wouldn't affect the grammar at all.

It might seem odd to think of ? and : to be "parenthetic", since they don't look parenthetic. But a parser doesn't see the shapes of the symbols. It is satisfied by being told that a ( is closed by a ) and, in this case, that a ? is closed by a :. [Note 2]

Having said all that, I tried your compiler on the conditional expression

```<code>d = 0 ? 0 : n / d
</code>```

It parses this expression correctly, but the compiled code computes n / d before verifying whether d = 0 is true. That's not the way the conditional operator should work; in this case, it will lead to an unexpected divide by 0 exception. The conditional operator must first evaluate its left-hand argument, and then evaluate exactly one of the other two expressions.

Notes:

In C, this is not quite correct. The comma operator has lower precedence, and there is a more complex interaction with assignment operators, which logically have the same precedence and are also right-associative.

In C-like languages those symbols are not used for any other purpose, so it's OK to just regard them as strange-looking parentheses and leave it at that. But as the case of the function-call operator shows (or, for that matter, the unary - operator), it is sometimes possible to reuse operator symbols for more than one purpose.

As a curiosity, it is not strictly necessary that open and close parentheses be different symbols, as long as they are not used for any other purpose. So, for example, if | is not used as an operator symbol (as it is in C), then you could use | a | to mean the absolute value of a without creating any ambiguities.

A precise analysis of the circumstances in which symbol reuse leads to actual ambiguities is beyond the scope of this answer.

Title: How is the conditional operator parsed?

Body:
So, the cppreference claims:

The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored.

However, it appears to me that the part of the expression after the ':' operator is also parsed as if it were between parentheses. I've tried to implement the ternary operator in my programming language (and you can see the results of parsing expressions here), and my parser pretends that the part of the expression after ':' is also parenthesized. For example, for the expression (1?1:0?2:0)-1, the interpreter for my programming language outputs 0, and this appears to be compatible with C. For instance, the C program:

#include <stdio.h>

int main() {
    printf("%d\n",(1?1:0?2:0)-1);
}

Outputs 0.

Had I programmed the parser of my programming language that, when parsing the ternary operators, simply take the first already parsed node after ':' and take it as the third operand to '?:', it would output the same as ((1?1:0)?2:0)-1, that is 1.

My question is whether this would (pretending that the expression after the ':' is parenthesized) always be compatible with C?

Body:
"Pretends that it is parenthesised" is some kind of description of operator parenthesis. But of course that has to be interpreted relative to precedence relations (including associativity). So in a-b*c and a*b-c, the subtraction effectively acts as though its arguments are parenthesised, only the left-hand argument is treated that way in a-b-c and it is the comparison operator which causes grouping in a<b-c and a-b<c.

I'm sure you know all that since your parser seems to work for all these cases, but I say that because the ternary operator is right-associative and of lower precedence than any other operator [Note 1]. That means that the pseudo-parentheses imposed by operator precedence surround the right-hand argument (regardless of its dominating operator, since all operators have higher precedence), and also the left-hand argument unless its dominating operator is another conditional operator. But that wouldn't be the case in C, where the comma operator has lower precedence and would not be enclosed by the imaginary parentheses following the :.

It's important to understand what is meant by the precedence of a complex operator. In effect, to compute the precedence relations we first collapse the operator to a simple ?: which includes the enclosed (second) argument. This is not "as if the expression were parenthesized", because it is parenthesized. It is parenthesized between ? and :, which in this context are syntactically parenthetic.

In this sense, it is very similar to the usual analysis of the subscript operator as a postfix operator, although the brackets of the subscript operator enclose a second argument. The precedence of the subscript operator is logically what would result from considering it to be a single [], abstracting away the expression contained inside. This is also the same as the function call operator. That happens to be written with parentheses, but the precise symbols are not important: it is possible to imagine an alternative language in which function calls are written with different symbols, perhaps { and }. That wouldn't affect the grammar at all.

It might seem odd to think of ? and : to be "parenthetic", since they don't look parenthetic. But a parser doesn't see the shapes of the symbols. It is satisfied by being told that a ( is closed by a ) and, in this case, that a ? is closed by a :. [Note 2]

Having said all that, I tried your compiler on the conditional expression

d = 0 ? 0 : n / d

It parses this expression correctly, but the compiled code computes n / d before verifying whether d = 0 is true. That's not the way the conditional operator should work; in this case, it will lead to an unexpected divide by 0 exception. The conditional operator must first evaluate its left-hand argument, and then evaluate exactly one of the other two expressions.

Notes:

In C, this is not quite correct. The comma operator has lower precedence, and there is a more complex interaction with assignment operators, which logically have the same precedence and are also right-associative.

In C-like languages those symbols are not used for any other purpose, so it's OK to just regard them as strange-looking parentheses and leave it at that. But as the case of the function-call operator shows (or, for that matter, the unary - operator), it is sometimes possible to reuse operator symbols for more than one purpose.

As a curiosity, it is not strictly necessary that open and close parentheses be different symbols, as long as they are not used for any other purpose. So, for example, if | is not used as an operator symbol (as it is in C), then you could use | a | to mean the absolute value of a without creating any ambiguities.

A precise analysis of the circumstances in which symbol reuse leads to actual ambiguities is beyond the scope of this answer.


问:
Checking for duplicate data in SQL Server
Please don't ask me why but there is a lot of duplicate data where every field is duplicated.

For example

```<code>alex, 1
alex, 1
liza, 32
hary, 34
</code>```

I will need to eliminate from this table one of the alex, 1 rows

I know this algorithm will be very ineffecient, but it does not matter. I will need to remove duplicate data.

What is the best way to do this? Please keep in mind I do not have 2 fields, I actually have about 10 fields to check on.

答:
```<code>create table DuplicateTable(name varchar(10), number int)

insert DuplicateTable
values
    ('alex', 1),
    ('alex', 1),
    ('liza', 32),
    ('hary', 34);

with cte
as
(
    select *, row_number() over(partition by name, number order by name) RowNumber
    from DuplicateTable
)
delete cte
where RowNumber > 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please don't ask me why but there is a lot of duplicate data where every field is duplicated.

For example

alex, 1
alex, 1
liza, 32
hary, 34

I will need to eliminate from this table one of the alex, 1 rows

I know this algorithm will be very ineffecient, but it does not matter. I will need to remove duplicate data.

What is the best way to do this? Please keep in mind I do not have 2 fields, I actually have about 10 fields to check on.


问:
Code printing hello world despite being math
I'm trying this on repl.it and it just... prints "hello world" as a default. I don't know exactly what I'm doing wrong.

    import java.util.Scanner;

    class Input{
      public static void mian(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter your first double: ");
        double firstDouble = input.nextDouble();
        System.out.print("You entered " + firstDouble + " as your first number.");

        System.out.print("Enter you second double: ");
        double secondDouble = input.nextDouble();
        System.out.print("You entered " + secondDouble + " as you second number.");

        System.out.print("Enter your third double: ");
        double thirdDouble = input.nextDouble();
        System.out.print("You entered " + thirdDouble + "As your third number.");

        input.close();

      }

    }
```

答:
Looks like your main method is called mian.

Other than that, if you didn't change the default name of the first file, you should name your class Main or repl.it won't compile.


问:
How to RESET Arraylist at the end of the week?

I have an arraylist:

```<code>ArrayList<String> wholeWeekArrayList = new ArrayList<>();
</code>```

DatabaseHelper(SQLite) is storing the values into the(above) arrayList:

```<code>Cursor data = mDatabaseHelper.getData();
while (data.moveToNext() ) {
    wholeWeekArrayListString.add(data.getString(1));
    //getString(1) is column values from SQLite
}
</code>```

Then I have SumofWeek where all the data in wholeWeekArrayListString is added together.
(I Convert wholeWeekArrayListString to double to view it in a TEXTVIEW);

I want this SumOfWeek to reset to Zero at the end of the week but the data inside the SQLite must keep adding(for SumOfMonth view).

So by Sunday the data may be $50.00 (for Example) and Starting on int Monday. the data must reset to 0.0 and sum all the way up until Sunday.
This must happen weekly.

How would u do this? I have tried assining days of weeks.

```<code>Monday =1;
Tuesday = 2;
Wednesday =3;
// ...
</code>```

and iterate through the whole week but Im not able to get(i), which is the data of each single day of the week and then reset it on which is

```<code>int Sunday =7;
</code>```

I have the total amount but dont know what method to use to reset the data at the end of the week?

答:
Without changing the DB calls, you´ll have to store the timestamp of the latest reset (resetTimestamp in the example below). If the current time is in a different week, the code will trigger a reset of sumofWeek. After that, it´s your normal sumofWeek logic.

Thread safety: to be added depending on the application specifics.

```<code>    private ArrayList<Long> sumofWeek = new ArrayList<>();
    private Long resetTimestamp;

    public void populateWeek() {
        if(resetTimestamp == null || isDifferentWeek(resetTimestamp)) {
            sumofWeek = new ArrayList<Long>();
            for(int i = 0; i < 7; i++){
                sumofWeek.add(0l);
            }
            System.out.println(sumofWeek);
            resetTimestamp = java.lang.System.currentTimeMillis();
        }
        // populate sumofWeek here
    }

    private boolean isDifferentWeek(long resetTimestamp) {
        Calendar cl1 = new GregorianCalendar();
        cl1.setTimeInMillis(java.lang.System.currentTimeMillis());

        Calendar cl2 = new GregorianCalendar();
        cl2.setTimeInMillis(resetTimestamp);

        return cl1.get(Calendar.WEEK_OF_YEAR) != cl2.get(Calendar.WEEK_OF_YEAR);
    }
</code>```

Body:
I have an arraylist:

ArrayList<String> wholeWeekArrayList = new ArrayList<>();

DatabaseHelper(SQLite) is storing the values into the(above) arrayList:

Cursor data = mDatabaseHelper.getData();
while (data.moveToNext() ) {
    wholeWeekArrayListString.add(data.getString(1));
    //getString(1) is column values from SQLite
}

Then I have SumofWeek where all the data in wholeWeekArrayListString is added together.
(I Convert wholeWeekArrayListString to double to view it in a TEXTVIEW);

I want this SumOfWeek to reset to Zero at the end of the week but the data inside the SQLite must keep adding(for SumOfMonth view).

So by Sunday the data may be $50.00 (for Example) and Starting on int Monday. the data must reset to 0.0 and sum all the way up until Sunday.
This must happen weekly.

How would u do this? I have tried assining days of weeks.

Monday =1;
Tuesday = 2;
Wednesday =3;
// ...

and iterate through the whole week but Im not able to get(i), which is the data of each single day of the week and then reset it on which is

int Sunday =7;

I have the total amount but dont know what method to use to reset the data at the end of the week?

Body:
Without changing the DB calls, you´ll have to store the timestamp of the latest reset (resetTimestamp in the example below). If the current time is in a different week, the code will trigger a reset of sumofWeek. After that, it´s your normal sumofWeek logic.

Thread safety: to be added depending on the application specifics.

    private ArrayList<Long> sumofWeek = new ArrayList<>();
    private Long resetTimestamp;

    public void populateWeek() {
        if(resetTimestamp == null || isDifferentWeek(resetTimestamp)) {
            sumofWeek = new ArrayList<Long>();
            for(int i = 0; i < 7; i++){
                sumofWeek.add(0l);
            }
            System.out.println(sumofWeek);
            resetTimestamp = java.lang.System.currentTimeMillis();
        }
        // populate sumofWeek here
    }

    private boolean isDifferentWeek(long resetTimestamp) {
        Calendar cl1 = new GregorianCalendar();
        cl1.setTimeInMillis(java.lang.System.currentTimeMillis());

        Calendar cl2 = new GregorianCalendar();
        cl2.setTimeInMillis(resetTimestamp);

        return cl1.get(Calendar.WEEK_OF_YEAR) != cl2.get(Calendar.WEEK_OF_YEAR);
    }


问:
How to 'minify' Javascript code
JQuery has two versions for download, one is Production (19KB, Minified and Gzipped), and the other is Development (120KB, Uncompressed Code).

Now the compact 19kb version, if you download it, you will see is still a javascript executable code. How did they compactify it? And how can I 'minify' my code like that too?

答: You can use javascript minifier of ubercompute.com to minify your code, It will minify your javascript code upto 75% of their original version.</p>

Title: How to 'minify' Javascript code


问:
How can I use a DLL file from Python?
What is the easiest way to use a DLL file from within Python?

Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python?

Native Python functionality is strongly preferred over using a third-party library.

答:
If the DLL is of type COM library, then you can use pythonnet.

```<code>pip install pythonnet
</code>```

Then in your python code, try the following

```<code>import clr
clr.AddReference('path_to_your_dll')

# import the namespace and class

from Namespace import Class

# create an object of the class

obj = Class()

# access functions return type using object

value = obj.Function(<arguments>)

</code>```

then instantiate an object as per the class in the DLL, and access the methods within it.

OwnerDisplayName: Tom

Title: How can I use a DLL file from Python?

Body:
If the DLL is of type COM library, then you can use pythonnet.

pip install pythonnet

Then in your python code, try the following

import clr
clr.AddReference('path_to_your_dll')

# import the namespace and class

from Namespace import Class

# create an object of the class

obj = Class()

# access functions return type using object

value = obj.Function(<arguments>)

then instantiate an object as per the class in the DLL, and access the methods within it.


问:
How to programmatically create/build Sharepoint PPS -- Dashboard, Scorecard, KPIs
Is there any ariticles or suggestions that can help me go through this: How to programmatically create/build Sharepoint PPS -- Dashboard, Scorecard, KPIs, and then dploy it or import it to a web page?

I am planning to create a KPI and conncted with a analytic service table, add such kpi to a scorecard, add scordcard to a dashboard. Finally, add such dashboard to the page(web page or web part page).

I hope MS allow me do the following:

```<code>KPI myKpi = new KPI();
Dashboard myDb = new DashBoard();
        .
        .
        .
myPage.import(myDb);
MyDb.visulization();
</code>```

答:
Please check out the "Creating and Deploying Dashboards Remotely" blog post at http://blogs.msdn.com/b/performancepoint/archive/2010/10/21/creating-and-deploying-dashboards-remotely.aspx

Also, the MSDN topics have code examples for the Create/Delete/Get/Update methods in the SPDataStore class: http://msdn.microsoft.com/en-us/library/microsoft.performancepoint.scorecards.store.spdatastore_methods.aspx

Body:
Is there any ariticles or suggestions that can help me go through this: How to programmatically create/build Sharepoint PPS -- Dashboard, Scorecard, KPIs, and then dploy it or import it to a web page?

I am planning to create a KPI and conncted with a analytic service table, add such kpi to a scorecard, add scordcard to a dashboard. Finally, add such dashboard to the page(web page or web part page).

I hope MS allow me do the following:

KPI myKpi = new KPI();
Dashboard myDb = new DashBoard();
        .
        .
        .
myPage.import(myDb);
MyDb.visulization();


问:
LinkedIn sharing doesn't work as expected
I'm looking for an easy way to share through LinkedIn without all that hassle with OAuth 2.0 which I don't see required when I see other pages that use this kind of sharing (and they didn't required anything from - I can straight out share).

Straight to the issue:

this one works: https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Frefair.me

this one doesn't: https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Frefair.me%2Fjob%2F494

Seems like beyond main domain I can't get sharing working. For instance from other site a link that goes deeper and is still shareable: https://www.linkedin.com/shareArticle?mini=true&url=https://bulldogjob.pl/companies/jobs/2043-programista-java-warszawa-bms-sp-z-o-o&title=Programista+Java&summary=&source=https://bulldogjob.pl

I also tested with and without source and summary query params. Anyone had that issue?

答:
I decoded your URL so I could get a cleaner look...

https://www.linkedin.com/sharing/share-offsite/?url=https://refair.me/job/494

So, let's try to visit your URL: https://refair.me/job/494 .  The webpage you are sharing DOES NOT LOAD.

Is your site down for everyone?  Yes, your site is down for everyone.

In order to share a URL on LinkedIn, you must fulfill the following minimum requirements:

The URL must load.

If you just want to test out the API, try using wikipedia.org or google.com as test pages.

Surprisingly, the old refair.me URL by itself works fine in LinkedIn, but that could be from some internal cache, from way back in the day when the page once did work.  It certainly does not do so anymore.


问:
How to add an text in a Python / Tkinter text
I have a question about Python/Tkinter. I want to add text
before the number of sport activities in a Tk.Label.
For Example I want to write 'Kalorien:' before the int Kalorien in the textfield Kalorien_fen

```<code>def Kalorienzähler():

fenster1=tk.Tk()
fenster1.wm_geometry('800x480')
Kalorien_fen =  tk.Label(fenster1, text= (Kalorien)  )
Kalorien_fen.config(font=('Arial', 62))
Kalorien_fen.pack()
Liegestütze_fen = tk.Label(fenster1,text= (Liegestütze))
Liegestütze_fen.config(font=('Arial', 62))
Liegestütze_fen.pack()
Kniebeuge_fen = tk.Label(fenster1,text= (Kniebeuge))
Kniebeuge_fen.config(font=('Arial', 62))
Kniebeuge_fen.pack()
Planks_fen = tk.Label(fenster1,text= (Planks))
Planks_fen.config(font=('Arial', 62))
Planks_fen.pack()
Hampelmann_fen = tk.Label(fenster1,text= (Hampelmann))
Hampelmann_fen.config(font=('Arial', 62))
Hampelmann_fen.pack()

Aufgabe=random.choice(Sport_liste)
fenster=tk.Tk()
fenster.wm_geometry('800x480')
text =  tk.Label(master=fenster, text= Aufgabe)
text.config(font=('Arial', 72))
text.pack()
if Aufgabe == 'Liegestütze 5x ':
    Kalorien += 1
    Liegestütze += 5
if Aufgabe == 'Liegestütze 10x ':
    Kalorien += 2
    Liegestütze += 10
if Aufgabe == 'Kniebeuge 15X':
    Kalorien += 2.5
    Kniebeuge += 10
if Aufgabe == 'Kniebeuge 10x':
    Kalorien += 3.5
    Kniebeuge += 10
if Aufgabe == 'Planks 30s':
    Kalorien += 2.5
    Planks += 30
if Aufgabe == 'Planks 10s':
    Kalorien += 1
    Planks += 10
if Aufgabe == 'Hampelmann 10x':
    Kalorien += 10
    Hampelmann += 10

B = tk.Button(master=fenster, text ="Wiederholen", command = wiederholen )
B.config( height = 5, width = 50 )
B.pack()
Bu = tk.Button(master=fenster, text ="Statistiken", command = Kalorienzähler )
Bu.config( height = 5, width = 50 )
Bu.pack()
fenster.mainloop()
'''
</code>```

I also want to write 'Liegestütze' before the int Liegestützen in Liegestütze_fen, but I don't know how to do this.
Thanks

答:
Try:

Kalorien_fen = tk.Label(fenster1, text=f"Kalorien:{Kalorien}")
```

<p>Or if you don't want to use f-strings/your Python version doesn't support them, you can do:</p>

<pre class="lang-py prettyprint-override"><code>Kalorien_fen = tk.Label(fenster1, text="Kalorien:" + str(Kalorien))
</code>```

You can do something similar for Liegestütze.

Body:
I have a question about Python/Tkinter. I want to add text
before the number of sport activities in a Tk.Label.
For Example I want to write 'Kalorien:' before the int Kalorien in the textfield Kalorien_fen

def Kalorienzähler():

fenster1=tk.Tk()
fenster1.wm_geometry('800x480')
Kalorien_fen =  tk.Label(fenster1, text= (Kalorien)  )
Kalorien_fen.config(font=('Arial', 62))
Kalorien_fen.pack()
Liegestütze_fen = tk.Label(fenster1,text= (Liegestütze))
Liegestütze_fen.config(font=('Arial', 62))
Liegestütze_fen.pack()
Kniebeuge_fen = tk.Label(fenster1,text= (Kniebeuge))
Kniebeuge_fen.config(font=('Arial', 62))
Kniebeuge_fen.pack()
Planks_fen = tk.Label(fenster1,text= (Planks))
Planks_fen.config(font=('Arial', 62))
Planks_fen.pack()
Hampelmann_fen = tk.Label(fenster1,text= (Hampelmann))
Hampelmann_fen.config(font=('Arial', 62))
Hampelmann_fen.pack()

Aufgabe=random.choice(Sport_liste)
fenster=tk.Tk()
fenster.wm_geometry('800x480')
text =  tk.Label(master=fenster, text= Aufgabe)
text.config(font=('Arial', 72))
text.pack()
if Aufgabe == 'Liegestütze 5x ':
    Kalorien += 1
    Liegestütze += 5
if Aufgabe == 'Liegestütze 10x ':
    Kalorien += 2
    Liegestütze += 10
if Aufgabe == 'Kniebeuge 15X':
    Kalorien += 2.5
    Kniebeuge += 10
if Aufgabe == 'Kniebeuge 10x':
    Kalorien += 3.5
    Kniebeuge += 10
if Aufgabe == 'Planks 30s':
    Kalorien += 2.5
    Planks += 30
if Aufgabe == 'Planks 10s':
    Kalorien += 1
    Planks += 10
if Aufgabe == 'Hampelmann 10x':
    Kalorien += 10
    Hampelmann += 10

B = tk.Button(master=fenster, text ="Wiederholen", command = wiederholen )
B.config( height = 5, width = 50 )
B.pack()
Bu = tk.Button(master=fenster, text ="Statistiken", command = Kalorienzähler )
Bu.config( height = 5, width = 50 )
Bu.pack()
fenster.mainloop()
'''

I also want to write 'Liegestütze' before the int Liegestützen in Liegestütze_fen, but I don't know how to do this.
Thanks

Body:
Try:

Kalorien_fen = tk.Label(fenster1, text=f"Kalorien:{Kalorien}")

Or if you don't want to use f-strings/your Python version doesn't support them, you can do:

Kalorien_fen = tk.Label(fenster1, text="Kalorien:" + str(Kalorien))

You can do something similar for Liegestütze.


问:
C++ for loop too slow
I'm trying to make an audio application with PortAudio. My callback function has been very slow and it has been creating constant underruns. I removed everything in the callback one by one until I found the issue: the for loop. I removed everything so that the only thing happening in the callback function is the for loop and it is still causing underruns. I know it is the for loop because when I reduce the number of iterations, the underruns go away.

```<code>static int patestCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags, void *userData)
{
    int x = 0;
    for (int jj = 0; jj < 10000; jj++)
    {
        x++; // for testing, not actually used
    };
    return paContinue;
}
</code>```

Here is my full code for testing: https://gist.github.com/johnroper100/b87641f5609dbb49bc3c1121b1f4daf1

Not really necessary for this question, but I did the same callback in the python equivalent (sounddevice) and there are no issues.

答:
I believe that the reason to why the callback function is not working properly is explained by the documentation (in the answer @ÁdámHunyadi provided). But I am not sure if it explains WHY the for-loop is too slow.

In order for a stream to maintain glitch-free operation the callback
  must consume and return audio data faster than it is recorded and/or
  played. PortAudio anticipates that each callback invocation may
  execute for a duration approaching the duration of frameCount audio
  frames at the stream sample rate. It is reasonable to expect to be
  able to utilise 70% or more of the available CPU time in the PortAudio
  callback. However, due to buffer size adaption and other factors, not
  all host APIs are able to guarantee audio stability under heavy CPU
  load with arbitrary fixed callback buffer sizes. When high callback
  CPU utilisation is required the most robust behavior can be achieved
  by using paFramesPerBufferUnspecified as the Pa_OpenStream()
  framesPerBuffer parameter.

Looking at the example in the PortAudio Doc Example, they iterate through a for-loop of framesPerBuffer iteration (which in the docs are defined as framesCount). Approaching the duration of frameCount. But in your code example you are doing the same thing BUT you do it the size of a vector times (which I believe is not Approaching the duration of frameCount). Only using one for-loop instead of two, and using framesPerBuffer instead of 10000 as the maximum number of iterations might resolve the "Too slow for-loop" issue.

Title: C++ for loop too slow

Body:
I'm trying to make an audio application with PortAudio. My callback function has been very slow and it has been creating constant underruns. I removed everything in the callback one by one until I found the issue: the for loop. I removed everything so that the only thing happening in the callback function is the for loop and it is still causing underruns. I know it is the for loop because when I reduce the number of iterations, the underruns go away.

static int patestCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags, void *userData)
{
    int x = 0;
    for (int jj = 0; jj < 10000; jj++)
    {
        x++; // for testing, not actually used
    };
    return paContinue;
}

Here is my full code for testing: https://gist.github.com/johnroper100/b87641f5609dbb49bc3c1121b1f4daf1

Not really necessary for this question, but I did the same callback in the python equivalent (sounddevice) and there are no issues.


问:
asp.net on session timeout redirect to home page
i have web app and on session timeout and user interaction on the page, this needs to redirect to home/landing page

solutions found on the net

1) Session check in page_load of all the aspx pages of the application.
2) code in session start of global.asax

```<code>public void Session_Start
{
        Response.Redirect("home.aspx");
        // or Server.Transfer("home.aspx");
}
</code>```

I am going for 2nd option,let me know
1) whether i am in right way or any better solutions for this?
2) in the second option whether to use Response.Redirect or Server.Transfer

-Thanks

答:
I will go for the first one and do check for the session.....

Write following code in OnInit method of the Master page will do your tack easily

```<code>    /// <summary>
    /// Check for the session time out
    /// </summary>
    /// <param name="e"></param>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (Context.Session != null)
        {
            //check whether a new session was generated
            if (Session.IsNewSession)
            {
                //check whether a cookies had already been associated with this request
                HttpCookie sessionCookie = Request.Cookies["ASP.NET_SessionId"];
                if (sessionCookie != null)
                {
                    string sessionValue = sessionCookie.Value;
                    if (!string.IsNullOrEmpty(sessionValue))
                    {
                        // we have session timeout condition!
                        Response.Redirect("Home.aps");
                    }
                }
            }
        }
    }
</code>```

Body:
i have web app and on session timeout and user interaction on the page, this needs to redirect to home/landing page

solutions found on the net

1) Session check in page_load of all the aspx pages of the application.
2) code in session start of global.asax

public void Session_Start
{
        Response.Redirect("home.aspx");
        // or Server.Transfer("home.aspx");
}

I am going for 2nd option,let me know
1) whether i am in right way or any better solutions for this?
2) in the second option whether to use Response.Redirect or Server.Transfer

-Thanks

Body:
I will go for the first one and do check for the session.....

Write following code in OnInit method of the Master page will do your tack easily

    /// <summary>
    /// Check for the session time out
    /// </summary>
    /// <param name="e"></param>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (Context.Session != null)
        {
            //check whether a new session was generated
            if (Session.IsNewSession)
            {
                //check whether a cookies had already been associated with this request
                HttpCookie sessionCookie = Request.Cookies["ASP.NET_SessionId"];
                if (sessionCookie != null)
                {
                    string sessionValue = sessionCookie.Value;
                    if (!string.IsNullOrEmpty(sessionValue))
                    {
                        // we have session timeout condition!
                        Response.Redirect("Home.aps");
                    }
                }
            }
        }
    }


问:
Oidc Client Sign in with Username and password
I have a login form which have username and password fields in it. I want to authenticate username and password with Oidc Client . This is a method that was used for signing in by default:

```<code>     async signIn(state) {
            await this.ensureUserManagerInitialized();
            try {
                const silentUser = await this.userManager.signinSilent(this.createArguments());
                this.updateState(silentUser);
                return this.success(state);
            } catch (silentError) {
                // User might not be authenticated, fallback to popup authentication
                console.log("Silent authentication error: ", silentError);

                try {
                    if (this._popUpDisabled) {
                        throw new Error('Popup disabled. Change \'AuthorizeService.js:AuthorizeService._popupDisabled\' to false to enable it.')
                    }

                    const popUpUser = await this.userManager.signinPopup(this.createArguments());
                    this.updateState(popUpUser);
                    return this.success(state);
                } catch (popUpError) {
                    if (popUpError.message === "Popup window closed") {
                        // The user explicitly cancelled the login action by closing an opened popup.
                        return this.error("The user closed the window.");
                    } else if (!this._popUpDisabled) {
                        console.log("Popup authentication error: ", popUpError);
                    }

                    // PopUps might be blocked by the user, fallback to redirect
                    try {
                        await this.userManager.signinRedirect(this.createArguments(state));
                        return this.redirect();
                    } catch (redirectError) {
                        console.log("Redirect authentication error: ", redirectError);
                        return this.error(redirectError);
                    }
                }
            }
        }
</code>```

Method was called from Login.js :

```<code>async login(returnUrl) {
        const state = {returnUrl };
        const result = await authService.signIn(state);
        switch (result.status) {
            case AuthenticationResultStatus.Redirect:
                break;
            case AuthenticationResultStatus.Success:
                await this.navigateToReturnUrl(returnUrl);
                break;
            case AuthenticationResultStatus.Fail:
                this.setState({ message: result.message });
                break;
            default:
                throw new Error(`Invalid status result ${result.status}.`);
        }
    }
</code>```

Now i have a custom login form. I will have value of user-entered username and password but I have no idea of authenticating it. How can it be done?

答:
Unfortunately it's not supported by the library yet.

https://github.com/IdentityModel/oidc-client-js/issues/234

Body:
I have a login form which have username and password fields in it. I want to authenticate username and password with Oidc Client . This is a method that was used for signing in by default:

     async signIn(state) {
            await this.ensureUserManagerInitialized();
            try {
                const silentUser = await this.userManager.signinSilent(this.createArguments());
                this.updateState(silentUser);
                return this.success(state);
            } catch (silentError) {
                // User might not be authenticated, fallback to popup authentication
                console.log("Silent authentication error: ", silentError);

                try {
                    if (this._popUpDisabled) {
                        throw new Error('Popup disabled. Change \'AuthorizeService.js:AuthorizeService._popupDisabled\' to false to enable it.')
                    }

                    const popUpUser = await this.userManager.signinPopup(this.createArguments());
                    this.updateState(popUpUser);
                    return this.success(state);
                } catch (popUpError) {
                    if (popUpError.message === "Popup window closed") {
                        // The user explicitly cancelled the login action by closing an opened popup.
                        return this.error("The user closed the window.");
                    } else if (!this._popUpDisabled) {
                        console.log("Popup authentication error: ", popUpError);
                    }

                    // PopUps might be blocked by the user, fallback to redirect
                    try {
                        await this.userManager.signinRedirect(this.createArguments(state));
                        return this.redirect();
                    } catch (redirectError) {
                        console.log("Redirect authentication error: ", redirectError);
                        return this.error(redirectError);
                    }
                }
            }
        }

Method was called from Login.js :

async login(returnUrl) {
        const state = {returnUrl };
        const result = await authService.signIn(state);
        switch (result.status) {
            case AuthenticationResultStatus.Redirect:
                break;
            case AuthenticationResultStatus.Success:
                await this.navigateToReturnUrl(returnUrl);
                break;
            case AuthenticationResultStatus.Fail:
                this.setState({ message: result.message });
                break;
            default:
                throw new Error(`Invalid status result ${result.status}.`);
        }
    }

Now i have a custom login form. I will have value of user-entered username and password but I have no idea of authenticating it. How can it be done?


问:
Wrong Values in For Loop C++
I am trying to print the values stored in Array l[] and r[] from array a[].

When I am trying to print values of array l[] its showing me invalid values.

But when I comment down the line which are providing values in array r[] from a[] the values of array l[] are then showing correct values.

I am providing input values 1 2 3 ... 10 and the output is comming 7 8 9 10 5 but when i comment lines which are providing values to arrar r[] the output is correct 1 2 3 4 5.

Why is this happening ?

```<code>#include <iostream>

using namespace std;

int main()
{
    int a[10], l[6], r[6],m = 0,n = 0;

    for(int i=0;i<10;i++)
        cin>>a[i];

    for(int i=0;i<5;i++)
        l[i] = a[i];

    for(int i=5;i<10;i++)
        r[i] = a[i];

    //l[6] = r[6] = 1e9;

    for(int i=0;i<5;i++)
        cout<<l[i];

    return 0;
}
</code>```

答:
Here's your code:</p>

```<code>for(int i=0;i<10;i++)
    cin>>a[i];  // this one looks OK

for(int i=0;i<5;i++)
    l[i] = a[i];  // this one looks OK too

for(int i=5;i<10;i++)
    r[i] = a[i];  // you access 'r' beyond 5 that damages other vars
</code>```

Title: Wrong Values in For Loop C++

Body:
I am trying to print the values stored in Array l[] and r[] from array a[].

When I am trying to print values of array l[] its showing me invalid values.

But when I comment down the line which are providing values in array r[] from a[] the values of array l[] are then showing correct values.

I am providing input values 1 2 3 ... 10 and the output is comming 7 8 9 10 5 but when i comment lines which are providing values to arrar r[] the output is correct 1 2 3 4 5.

Why is this happening ?

#include <iostream>

using namespace std;

int main()
{
    int a[10], l[6], r[6],m = 0,n = 0;

    for(int i=0;i<10;i++)
        cin>>a[i];

    for(int i=0;i<5;i++)
        l[i] = a[i];

    for(int i=5;i<10;i++)
        r[i] = a[i];

    //l[6] = r[6] = 1e9;

    for(int i=0;i<5;i++)
        cout<<l[i];

    return 0;
}

Body:
Here's your code:

for(int i=0;i<10;i++)
    cin>>a[i];  // this one looks OK

for(int i=0;i<5;i++)
    l[i] = a[i];  // this one looks OK too

for(int i=5;i<10;i++)
    r[i] = a[i];  // you access 'r' beyond 5 that damages other vars


问:
EBUSY: resource busy or locked, unlink
Sometimes when I try to launch the angular-cli command :

```<code>ng build --app myApplication -w
</code>```

I get the following error :

```<code>EBUSY: resource busy or locked, unlink 'C:\...\inline.bundle.js'
</code>```

Any idea to overcome this problem?

答:
I had the same problem with google-services.json when trying to deploy the app to the device.

EBUSY: resource busy or locked, unlink 'C:\...\google-services.json'

Solution:
Open task manager on windows and kill the Java(TM) Platform SE Binary  process in task manager.

Title: EBUSY: resource busy or locked, unlink

Body:
Sometimes when I try to launch the angular-cli command :

ng build --app myApplication -w

I get the following error :

EBUSY: resource busy or locked, unlink 'C:\...\inline.bundle.js'

Any idea to overcome this problem?


问:
Why isn't this R script sorting through the matrix like I think it's supposed to?
I'm new to R so I don't know all the ins and outs of it yet, but I think the code should work. It's supposed to look through a matrix of people with different heights, weights, and income levels read from a .csv file, then remove any rows that have any value as NA or that have any value not within a certain given range (e.g. 4.5 to 6.5 for height). When I run the script some people are removed but there are still people with NA values or values outside of the given ranges, so I don't know if it's removing only a certain amount of the people that don't fit or if it's removing the wrong people completely, or both.</p>

```<code>original = read.csv("C:/Users/gsbal/OneDrive/Documents/Quants R Course/HW/A2-C-DirtyData.csv")

nums = 1:nrow(original)
toDelete = 0
deleted = 0
for (i in nums)
{
  na = is.na(original[i, 1]) | is.na(original[i, 2]) | is.na(original[i, 3])
  if (na == T)
  {
    toDelete = i - deleted
    original = original[-toDelete,]
    deleted = deleted + 1
  }
}

nums = 1:nrow(original)
toDelete = 0
deleted = 0
for (i in nums)
{
  height = original[i, 1] < 4.5 | original[i, 1] > 6.5
  if (height == T)
  {
    toDelete = i - deleted
    original = original[-toDelete,]
    deleted = deleted + 1
  }
}
</code>```

答:
One of the great strengths of R is that it works on columns of data, rather than individual values.  So you should be able to do all that you want to do without resorting to loops.  I recommend tidyverse as a package that will almost always be helpful.  It is, in the words of its developers, "opinionated" - and it is - but it's also very good.

Unfortunately, you haven't given us a simple self-contained example, so I can't test my code, but something like this should remove any row of your data with an NA in any column.  [See this post if you'd like to know more about simple self-contained examples and reprexes.]

```<code>library(tidyverse)

modified <- original %>% drop_na()
</code>```

How simple was that?  You can implement your range checks in a similar way:

```<code>modifiedAgain <- modified %>% filter(height < 4.5 | height > 6.5)
</code>```

Body:
I'm new to R so I don't know all the ins and outs of it yet, but I think the code should work. It's supposed to look through a matrix of people with different heights, weights, and income levels read from a .csv file, then remove any rows that have any value as NA or that have any value not within a certain given range (e.g. 4.5 to 6.5 for height). When I run the script some people are removed but there are still people with NA values or values outside of the given ranges, so I don't know if it's removing only a certain amount of the people that don't fit or if it's removing the wrong people completely, or both.

original = read.csv("C:/Users/gsbal/OneDrive/Documents/Quants R Course/HW/A2-C-DirtyData.csv")

nums = 1:nrow(original)
toDelete = 0
deleted = 0
for (i in nums)
{
  na = is.na(original[i, 1]) | is.na(original[i, 2]) | is.na(original[i, 3])
  if (na == T)
  {
    toDelete = i - deleted
    original = original[-toDelete,]
    deleted = deleted + 1
  }
}

nums = 1:nrow(original)
toDelete = 0
deleted = 0
for (i in nums)
{
  height = original[i, 1] < 4.5 | original[i, 1] > 6.5
  if (height == T)
  {
    toDelete = i - deleted
    original = original[-toDelete,]
    deleted = deleted + 1
  }
}

Body:
One of the great strengths of R is that it works on columns of data, rather than individual values.  So you should be able to do all that you want to do without resorting to loops.  I recommend tidyverse as a package that will almost always be helpful.  It is, in the words of its developers, "opinionated" - and it is - but it's also very good.

Unfortunately, you haven't given us a simple self-contained example, so I can't test my code, but something like this should remove any row of your data with an NA in any column.  [See this post if you'd like to know more about simple self-contained examples and reprexes.]

library(tidyverse)

modified <- original %>% drop_na()

How simple was that?  You can implement your range checks in a similar way:

modifiedAgain <- modified %>% filter(height < 4.5 | height > 6.5)


问:
Is there a ip2location conversion for Microsoft SQL Server?
I am really interested in ip2location, because it is implemented in a way that I have all the data in my database, with no external lookup (YAY!).

However, ip2location is built on mysql + php.  I'm in the Microsoft world, with asp.net, SQL Server and WPF/Winforms.

I'm looking for a conversion of ip2location for .NET, which is basically just the SQL Server portion.

Any converted project out there?  If so, link or someone I can contact?

EDIT:
Someone should build something like this which is native to SQL Server.  The core requirement is to not rely on an external service, be fast, and give some level of accuracy to country (or closest server when no country is available).

答:
Looks like the schema and bulk import fmt files are located here:  link

There is also a .csv file that appears to be dataset you are interested in posted here link


问:
cant seem to get enable-migrations working Successfully installed but not added
I am nw to Entity Framework and ASP.NEt in general..i have instaled EF and when i write  enable-migrations i get following line No context type was found in the assembly 'Demogorgon'.

I have tried to
1. instal and uninstal EF
2. Made sure that i have selected the right project as default (easy there is only one in the dropdown)
3. used for instalation of EF Console or Manage nugets
4. i am ofc reading answers here and elsewhere but since i am quite new to this i am not how to proceed

```<code>   Attempting to gather dependency information for package 'EntityFramework.6.4.4' with respect to project 'Demogorgon', targeting '.NETFramework,Version=v4.7.2'
    Gathering dependency information took 1.14 sec
    Attempting to resolve dependencies for package 'EntityFramework.6.4.4' with DependencyBehavior 'Lowest'
    Resolving dependency information took 0 ms
    Resolving actions to install package 'EntityFramework.6.4.4'
    Resolved actions to install package 'EntityFramework.6.4.4'
    Retrieving package 'EntityFramework 6.4.4' from 'nuget.org'.
    Adding package 'EntityFramework.6.4.4' to folder 'C:\Users\novot\source\repos\Demogorgon\packages'
    Added package 'EntityFramework.6.4.4' to folder 'C:\Users\novot\source\repos\Demogorgon\packages'
    Added package 'EntityFramework.6.4.4' to 'packages.config'
    **Successfully installed 'EntityFramework 6.4.4' to Demogorgon**
    Executing nuget actions took 1.49 sec
    Time Elapsed: 00:00:02.7731151
    PM> Enable-Migrations
    No context type was found in the assembly 'Demogorgon'.
    PM> enable-migrations
    No context type was found in the assembly 'Demogorgon'.
    PM>
</code>```

答: Make sure that in Package Manager Console(Default project drop-down option) you have selected the correct project(the project where your DBContext class is), and try again</p>

Body:
I am nw to Entity Framework and ASP.NEt in general..i have instaled EF and when i write  enable-migrations i get following line No context type was found in the assembly 'Demogorgon'.

I have tried to
1. instal and uninstal EF
2. Made sure that i have selected the right project as default (easy there is only one in the dropdown)
3. used for instalation of EF Console or Manage nugets
4. i am ofc reading answers here and elsewhere but since i am quite new to this i am not how to proceed

   Attempting to gather dependency information for package 'EntityFramework.6.4.4' with respect to project 'Demogorgon', targeting '.NETFramework,Version=v4.7.2'
    Gathering dependency information took 1.14 sec
    Attempting to resolve dependencies for package 'EntityFramework.6.4.4' with DependencyBehavior 'Lowest'
    Resolving dependency information took 0 ms
    Resolving actions to install package 'EntityFramework.6.4.4'
    Resolved actions to install package 'EntityFramework.6.4.4'
    Retrieving package 'EntityFramework 6.4.4' from 'nuget.org'.
    Adding package 'EntityFramework.6.4.4' to folder 'C:\Users\novot\source\repos\Demogorgon\packages'
    Added package 'EntityFramework.6.4.4' to folder 'C:\Users\novot\source\repos\Demogorgon\packages'
    Added package 'EntityFramework.6.4.4' to 'packages.config'
    **Successfully installed 'EntityFramework 6.4.4' to Demogorgon**
    Executing nuget actions took 1.49 sec
    Time Elapsed: 00:00:02.7731151
    PM> Enable-Migrations
    No context type was found in the assembly 'Demogorgon'.
    PM> enable-migrations
    No context type was found in the assembly 'Demogorgon'.
    PM>


问:
How to convert column of strings into sequential numbers in Pandas?
I have a column in a df that is full of strings like like ["1120", "2230", "1120", "1234" ...]
where not every value in this column is unique.

I want to convert these strings into SEQUENTIAL NUMBERS from 0 to N where N is the number of unique values in that column so that I can make a scatterplot with this data. Simply changing the type of the column is not sufficient for this task. Any guidance is much appreciated. I tried using dummy variables, but don't really know where to start.

答:
You can hack this - I am not good enough to give you a pure pandas implementation, but this might work:

```<code>import pandas as pd

# prepare demo df
df = pd.DataFrame({"nums" : ["1120", "2230", "1120", "1234","9999","9"]})

# map(int, ...) needed for numeric sorting instead of lexicographical sorting
s = {str(v):i for i,v in enumerate(sorted(set(map(int, df["nums"]))))}

df["ReIndex"] = [s[key] for key in df["nums"]]
print(df)
</code>```

Output:

```<code>   nums  ReIndex
0  1120        1
1  2230        3
2  1120        1
3  1234        2
4  9999        4
5     9        0
</code>```

You can del df["nums"] and df.rename(columns = {'ReIndex':'nums'}, inplace = True) to get the numbers to be what you need them to be.

Body:
You can hack this - I am not good enough to give you a pure pandas implementation, but this might work:

import pandas as pd

# prepare demo df
df = pd.DataFrame({"nums" : ["1120", "2230", "1120", "1234","9999","9"]})

# map(int, ...) needed for numeric sorting instead of lexicographical sorting
s = {str(v):i for i,v in enumerate(sorted(set(map(int, df["nums"]))))}

df["ReIndex"] = [s[key] for key in df["nums"]]
print(df)

Output:

   nums  ReIndex
0  1120        1
1  2230        3
2  1120        1
3  1234        2
4  9999        4
5     9        0

You can del df["nums"] and df.rename(columns = {'ReIndex':'nums'}, inplace = True) to get the numbers to be what you need them to be.


问:
java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20
Im doing a thing for a thing and I have to "Multiply each element in list2 by its element index number and place the value in array list1."
and so my code is

```<code>public static void main(String[] args) {
        int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
        int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
        int L1= 0;
        int L2= 0;

        for( L2=0 ;L2<List2.length;L2++) {
            List2[L2]= (int) (100*Math.random());
            System.out.print(" "+List2[L2]);
        }//end of list2 for loop

System.out.println("");

        for( L1 = 0;L1<List1.length;L1++)
        {
            List1[L1]= List2[L2]*L2;
            System.out.print(" "+List1[L1]);
        }//end of list1 for loop
)
</code>```

and it throws this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20"

答: Your List1 actually contains 21 elements (mind the last ",", which adds another element) while List2 contains only 20. So, in the second loop, you're iterating 21 times, and when you get to the 21st, List2 contains no more elements.</p>

Body:
Im doing a thing for a thing and I have to "Multiply each element in list2 by its element index number and place the value in array list1."
and so my code is

public static void main(String[] args) {
        int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
        int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
        int L1= 0;
        int L2= 0;

        for( L2=0 ;L2<List2.length;L2++) {
            List2[L2]= (int) (100*Math.random());
            System.out.print(" "+List2[L2]);
        }//end of list2 for loop

System.out.println("");

        for( L1 = 0;L1<List1.length;L1++)
        {
            List1[L1]= List2[L2]*L2;
            System.out.print(" "+List1[L1]);
        }//end of list1 for loop
)

and it throws this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20"


问:
TFF : TypeError while saving model
Please I need Help!
After writing my code of TFF, I would like to save my model So I add this line in the end of code

```<code>ckpt_manager = checkpoint_manager.FileCheckpointManager("model.h5")
ckpt_manager.save_checkpoint(state, round_num=1)

</code>```

The error was:

```<code>TypeError: To be compatible with tf.contrib.eager.defun, Python functions must return zero or more Tensors; in compilation of <function FileCheckpointManager.save_checkpoint.<locals>.<lambda> at 0x7f06b40de730>, found return value of type <class 'tensorflow_federated.python.common_libs.anonymous_tuple.AnonymousTuple'>, which is not a Tensor.
</code>```

答:
The FileCheckpointManager uses pure TensorFlow API under the hood, and hence doesn't understand TFF's AnonymousTuple type used for structured data.

It will be necessary to convert the AnonymousTuple back into the Python structure it was created from. This can sometimes be done via the _asdict() method on the AnonymousTuple, but that will fail if the tuple has any unnamed fields. Otherwise, performing something like from_tff_result method here will be necessary.

Title: TFF : TypeError while saving model

Body:
Please I need Help!
After writing my code of TFF, I would like to save my model So I add this line in the end of code

ckpt_manager = checkpoint_manager.FileCheckpointManager("model.h5")
ckpt_manager.save_checkpoint(state, round_num=1)

The error was:

TypeError: To be compatible with tf.contrib.eager.defun, Python functions must return zero or more Tensors; in compilation of <function FileCheckpointManager.save_checkpoint.<locals>.<lambda> at 0x7f06b40de730>, found return value of type <class 'tensorflow_federated.python.common_libs.anonymous_tuple.AnonymousTuple'>, which is not a Tensor.


问:
Checking for duplicate data in SQL Server
Please don't ask me why but there is a lot of duplicate data where every field is duplicated.

For example

```<code>alex, 1
alex, 1
liza, 32
hary, 34
</code>```

I will need to eliminate from this table one of the alex, 1 rows

I know this algorithm will be very ineffecient, but it does not matter. I will need to remove duplicate data.

What is the best way to do this? Please keep in mind I do not have 2 fields, I actually have about 10 fields to check on.

答:
As you said, yes this will be very inefficient, but you can try something like</p>

```<code>DECLARE @TestTable TABLE(
        Name VARCHAR(20),
        SomeVal INT
)
INSERT INTO @TestTable SELECT 'alex', 1
INSERT INTO @TestTable SELECT 'alex', 1
INSERT INTO @TestTable SELECT 'liza', 32
INSERT INTO @TestTable SELECT 'hary', 34

SELECT  *
FROM    @TestTable

;WITH DuplicateVals AS (
    SELECT  *,
            ROW_NUMBER() OVER (PARTITION BY Name, SomeVal ORDER BY (SELECT NULL)) RowID
    FROM    @TestTable
)
DELETE FROM DuplicateVals WHERE RowID > 1

SELECT *
FROM    @TestTable
</code>```

Body:
Please don't ask me why but there is a lot of duplicate data where every field is duplicated.

For example

alex, 1
alex, 1
liza, 32
hary, 34

I will need to eliminate from this table one of the alex, 1 rows

I know this algorithm will be very ineffecient, but it does not matter. I will need to remove duplicate data.

What is the best way to do this? Please keep in mind I do not have 2 fields, I actually have about 10 fields to check on.

Body:
As you said, yes this will be very inefficient, but you can try something like

DECLARE @TestTable TABLE(
        Name VARCHAR(20),
        SomeVal INT
)
INSERT INTO @TestTable SELECT 'alex', 1
INSERT INTO @TestTable SELECT 'alex', 1
INSERT INTO @TestTable SELECT 'liza', 32
INSERT INTO @TestTable SELECT 'hary', 34

SELECT  *
FROM    @TestTable

;WITH DuplicateVals AS (
    SELECT  *,
            ROW_NUMBER() OVER (PARTITION BY Name, SomeVal ORDER BY (SELECT NULL)) RowID
    FROM    @TestTable
)
DELETE FROM DuplicateVals WHERE RowID > 1

SELECT *
FROM    @TestTable


答:
Your first list has 21 elements, your second list has 20 elements. In your second loop you access the 21 element of the second list. So you get the exception.

notice the comma at the end of your declaration of List1:

```<code>int List1 [] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
int List2 [] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
</code>```

You probably wanted to do the following:

```<code>int List1 [] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int List2 [] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
</code>```

But looking at your code - if you just want to initialize an array with empty values you just can do

```<code>int[] list = new int[20];
</code>```

And you got other problems in your code. After your first loop L2 will always be the size of List2 (20). So in your second loop in List1[L1] = List2[L2] * L2; you are accessing the element at index 20 of List2 - that doesn't exist, because at size=20 your maximum index is 19.

So - I don't know what you try to achieve with your code, but it won't work this way.

Title: java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20

Body:
Your first list has 21 elements, your second list has 20 elements. In your second loop you access the 21 element of the second list. So you get the exception.

notice the comma at the end of your declaration of List1:

int List1 [] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
int List2 [] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

You probably wanted to do the following:

int List1 [] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int List2 [] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

But looking at your code - if you just want to initialize an array with empty values you just can do

int[] list = new int[20];

And you got other problems in your code. After your first loop L2 will always be the size of List2 (20). So in your second loop in List1[L1] = List2[L2] * L2; you are accessing the element at index 20 of List2 - that doesn't exist, because at size=20 your maximum index is 19.

So - I don't know what you try to achieve with your code, but it won't work this way.


问:
can't upload DataFrame with NaN with DolphinDB python api
While I was trying to upload some data to dolphindb server using python api, I found that dolphindb server will refuse to accept it and throw an exception if my dataframe contains null values. The following code could reproduce this.

import dolphindb as ddb
import numpy as np
import pandas as pd

df = pd.DataFrame({"a": ["a", np.NaN]})
sess = ddb.Session()
sess.connect('localhost', 9921)
sess.upload({"t", df})
sess.run("1")

```

<p>The error msg is as follows</p>

``` <Server Exception> in upload: Failed to read response header from the socket with IO error type 1
```

How to solve this problem?

答: The code looks good. Tested working fine. Please double check if you connect to the server properly or If the session is timed out. Otherwise, it could be a feature that had not been implemented at the time of question being raised. </p>

Body:
While I was trying to upload some data to dolphindb server using python api, I found that dolphindb server will refuse to accept it and throw an exception if my dataframe contains null values. The following code could reproduce this.

import dolphindb as ddb
import numpy as np
import pandas as pd

df = pd.DataFrame({"a": ["a", np.NaN]})
sess = ddb.Session()
sess.connect('localhost', 9921)
sess.upload({"t", df})
sess.run("1")

The error msg is as follows

 <Server Exception> in upload: Failed to read response header from the socket with IO error type 1

How to solve this problem?


问:
Referring to `this` vue component within an event handler
Given this Vue component that attaches a global event listener:

```<code>var app = new Vue({
    data: {
        foo: 0;
    },
    methods: {
        handle: function(e) {
            this.foo = 1; // this refers to handler, not app
        }
    },
    mounted: function() {
        window.addEventListener("keypress", this.handle);
    }
});
</code>```

What is the correct way to refer to this from within the event handler in order to update the component state? Alternatively, is there a better way to set event handlers on the entire window?

答:
Actually this is binded to the vue instance and your code works fine.

var app = new Vue({
    el: "#app",
    data: {
        foo: 0
    },
    methods: {
        handle: function(e) {
            this.foo++;
            console.log(this.foo);
        }
    },
    mounted: function() {
        window.addEventListener("keypress", this.handle);
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
{{ foo }}
</div></code>```

The common mistake is if you have for example an function with an callback and you try to use this inside the callback, it will be undefined

```<code>    handle: function(e) {
        this.foo++;
        setTimeout(function(){
           console.log(this.foo); //undefined
        })
        console.log(this.foo);
    }
</code>```

You could either use arrow functions

```<code>    handle: function(e) {
        this.foo++;
        setTimeout(() =>{
           console.log(this.foo);
        })
        console.log(this.foo);
    }
},
</code>```

Or if its need to be backwards compatible you could use .bind()

```<code>    handle: function(e) {
        this.foo++;
        setTimeout(function(){
           console.log(this.foo);
        }.bind(this))
        console.log(this.foo);
    }
},
</code>```

Body:
Given this Vue component that attaches a global event listener:

var app = new Vue({
    data: {
        foo: 0;
    },
    methods: {
        handle: function(e) {
            this.foo = 1; // this refers to handler, not app
        }
    },
    mounted: function() {
        window.addEventListener("keypress", this.handle);
    }
});

What is the correct way to refer to this from within the event handler in order to update the component state? Alternatively, is there a better way to set event handlers on the entire window?

Body:
Actually this is binded to the vue instance and your code works fine.

var app = new Vue({
    el: "#app",
    data: {
        foo: 0
    },
    methods: {
        handle: function(e) {
            this.foo++;
            console.log(this.foo);
        }
    },
    mounted: function() {
        window.addEventListener("keypress", this.handle);
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
{{ foo }}
</div>

The common mistake is if you have for example an function with an callback and you try to use this inside the callback, it will be undefined

    handle: function(e) {
        this.foo++;
        setTimeout(function(){
           console.log(this.foo); //undefined
        })
        console.log(this.foo);
    }

You could either use arrow functions

    handle: function(e) {
        this.foo++;
        setTimeout(() =>{
           console.log(this.foo);
        })
        console.log(this.foo);
    }
},

Or if its need to be backwards compatible you could use .bind()

    handle: function(e) {
        this.foo++;
        setTimeout(function(){
           console.log(this.foo);
        }.bind(this))
        console.log(this.foo);
    }
},


问:
How can we receive notification for deleted non series-master recurring event using Microsoft Graph API?
I've subscribed to the user's calendar but when one/few of the recurring event(s) in the calendar is removed, then I just received notification for the series-master event along with all other events which are part of the recurrence.

Is there some way to determine the removed events?

答: We don't get deleted notification when one/a few of the recurrent events get deleted. We need to fetch all occurrences of the event using recurrent master and then find the ones that got deleted if we had our previous entries stored in a persistent location.</p>


问:
To retrieve specific data from multiple similar portions in a .json file
A part of json file's content as below:

```<code>{"ID": "PK45", "People": "Kate", "Date": "2020-01-05"}, {"ID": "OI85", "People": "John", "Date": "2020-01-18" }, {"ID": "CN658", "People": "Pevo", "Date": "2020-02-01" }
</code>```

It has multiple portions containing "ID", "People" and "Date".

What I want to do is to retrieve John's ID (in this case "OI85". )

If the key is unique, I can use:

```<code>data_content = json.loads(data)
ID = data_content['ID']
</code>```

But there are multiple similar portions. So I can only locate the "John" first:

```<code>with open("C:\\the_file.json") as data_file:
    data = data_file.read()
    where = data.find('John')
    where_1 = data[where - 20 : where]
    ID = where_1[where_1.find('ID')+3:where_1.find('ID')+7]
    print (ID)
</code>```

It looked clumsy.

What will be the smart json way to retrieve the specific data from multiple similar portions in a .json file?

Thank you.

答:
You probably should use the json module, which makes the task trivial:

import json

with open('data.json') as f:
    records = json.load(f)

for record in records:
    if record['People'] == 'John':
        print(record['ID'])
        break
```

Body:
A part of json file's content as below:

{"ID": "PK45", "People": "Kate", "Date": "2020-01-05"}, {"ID": "OI85", "People": "John", "Date": "2020-01-18" }, {"ID": "CN658", "People": "Pevo", "Date": "2020-02-01" }

It has multiple portions containing "ID", "People" and "Date".

What I want to do is to retrieve John's ID (in this case "OI85". )

If the key is unique, I can use:

data_content = json.loads(data)
ID = data_content['ID']

But there are multiple similar portions. So I can only locate the "John" first:

with open("C:\\the_file.json") as data_file:
    data = data_file.read()
    where = data.find('John')
    where_1 = data[where - 20 : where]
    ID = where_1[where_1.find('ID')+3:where_1.find('ID')+7]
    print (ID)

It looked clumsy.

What will be the smart json way to retrieve the specific data from multiple similar portions in a .json file?

Thank you.


问:
Preventing the jqTree UI from displaying the option to drop into node for some nodes
I have the following:

```<code>    $('#sidebar-tree').tree({
        data: data,
        autoOpen: false,
        dragAndDrop: true,
        selectable: false,
        closedIcon: $('<i class="fas fa-angle-up"></i>'),
        openedIcon: $('<i class="fas fa-angle-down"></i>')
    })
</code>```

Though for some nodes, I'd like to allow the user to reorder them (so dragging the node between nodes is cool) but I want to prevent the user from dropping them into other nodes. Is there a way to configure this "permitted behavior" per node?

Note: this has been asked on GitHub here: https://github.com/mbraak/jqTree/issues/598

答:
You can use the onCanMoveTo option: https://mbraak.github.io/jqTree/#options-oncanmoveto

I think the onCanMoveTo should look like this (not tested it):

```<code>onCanMoveTo: function(moved_node, target_node, position) {
  return position !== 'inside';
}
</code>```

Body:
I have the following:

    $('#sidebar-tree').tree({
        data: data,
        autoOpen: false,
        dragAndDrop: true,
        selectable: false,
        closedIcon: $(''),
        openedIcon: $('')
    })

Though for some nodes, I'd like to allow the user to reorder them (so dragging the node between nodes is cool) but I want to prevent the user from dropping them into other nodes. Is there a way to configure this "permitted behavior" per node?

Note: this has been asked on GitHub here: https://github.com/mbraak/jqTree/issues/598

Body:
You can use the onCanMoveTo option: https://mbraak.github.io/jqTree/#options-oncanmoveto

I think the onCanMoveTo should look like this (not tested it):

onCanMoveTo: function(moved_node, target_node, position) {
  return position !== 'inside';
}