问:
RegEx for a conditional pattern in a string
I need to extract substrings from some strings,for example:
My data is a vector: c("Shigella dysenteriae","PREDICTED: Ceratitis")

```<code>a = "Shigella dysenteriae"

b = "PREDICTED: Ceratitis"
</code>```

I hope that if the string starts with "PREDICTED:", it can be extracted to the subsequent word(maybe "Ceratitis"), and if the string doesn't start with "PREDICTED", it can be extracted to the first word(maybe Shigella);

In this example, the result would be:

```<code>result_of_a = "Shigella"

result_of_b = "Ceratitis"
</code>```

Well,it is a typical conditional regular expression.I tried,but always failed;

I used R which can compatible perl's regular expression.

I know R supports perl's regular expression so I tried to use regexpr and regmatches, two functions to extract the substrings that I want.

The code  is :

```<code>
pattern = "(?<=PREDICTED:)?(?(1)(\\s+\\w+\\b)|(\\w+\\b))"

a = c("Shigella dysenteriae")
m_a = regexpr(pattern,a,perl = TRUE)
result_a = regmatches(a,m_a)

b = c("PREDICTED: Ceratitis")
m_b = regexpr(pattern,a,perl = TRUE)
result_b = regmatches(b,m_b)
</code>```

Finaly,the result is :

```<code># result_a = "Shigella"
# result_b = "PREDICTED"
</code>```

It is not the result I expect,result_a is right,result_b is wrong.

WHY???Its seem that the condition didn't work...

PS:
   I tried to read some details of conditional reg-expresstion. this is the web I tried to read : https://www.regular-expressions.info/conditional.html and I try to imitate "pattern" from this web ,and also tried to use "RegexBuddy" software to find the reason.

答:
I think the reason it does not work is because (1) checks if a numbered capture group has been set but there is no first capturing group set yet, also not in the positive lookbehind (?<=PREDICTED:)?.

There are a first and second capturing group in the parts that follow. The if clause will check for group 1, it is not set so it will match group 2.

If you would make it the only capturing group (?<=(PREDICTED: )?) and omit the other 2 then the if clause will be true but you will get an error because the lookbehind assertion is not fixed length.

Instead of using a conditional pattern, to get both words you might use a capturing group and make PREDICTED: optional:

```<code>^(?:PREDICTED: )?(\w+)
</code>```

Regex demo | R demo

Body:
I need to extract substrings from some strings,for example:
My data is a vector: c("Shigella dysenteriae","PREDICTED: Ceratitis")

a = "Shigella dysenteriae"

b = "PREDICTED: Ceratitis"

I hope that if the string starts with "PREDICTED:", it can be extracted to the subsequent word(maybe "Ceratitis"), and if the string doesn't start with "PREDICTED", it can be extracted to the first word(maybe Shigella);

In this example, the result would be:

result_of_a = "Shigella"

result_of_b = "Ceratitis"

Well,it is a typical conditional regular expression.I tried,but always failed;

I used R which can compatible perl's regular expression.

I know R supports perl's regular expression so I tried to use regexpr and regmatches, two functions to extract the substrings that I want.

The code  is :

pattern = "(?<=PREDICTED:)?(?(1)(\\s+\\w+\\b)|(\\w+\\b))"

a = c("Shigella dysenteriae")
m_a = regexpr(pattern,a,perl = TRUE)
result_a = regmatches(a,m_a)

b = c("PREDICTED: Ceratitis")
m_b = regexpr(pattern,a,perl = TRUE)
result_b = regmatches(b,m_b)

Finaly,the result is :

# result_a = "Shigella"
# result_b = "PREDICTED"

It is not the result I expect,result_a is right,result_b is wrong.

WHY???Its seem that the condition didn't work...

PS:
   I tried to read some details of conditional reg-expresstion. this is the web I tried to read : https://www.regular-expressions.info/conditional.html and I try to imitate "pattern" from this web ,and also tried to use "RegexBuddy" software to find the reason.

Body:
I think the reason it does not work is because (1) checks if a numbered capture group has been set but there is no first capturing group set yet, also not in the positive lookbehind (?<=PREDICTED:)?.

There are a first and second capturing group in the parts that follow. The if clause will check for group 1, it is not set so it will match group 2.

If you would make it the only capturing group (?<=(PREDICTED: )?) and omit the other 2 then the if clause will be true but you will get an error because the lookbehind assertion is not fixed length.

Instead of using a conditional pattern, to get both words you might use a capturing group and make PREDICTED: optional:

^(?:PREDICTED: )?(\w+)

Regex demo | R demo


来源: stackexchange

问:
How to remove an empty lines while exporting the text files?
```<code>DEFINE VARIABLE cExportData AS CHARACTER NO-UNDO FORMAT 'X(250)'.
DEFINE VARIABLE cPath AS CHARACTER NO-UNDO.
DEFINE VARIABLE cExt  AS CHARACTER NO-UNDO.
DEFINE VARIABLE cSFTL AS CHARACTER NO-UNDO FORMAT 'X(150)'.
DEFINE VARIABLE cMessageDateTime AS CHARACTER NO-UNDO.

ASSIGN
      cPath  = "R:\Downloads\progress\".
      cExt   = ".Txt".
      cMessageDateTime = "123456789".

OUTPUT TO VALUE (cPath + cMessageDateTime + STRING(MTIME) + cExt ).

     cExportData = "Data1" + CHR(10) + "Data2" + CHR(10) + "Data3" + CHR(10) + "END.".
     MESSAGE  cExportData.

OUTPUT TO CLOSE.
</code>```

So when I see exported text file using notepad++ i could see first 3 for Data1,Data2,Data3 but 4th line is created with empty.How do I stop creating empty line.

答:
MESSAGE is not usually what you want to use for output to a file, it has many extra behaviors specific to interacting with users in the context of providing error messages etc.  PUT is generally more appropriate for writing files.  Embedding CHR(10) is also not a good idea -- that is a very OS specific line terminator.  CHR(10) is a Unix style newline but you are clearly running on Windows (which uses CHR(10) + CHR(13).

I might re-write your code as follows:

```<code>DEFINE VARIABLE cExportData AS CHARACTER NO-UNDO FORMAT 'X(250)'.
DEFINE VARIABLE cPath AS CHARACTER NO-UNDO.
DEFINE VARIABLE cExt  AS CHARACTER NO-UNDO.
DEFINE VARIABLE cSFTL AS CHARACTER NO-UNDO FORMAT 'X(150)'.
DEFINE VARIABLE cMessageDateTime AS CHARACTER NO-UNDO.

/* the "." that you had at the ends of the ASSIGN sub statements
 * is turning it into 3 distinct statements, not one as your
 * indentation shows
 */

ASSIGN
  cPath  = "R:\Downloads\progress\"
  cExt   = ".Txt"
  cMessageDateTime = "123456789"
. /* end the ASSIGN statement */

/* if you are using MTIME because you imagine it will make your
 * filename unique then you are mistaken, on a multi-user or
 * networked system it is trivial for 2 processes to create files
 * at the very same MTIME
 */

OUTPUT TO VALUE (cPath + cMessageDateTime + STRING(MTIME) + cExt ).

/* usually some kind of looping structure would output each line
 * building the whole output by concatenating into a string will
 * eventually exhaust memory.
 */

put unformatted "Data1" skip "Data2" skip "Data3" skip "End." skip.

/* the final SKIP might not be needed - it is unclear to me
 * if that is a problem for your client
 */

/* as originally written this creates
 * an empty file called "CLOSE"
 */

OUTPUT /*** TO ***/ CLOSE.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
DEFINE VARIABLE cExportData AS CHARACTER NO-UNDO FORMAT 'X(250)'.
DEFINE VARIABLE cPath AS CHARACTER NO-UNDO.
DEFINE VARIABLE cExt  AS CHARACTER NO-UNDO.
DEFINE VARIABLE cSFTL AS CHARACTER NO-UNDO FORMAT 'X(150)'.
DEFINE VARIABLE cMessageDateTime AS CHARACTER NO-UNDO.

ASSIGN
      cPath  = "R:\Downloads\progress\".
      cExt   = ".Txt".
      cMessageDateTime = "123456789".

OUTPUT TO VALUE (cPath + cMessageDateTime + STRING(MTIME) + cExt ).

     cExportData = "Data1" + CHR(10) + "Data2" + CHR(10) + "Data3" + CHR(10) + "END.".
     MESSAGE  cExportData.

OUTPUT TO CLOSE.

So when I see exported text file using notepad++ i could see first 3 for Data1,Data2,Data3 but 4th line is created with empty.How do I stop creating empty line.

Body:
MESSAGE is not usually what you want to use for output to a file, it has many extra behaviors specific to interacting with users in the context of providing error messages etc.  PUT is generally more appropriate for writing files.  Embedding CHR(10) is also not a good idea -- that is a very OS specific line terminator.  CHR(10) is a Unix style newline but you are clearly running on Windows (which uses CHR(10) + CHR(13).

I might re-write your code as follows:

DEFINE VARIABLE cExportData AS CHARACTER NO-UNDO FORMAT 'X(250)'.
DEFINE VARIABLE cPath AS CHARACTER NO-UNDO.
DEFINE VARIABLE cExt  AS CHARACTER NO-UNDO.
DEFINE VARIABLE cSFTL AS CHARACTER NO-UNDO FORMAT 'X(150)'.
DEFINE VARIABLE cMessageDateTime AS CHARACTER NO-UNDO.

/* the "." that you had at the ends of the ASSIGN sub statements
 * is turning it into 3 distinct statements, not one as your
 * indentation shows
 */

ASSIGN
  cPath  = "R:\Downloads\progress\"
  cExt   = ".Txt"
  cMessageDateTime = "123456789"
. /* end the ASSIGN statement */

/* if you are using MTIME because you imagine it will make your
 * filename unique then you are mistaken, on a multi-user or
 * networked system it is trivial for 2 processes to create files
 * at the very same MTIME
 */

OUTPUT TO VALUE (cPath + cMessageDateTime + STRING(MTIME) + cExt ).

/* usually some kind of looping structure would output each line
 * building the whole output by concatenating into a string will
 * eventually exhaust memory.
 */

put unformatted "Data1" skip "Data2" skip "Data3" skip "End." skip.

/* the final SKIP might not be needed - it is unclear to me
 * if that is a problem for your client
 */

/* as originally written this creates
 * an empty file called "CLOSE"
 */

OUTPUT /*** TO ***/ CLOSE.


问:
bootstrap conflict hamburger menu display
Why bootstrap  has conflict with hamburger menu display?

Hamburger menus open and close button is on left, but when I add bootstrap css line, hamburger close button float to right position!
and when I remove that line is okey.
How Should I Fix This?

Code:

function openNavbar () {
 document.querySelector("#navbar").style.width="100%";
 document.querySelectorAll(".open")[0].style.opacity = 0;
}
function closeNavbar () {
 document.querySelector("#navbar").style.width="0";
 document.querySelectorAll(".open")[0].style.opacity = 1;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
 padding: 0;
 margin: 0;
 box-sizing: border-box;
}

html,body{
 width: 100%;
 height: 100%;
 background: url("https://images.pexels.com/photos/1096658/pexels-photo-1096658.jpeg?auto=compress&cs=tinysrgb&h=650&w=940") center/cover no-repeat;
 font: bold 1rem Consolas;
}

.open, .close{
 display: inline-block;
 padding:30px 0 0 30px;
 cursor: pointer;
 font-size:2rem;
 color:#fff;
 text-decoration: none;
 transition: .5s;
}

.overlay{
 position: fixed;
 width: 0;
 top: 0;
 background-color: #333;
 opacity: .7;
 overflow-x: hidden;
 height: 100%;
 transition: .5s;
}

.overlay-content{
 text-align: center;
 position: relative;
 width: 100%;
 padding-top: 50px;
 margin-top: 30px;
}

.overlay-content a {
 font-size: 2rem;
 color:#fff;
 display: block;
 padding:10px;
 margin-bottom: 4px;
 text-decoration: none;
 transition: .3s;
 position: relative;

}
.overlay-content a:after{
 content: "";
 position: absolute;
    bottom: 0;
    left: 50%;
    width: 0%;
    transform: translateX(-50%);
    height: 3px;
    background:#fff;
    transition: .3s;
    display: block;

}
.overlay-content a:hover{
 color:#ff9f1a;
}

.overlay-content a:hover:after{
 width: 25%;
}</code>```

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

        ☰ Menu

        ⛌

        Home
        Portfolio
        Services
        About
        Contact

```

答:
If you want to keep your close button on the left when the menu is open, you will have to set float: none; to prevent the default float: right; set by the close class helper from bootstrap (more infos here).

So at your a link, apply style="float:none;" like so :

⛌

or you can use bootstrap's float-none helper like this :

⛌ and the close button will remain on the left.

Example below :

function openNavbar () {
 document.querySelector("#navbar").style.width="100%";
 document.querySelectorAll(".open")[0].style.opacity = 0;
}
function closeNavbar () {
 document.querySelector("#navbar").style.width="0";
 document.querySelectorAll(".open")[0].style.opacity = 1;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
 padding: 0;
 margin: 0;
 box-sizing: border-box;
}

html,body{
 width: 100%;
 height: 100%;
 background: url("https://images.pexels.com/photos/1096658/pexels-photo-1096658.jpeg?auto=compress&cs=tinysrgb&h=650&w=940") center/cover no-repeat;
 font: bold 1rem Consolas;
}

.open, .close{
 display: inline-block;
 padding:30px 0 0 30px;
 cursor: pointer;
 font-size:2rem;
 color:#fff;
 text-decoration: none;
 transition: .5s;
}

.overlay{
 position: fixed;
 width: 0;
 top: 0;
 background-color: #333;
 opacity: .7;
 overflow-x: hidden;
 height: 100%;
 transition: .5s;
}

.overlay-content{
 text-align: center;
 position: relative;
 width: 100%;
 padding-top: 50px;
 margin-top: 30px;
}

.overlay-content a {
 font-size: 2rem;
 color:#fff;
 display: block;
 padding:10px;
 margin-bottom: 4px;
 text-decoration: none;
 transition: .3s;
 position: relative;

}
.overlay-content a:after{
 content: "";
 position: absolute;
    bottom: 0;
    left: 50%;
    width: 0%;
    transform: translateX(-50%);
    height: 3px;
    background:#fff;
    transition: .3s;
    display: block;

}
.overlay-content a:hover{
 color:#ff9f1a;
}

.overlay-content a:hover:after{
 width: 25%;
}</code>```

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

        ☰ Menu

        ⛌

        Home
        Portfolio
        Services
        About
        Contact

```

Body:
Why bootstrap  has conflict with hamburger menu display?

Hamburger menus open and close button is on left, but when I add bootstrap css line, hamburger close button float to right position!
and when I remove that line is okey.
How Should I Fix This?

Code:

function openNavbar () {
 document.querySelector("#navbar").style.width="100%";
 document.querySelectorAll(".open")[0].style.opacity = 0;
}
function closeNavbar () {
 document.querySelector("#navbar").style.width="0";
 document.querySelectorAll(".open")[0].style.opacity = 1;
}

*{
 padding: 0;
 margin: 0;
 box-sizing: border-box;
}

html,body{
 width: 100%;
 height: 100%;
 background: url("https://images.pexels.com/photos/1096658/pexels-photo-1096658.jpeg?auto=compress&cs=tinysrgb&h=650&w=940") center/cover no-repeat;
 font: bold 1rem Consolas;
}

.open, .close{
 display: inline-block;
 padding:30px 0 0 30px;
 cursor: pointer;
 font-size:2rem;
 color:#fff;
 text-decoration: none;
 transition: .5s;
}

.overlay{
 position: fixed;
 width: 0;
 top: 0;
 background-color: #333;
 opacity: .7;
 overflow-x: hidden;
 height: 100%;
 transition: .5s;
}

.overlay-content{
 text-align: center;
 position: relative;
 width: 100%;
 padding-top: 50px;
 margin-top: 30px;
}

.overlay-content a {
 font-size: 2rem;
 color:#fff;
 display: block;
 padding:10px;
 margin-bottom: 4px;
 text-decoration: none;
 transition: .3s;
 position: relative;

}
.overlay-content a:after{
 content: "";
 position: absolute;
    bottom: 0;
    left: 50%;
    width: 0%;
    transform: translateX(-50%);
    height: 3px;
    background:#fff;
    transition: .3s;
    display: block;

}
.overlay-content a:hover{
 color:#ff9f1a;
}

.overlay-content a:hover:after{
 width: 25%;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

        ☰ Menu

        ⛌

        Home
        Portfolio
        Services
        About
        Contact

Body:
If you want to keep your close button on the left when the menu is open, you will have to set float: none; to prevent the default float: right; set by the close class helper from bootstrap (more infos here).

So at your a link, apply style="float:none;" like so :

<a style="float:none;" href="javascript:void(0);" onclick="closeNavbar()" class="close">&#9932;</a>

or you can use bootstrap's float-none helper like this :

<a href="javascript:void(0);" onclick="closeNavbar()" class="close float-none">&#9932;</a> and the close button will remain on the left.

Example below :

function openNavbar () {
 document.querySelector("#navbar").style.width="100%";
 document.querySelectorAll(".open")[0].style.opacity = 0;
}
function closeNavbar () {
 document.querySelector("#navbar").style.width="0";
 document.querySelectorAll(".open")[0].style.opacity = 1;
}

*{
 padding: 0;
 margin: 0;
 box-sizing: border-box;
}

html,body{
 width: 100%;
 height: 100%;
 background: url("https://images.pexels.com/photos/1096658/pexels-photo-1096658.jpeg?auto=compress&cs=tinysrgb&h=650&w=940") center/cover no-repeat;
 font: bold 1rem Consolas;
}

.open, .close{
 display: inline-block;
 padding:30px 0 0 30px;
 cursor: pointer;
 font-size:2rem;
 color:#fff;
 text-decoration: none;
 transition: .5s;
}

.overlay{
 position: fixed;
 width: 0;
 top: 0;
 background-color: #333;
 opacity: .7;
 overflow-x: hidden;
 height: 100%;
 transition: .5s;
}

.overlay-content{
 text-align: center;
 position: relative;
 width: 100%;
 padding-top: 50px;
 margin-top: 30px;
}

.overlay-content a {
 font-size: 2rem;
 color:#fff;
 display: block;
 padding:10px;
 margin-bottom: 4px;
 text-decoration: none;
 transition: .3s;
 position: relative;

}
.overlay-content a:after{
 content: "";
 position: absolute;
    bottom: 0;
    left: 50%;
    width: 0%;
    transform: translateX(-50%);
    height: 3px;
    background:#fff;
    transition: .3s;
    display: block;

}
.overlay-content a:hover{
 color:#ff9f1a;
}

.overlay-content a:hover:after{
 width: 25%;
}

<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

</head>
<body>

        <span class="open" onclick="openNavbar()">&#9776; Menu</span>
        <div id="navbar" class="overlay">
        <a style="float:none;" href="javascript:void(0);" onclick="closeNavbar()" class="close">&#9932;</a>
        <div class="overlay-content">
        <a href="javascript:void(o);">Home</a>
        <a href="javascript:void(o);">Portfolio</a>
        <a href="javascript:void(o);">Services</a>
        <a href="javascript:void(o);">About</a>
        <a href="javascript:void(o);">Contact</a>
        </div>
        </div>

</body>


问:
Get autocomplete input value to a hidden input Vue.Js
I use https://santiblanko.github.io/vue-instant/ for autocompletion with Vue.

It works as I expected, except I cannot post the value inside the 'input' value to a form.

When I submit the form, the value inside the input is not posted to my backend server.

So that I have to create a hidden value when I submit so that I can read that input value.

How to do this. I just want the form and the value to be submitted as I cick magnifier icon.

https://codepen.io/snarex/pen/vwQjWR

<link rel="stylesheet" type="text/css" href="https://unpkg.com/vue-instant@0.0.10/dist/vue-instant.css">

<form action="https://www.google.com" method="GET">

    {{selectedEvent}}
    <vue-instant :suggestonallwords="true" :suggestion-attribute="suggestionAttribute" v-model="value" :disabled="false" @input="changed" @click-input="clickInput" @click-button="clickButton" @selected="selected" @enter="enter" @key-up="keyUp" @key-down="keyDown"
      @key-right="keyRight" @clear="clear" @escape="escape" :show-autocomplete="true" :autofocus="false" :suggestions="suggestions" name="customName" placeholder="custom placeholder" type="google"></vue-instant>

</form>```

答:
If I understand correctly, you want to post the suggested value to the server inside a form data object? If that's right, you can alter your clickButton method as follows.

```<code>clickButton: function() {
      this.selectedEvent = 'click button';
      var formData = new FormData();
      formData.append("selectedMovie", this.value);
      axios({
        method: 'post',
        url: '/yourapi/endpoint/',
        data: {
          formData:formData
        }
      }).then(function(response) {
        console.log(response.data);
        console.log(response.status);
        console.log(response.statusText);
      });
    }
</code>```

Body:
If I understand correctly, you want to post the suggested value to the server inside a form data object? If that's right, you can alter your clickButton method as follows.

clickButton: function() {
      this.selectedEvent = 'click button';
      var formData = new FormData();
      formData.append("selectedMovie", this.value);
      axios({
        method: 'post',
        url: '/yourapi/endpoint/',
        data: {
          formData:formData
        }
      }).then(function(response) {
        console.log(response.data);
        console.log(response.status);
        console.log(response.statusText);
      });
    }


问:
Sending Bearer Token with HttpPost in Android
I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.

I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on Stackoverflow.

```<code>HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");

try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
</code>```

The error I get is 401 Unauthorized on every attempt.

答:
The "Authorization" should not be a parameter. Its a header.

```<code>HttpPost request = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
byte[] encodedAuth = Base64.encodeBase64(
  auth.getBytes(StandardCharsets.ISO_8859_1));
String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
</code>```

Body:
I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.

I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on Stackoverflow.

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");

try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));

The error I get is 401 Unauthorized on every attempt.

Body:
The "Authorization" should not be a parameter. Its a header.

HttpPost request = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
byte[] encodedAuth = Base64.encodeBase64(
  auth.getBytes(StandardCharsets.ISO_8859_1));
String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);


问:
Why java.lang.IllegalStateException occurs when running Word2VecExample form Scala Spark mllib?
I am trying to read a text file in Spark-mllib examples (Word2VecExample) and create it word vectors. I run it by some text files and it gives no error but when reading one of my files, it gives this error and I am really confuse with that because I tried everything such as file format(utf-8) and ASCII characters.
this is my source code:

```<code>package org.apache.spark.examples.mllib

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
// $example on$
import org.apache.spark.mllib.feature.{Word2Vec, Word2VecModel}
// $example off$

object Word2VecExample {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setAppName("Word2VecExample")
    conf.setMaster("local[4]")
    val sc = new SparkContext(conf)

    val input = sc.textFile("C:\\Users\\...\\Desktop\\yelp_labelled.txt").map(line => line.split(" ").toSeq)

    val word2vec = new Word2Vec()

    val model = word2vec.fit(input)

    val synonyms = model.findSynonyms("1", 5)

    for((synonym, cosineSimilarity) <- synonyms) {
      println(s"$synonym $cosineSimilarity")
    }

    model.save(sc, "C:\\Users\\...\\Desktop\\Edited1Yelp")
    val sameModel = Word2VecModel.load(sc, "C:\\Users\\...\\Edited1Yelp")

    // $example off$

    sc.stop()
  }
}
</code>```

And this is the Error:

```<code>Exception in thread "main" 19/05/29 18:36:29 INFO BlockManagerInfo: Removed broadcast_4_piece0 on DESKTOP-T5EN156:64774 in memory (size: 13.0 KB, free: 2.2 GB)
java.lang.IllegalStateException: 1 not in vocabulary
    at org.apache.spark.mllib.feature.Word2VecModel.transform(Word2Vec.scala:533)
    at org.apache.spark.mllib.feature.Word2VecModel.findSynonyms(Word2Vec.scala:545)
    at org.apache.spark.examples.mllib.Word2VecExample$.main(Word2VecExample.scala:43)
    at org.apache.spark.examples.mllib.Word2VecExample.main(Word2VecExample.scala)
</code>```

And line 43 refers to val synonyms = model.findSynonyms("1", 5) but I'm sure it's true because I run the program correctly with some other files.

答:
Hello don't know much about Spark. Also can't post comments yet so an answer will have to do. Looking at the documention here.

.findSynonyms("string",num)
"Find "num" number of words closest in similarity to the given word, not including the word itself."

So i can't help wondering is looking for the string "1" not maybe the problem. Off the top of my head i struggle to find 5 synonyms for "1", perhaps "one",maybe "uniary" or potentially "individual". From what I read Spark is a machine learning library so have you tried dumbing down the question? Maybe ask for a single synonym or give a simpler string to search for like "happy". This is just my two cents though, and mostly just curious about what is actually happening.

Body:
I am trying to read a text file in Spark-mllib examples (Word2VecExample) and create it word vectors. I run it by some text files and it gives no error but when reading one of my files, it gives this error and I am really confuse with that because I tried everything such as file format(utf-8) and ASCII characters.
this is my source code:

package org.apache.spark.examples.mllib

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
// $example on$
import org.apache.spark.mllib.feature.{Word2Vec, Word2VecModel}
// $example off$

object Word2VecExample {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setAppName("Word2VecExample")
    conf.setMaster("local[4]")
    val sc = new SparkContext(conf)

    val input = sc.textFile("C:\\Users\\...\\Desktop\\yelp_labelled.txt").map(line => line.split(" ").toSeq)

    val word2vec = new Word2Vec()

    val model = word2vec.fit(input)

    val synonyms = model.findSynonyms("1", 5)

    for((synonym, cosineSimilarity) <- synonyms) {
      println(s"$synonym $cosineSimilarity")
    }

    model.save(sc, "C:\\Users\\...\\Desktop\\Edited1Yelp")
    val sameModel = Word2VecModel.load(sc, "C:\\Users\\...\\Edited1Yelp")

    // $example off$

    sc.stop()
  }
}

And this is the Error:

Exception in thread "main" 19/05/29 18:36:29 INFO BlockManagerInfo: Removed broadcast_4_piece0 on DESKTOP-T5EN156:64774 in memory (size: 13.0 KB, free: 2.2 GB)
java.lang.IllegalStateException: 1 not in vocabulary
    at org.apache.spark.mllib.feature.Word2VecModel.transform(Word2Vec.scala:533)
    at org.apache.spark.mllib.feature.Word2VecModel.findSynonyms(Word2Vec.scala:545)
    at org.apache.spark.examples.mllib.Word2VecExample$.main(Word2VecExample.scala:43)
    at org.apache.spark.examples.mllib.Word2VecExample.main(Word2VecExample.scala)

And line 43 refers to val synonyms = model.findSynonyms("1", 5) but I'm sure it's true because I run the program correctly with some other files.


问:
ViewPager missing from com.android.support:support-v4:28.0.0
Does anyone know if ViewPager class has been removed from revision 28 of the support library? Looks like the whole view package is gone.</p>

答:
Please remove implementation

'com.romandanylyk:pageindicatorview:1.0.3@aar'

this library if you  are using this then it is working fine not an any issue.


问:
How does swapping nodes in linked list works?
Below is the code for swapping nodes without changing data. I wonder whether swapping the next pointers of nodes required? Will swapping the current nodes doesn't swap the next pointers? Why?

```<code>    void swapNodes(Node** head_ref, int x, int y)
    {

        // Nothing to do if x and y are same
        if (x == y)
           return;

        Node **a = NULL, **b = NULL;

        // search for x and y in the linked list
        // and store therir pointer in a and b
        while (*head_ref) {

              if ((*head_ref)->data == x) {
                   a = head_ref;
              }

              else if ((*head_ref)->data == y) {
                   b = head_ref;
              }

              head_ref = &((*head_ref)->next);
         }

         // if we have found both a and b
         // in the linked list swap current
         // pointer and next pointer of these
         if (a && b) {

             swap(*a, *b);
             swap(((*a)->next), ((*b)->next));
         }
    }

    void swap(Node*& a, Node*& b)
    {

         Node* temp = a;
         a = b;
         b = temp;
    }
</code>```

Thank You.

答:
Swapping the current nodes won't be enough.

When swapping a and b, their address is changed so their place in the list will be replaced

But you do not change the inner fields of each node.

Nodes Illustraion:

a - b - c - d

Let's take node a and c.

a->next == &b (True)

c->next == &d (True)

If we swap the nodes like this:

c - b - a - d

The address of node c and node a will change, but the list would look the same since their ->next values will not change

If we also swap the ->next values, the list will be really swapped

Body:
Below is the code for swapping nodes without changing data. I wonder whether swapping the next pointers of nodes required? Will swapping the current nodes doesn't swap the next pointers? Why?

    void swapNodes(Node** head_ref, int x, int y)
    {

        // Nothing to do if x and y are same
        if (x == y)
           return;

        Node **a = NULL, **b = NULL;

        // search for x and y in the linked list
        // and store therir pointer in a and b
        while (*head_ref) {

              if ((*head_ref)->data == x) {
                   a = head_ref;
              }

              else if ((*head_ref)->data == y) {
                   b = head_ref;
              }

              head_ref = &((*head_ref)->next);
         }

         // if we have found both a and b
         // in the linked list swap current
         // pointer and next pointer of these
         if (a && b) {

             swap(*a, *b);
             swap(((*a)->next), ((*b)->next));
         }
    }

    void swap(Node*& a, Node*& b)
    {

         Node* temp = a;
         a = b;
         b = temp;
    }

Thank You.


问:
How do you pass an image to a styled component?
I'm using styled-components in ReactJS and I'm trying to create a component that can take in the background-image as a prop. After some research, I've tried this:

```<code>import SpeechBubble1 from '../images/home_images/Speech 1.png';
...

const SpeechBubble = styled.div`
    background-image: url(${props => props.background});
`;

...

<SpeechBubble background={SpeechBubble1} />
</code>```

But it doesn't work. Checking in the browser element window, I can see I'm getting an Invalid property value for background-image.

What am I doing wrong?

Edit:
I also tried doing this, which hasn't worked:

```<code><SpeechBubble style={{background: `url(${SpeechBubble1})`}} />
</code>```

答:
You can use inline styling:</p>

```<code><SpeechBubble style={{background: `url(${SpeechBubble1})`}} />
</code>```

Body:
I'm using styled-components in ReactJS and I'm trying to create a component that can take in the background-image as a prop. After some research, I've tried this:

import SpeechBubble1 from '../images/home_images/Speech 1.png';
...

const SpeechBubble = styled.div`
    background-image: url(${props => props.background});
`;

...

<SpeechBubble background={SpeechBubble1} />

But it doesn't work. Checking in the browser element window, I can see I'm getting an Invalid property value for background-image.

What am I doing wrong?

Edit:
I also tried doing this, which hasn't worked:

<SpeechBubble style={{background: `url(${SpeechBubble1})`}} />

Body:
You can use inline styling:

<SpeechBubble style={{background: `url(${SpeechBubble1})`}} />


问:
Escaping regular expressions inside square brackets
I'm trying to escape a parenthesis inside square brackets.

```<code>$pattern = "/^[a-zA-Z0-9 _-\(]{1,25}$/";
$str = "TEST (ok)";

if (preg_match($pattern, $str)) {
    echo "<br />OK";
} else {
    echo "<br />FAIL";
}
</code>```

This give me the warning:

Warning: preg_match(): Compilation
  failed: range out of order in
  character class at offset 15 in
  /var/www/test.php on line 6

  FAIL

Outside the square brackets the escaping works fine.

Any ideas?

答: You need to escape the hyphen as well...as written, it will match from the underscore (ASCII 95) through the left paren (ASCII 40).</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to escape a parenthesis inside square brackets.

$pattern = "/^[a-zA-Z0-9 _-\(]{1,25}$/";
$str = "TEST (ok)";

if (preg_match($pattern, $str)) {
    echo "
OK";
} else {
    echo "
FAIL";
}

This give me the warning:

Warning: preg_match(): Compilation
  failed: range out of order in
  character class at offset 15 in
  /var/www/test.php on line 6

  FAIL

Outside the square brackets the escaping works fine.

Any ideas?


问:
How do I count the number of records that have one or more associated object?
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

```<code>> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
</code>```

to:

```<code>> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
</code>```

to the more advanced:

```<code>>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
</code>```

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

Body:
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....

to:

> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...

to the more advanced:

>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

Body:
You can try like this, I have done in my projects,

Photo.group(:property_id).count

You will get property id with photos count

results = { 3314=>3, 2033=>3, 3532=>2, 3565=>6, 3510=>1, 3022=>7, 648=>2, 570=>3, 4678=>3, 3540=>1, 3489=>4, 536=>1, 1715=>4 }


问:
Acces violation on va_arg
I am trying to create a function that takes a variable number of matrix in parameters and multiply theses to a first one.
I can read a first one using va_arg, but the next call of va_arg will cause an access violation.

Here is how i declare my method :

```<code>template<class MType>
static CMatrice<MType> COperationsComplexesMatricesPassages::OCPChangementDeBase
   (CMatrice<MType> & MATVecteur, unsigned int uiNbMatricesPassages,
    CMatricePassage<MType> MAPMatrices...)
</code>```

And here is how i call it :

```<code>COperationsComplexesMatricesPassages::OCPChangementDeBase(mat1, 2, matP1, matP2)
</code>```

The exception appears on the first va_arg of the for(...) in the body of my method.
This is the code of my method:

```<code>unsigned int uiIndice;
unsigned int uiBaseArriveePrecedente;

va_list args;
va_start(args, MAPMatrices);

CMatrice<MType> MATResult(MATVecteur);
CMatricePassage<MType> MAPMatricePass = va_arg(args, CMatricePassage<MType>);

MATResult = MATResult * MAPMatricePass;

uiBaseArriveePrecedente = MAPMatricePass.MAPGetBaseArrivee();
for (uiIndice = 1; uiIndice < uiNbMatricesPassages; uiIndice++) {
    CMatricePassage<MType> MAPMatricePass2 = va_arg(args, CMatricePassage<MType>);
    if (uiBaseArriveePrecedente != MAPMatricePass2.MAPGetBaseDepart()) {
        CException EXCError(EXC_ChangementImpossible);
        throw EXCError;
    }
    uiBaseArriveePrecedente = MAPMatricePass2.MAPGetBaseArrivee();
    MATResult = MATResult * MAPMatricePass2;
}

return MATResult;
</code>```

答:
I don't understand what you exactly want obtain from your OCPChangementDeBase() method, anyway... maybe I'm wrong... but it seems to me that there are a couple of important points, regarding variadic functions, that you don't know.

(1) the old C variad syntax

```<code>void foo (int a, int b...)
</code>```

doesn't mean that b is a variadic list of integer.

That declaration is equivalent (the last comma is optional) to

```<code>void foo (int a, int b, ...)
</code>```

so, with both declarations, you have a b integer (a single b integer) and an unnamed list of variadic arguments.

So given you method

```<code>template<class MType>
static CMatrice<MType>
COperationsComplexesMatricesPassages::OCPChangementDeBase
   (CMatrice<MType> & MATVecteur, unsigned int uiNbMatricesPassages,
    CMatricePassage<MType> MAPMatrices...)
</code>```

and calling it

```<code>COperationsComplexesMatricesPassages::OCPChangementDeBase(mat1, 2, matP1, matP2)
</code>```

you have that

MATVecteur become mat1

uiNbMatricesPassages become 2

MAPMatrices become matP1

the unnamed variadic list ... become matP2

So, if you're expecting two arguments in the unnamed varidic list, you have only one and I'm not surprised that "the next call of va_arg will cause an access violation."

(2) the old C variadic syntax (va_list, va_arg, va_start based) remains available in C++ but, as far I know, works only for PODs (Plain Old Data) types.

So, as far I know, your code is UB (undefined bahaviour) because matP2 (I suppose) isn't POD.

Fortunately C++ (starting from C++11) introduce variadic templates that are compatible also with not PODs types.

So, I suppose, you count write your method as follows or something similar

```<code>template <typename MType, typename ... MTs>
static auto COperationsComplexesMatricesPassages::OCPChangementDeBase
   (CMatrice<MType> & MATVecteur, MTs ... MAPMatrices)
 {
   auto MatResult { MatVectour };

   ( MatResult *= MapMatrices, ... ); // template folding; only from C++17

   return MatResult;
 }
</code>```

You can also add some constraints (look for SFINAE) to impose that MTs... types are exactly (or, maybe better, convertible to) CMatricePassage<MType> (or another type, if you want).

Title: Acces violation on va_arg

Body:
I am trying to create a function that takes a variable number of matrix in parameters and multiply theses to a first one.
I can read a first one using va_arg, but the next call of va_arg will cause an access violation.

Here is how i declare my method :

template<class MType>
static CMatrice<MType> COperationsComplexesMatricesPassages::OCPChangementDeBase
   (CMatrice<MType> & MATVecteur, unsigned int uiNbMatricesPassages,
    CMatricePassage<MType> MAPMatrices...)

And here is how i call it :

COperationsComplexesMatricesPassages::OCPChangementDeBase(mat1, 2, matP1, matP2)

The exception appears on the first va_arg of the for(...) in the body of my method.
This is the code of my method:

unsigned int uiIndice;
unsigned int uiBaseArriveePrecedente;

va_list args;
va_start(args, MAPMatrices);

CMatrice<MType> MATResult(MATVecteur);
CMatricePassage<MType> MAPMatricePass = va_arg(args, CMatricePassage<MType>);

MATResult = MATResult * MAPMatricePass;

uiBaseArriveePrecedente = MAPMatricePass.MAPGetBaseArrivee();
for (uiIndice = 1; uiIndice < uiNbMatricesPassages; uiIndice++) {
    CMatricePassage<MType> MAPMatricePass2 = va_arg(args, CMatricePassage<MType>);
    if (uiBaseArriveePrecedente != MAPMatricePass2.MAPGetBaseDepart()) {
        CException EXCError(EXC_ChangementImpossible);
        throw EXCError;
    }
    uiBaseArriveePrecedente = MAPMatricePass2.MAPGetBaseArrivee();
    MATResult = MATResult * MAPMatricePass2;
}

return MATResult;

Body:
I don't understand what you exactly want obtain from your OCPChangementDeBase() method, anyway... maybe I'm wrong... but it seems to me that there are a couple of important points, regarding variadic functions, that you don't know.

(1) the old C variad syntax

void foo (int a, int b...)

doesn't mean that b is a variadic list of integer.

That declaration is equivalent (the last comma is optional) to

void foo (int a, int b, ...)

so, with both declarations, you have a b integer (a single b integer) and an unnamed list of variadic arguments.

So given you method

template<class MType>
static CMatrice<MType>
COperationsComplexesMatricesPassages::OCPChangementDeBase
   (CMatrice<MType> & MATVecteur, unsigned int uiNbMatricesPassages,
    CMatricePassage<MType> MAPMatrices...)

and calling it

COperationsComplexesMatricesPassages::OCPChangementDeBase(mat1, 2, matP1, matP2)

you have that

MATVecteur become mat1

uiNbMatricesPassages become 2

MAPMatrices become matP1

the unnamed variadic list ... become matP2

So, if you're expecting two arguments in the unnamed varidic list, you have only one and I'm not surprised that "the next call of va_arg will cause an access violation."

(2) the old C variadic syntax (va_list, va_arg, va_start based) remains available in C++ but, as far I know, works only for PODs (Plain Old Data) types.

So, as far I know, your code is UB (undefined bahaviour) because matP2 (I suppose) isn't POD.

Fortunately C++ (starting from C++11) introduce variadic templates that are compatible also with not PODs types.

So, I suppose, you count write your method as follows or something similar

template <typename MType, typename ... MTs>
static auto COperationsComplexesMatricesPassages::OCPChangementDeBase
   (CMatrice<MType> & MATVecteur, MTs ... MAPMatrices)
 {
   auto MatResult { MatVectour };

   ( MatResult *= MapMatrices, ... ); // template folding; only from C++17

   return MatResult;
 }

You can also add some constraints (look for SFINAE) to impose that MTs... types are exactly (or, maybe better, convertible to) CMatricePassage<MType> (or another type, if you want).


问:
Dose aws spot market still refund when the spot instance is revoked in its first hour?
As described in the title, I remember before in AWS spot market that if a spot instance is revoked in its first hour, all the charges would be refunded fully. Does this policy still work now?</p>

答:
If the EC2 service terminates or stops the spot instance in the first hour, then you are not charged.

To quote the Spot Instances FAQ:

If your Spot instance is terminated or stopped by Amazon EC2 in the
  first instance hour, you will not be charged for that usage. However,
  if you terminate the instance yourself, you will be charged to the
  nearest second. If the Spot instance is terminated or stopped by
  Amazon EC2 in any subsequent hour, you will be charged for your usage
  to the nearest second. If you are running on Windows and you terminate
  the instance yourself, you will be charged for an entire hour.


问:
How to set a default page in Reporting Server so that a user can land on a certain page with specified filters every time they open a report file?
I am creating PBI reports with multiple pages. My client requirement is that when a user opens a report they should land on a certain page with specified filters. How to achieve such behaviour in Power BI, please?</p>

答: You can create a featured dashboard by using "Set as featured" feature. You can make the report page as set as featured. Hope it helps!</p>


问:
Does the 'S' in SQL stand for "standard" or "structured"?
I'm thinking "structured", but my dad claims that when he taught a class that involved SQL (decades ago), they used "standard".  I was wondering if this changed over time, or is he mistaken?  I googled it with "standard" and did see some pages that said that's what it stands for.  Any old timers willing to give a history lesson?</p>

答:
It stands for Structured.

The precursor was called SEQUEL, standing for Structured English QUEry Language.

From wikipedia:

The acronym SEQUEL was later changed to SQL because "SEQUEL" was a trademark


答:
whether swapping the next pointers of nodes required?

Yes it is required because the original nodes take place in different positions of the list.

Will swapping the current nodes doesn't swap the next pointers?

Yes, swapping current nodes doesn't swap the next pointers. Swapping current nodes means only swapping only pointers that point to the current nodes.

Consider for example the list

```<code>| A |next B| -> | B |next C| -> | C |next D| -> | D |next nullptr|
</code>```

and let's assume that you need to swap nodes B and D. Then you'll get

```<code>                   ---------------------
                   |                    |
| A |next D| ... | B |next C| -> | C |next B| ... | D |next nullptr|
       |                                            |
       ----------------------------------------------
</code>```

So after the first swapping the node A points to node D but node D "points" to nullptr. Nodes B and C will be lost if not to swap their data members next.

Thus you need also to swap their data members next

```<code>                   --------------------------
                   |                        |
| A |next D| ... | B |next nullptr|   | C |next B| ... | D |next C|
       |                                                 |
       ---------------------------------------------------
</code>```

and as result you'll get

```<code>| A |next D| -> | D |next C| -> | C |next B| -> | B |next nullptr|
</code>```

Title: How does swapping nodes in linked list works?

Body:
whether swapping the next pointers of nodes required?

Yes it is required because the original nodes take place in different positions of the list.

Will swapping the current nodes doesn't swap the next pointers?

Yes, swapping current nodes doesn't swap the next pointers. Swapping current nodes means only swapping only pointers that point to the current nodes.

Consider for example the list

| A |next B| -> | B |next C| -> | C |next D| -> | D |next nullptr|

and let's assume that you need to swap nodes B and D. Then you'll get

                   ---------------------
                   |                    |
| A |next D| ... | B |next C| -> | C |next B| ... | D |next nullptr|
       |                                            |
       ----------------------------------------------

So after the first swapping the node A points to node D but node D "points" to nullptr. Nodes B and C will be lost if not to swap their data members next.

Thus you need also to swap their data members next

                   --------------------------
                   |                        |
| A |next D| ... | B |next nullptr|   | C |next B| ... | D |next C|
       |                                                 |
       ---------------------------------------------------

and as result you'll get

| A |next D| -> | D |next C| -> | C |next B| -> | B |next nullptr|


问:
CSS3 animation make a stop delay between frames
I'm trying to animate my logo using css, what I want is each logo fade in from top then stop in a certain point, then fade out to bottom, but couldn't make this, is this possible?

.logo {
    width: 50px;
    height: 50px;
    background: whitesmoke;
    transform: rotate(45deg);
    position: absolute;
    border-radius: 5px;
    border: 2px solid white;
}

#logo {
    width: 500px;
    height: 500px;
    margin: auto;
    margin-top: 100px;
    position: relative;
}

#logo-1 {
    top: 0px;
    animation: loading3 4s linear infinite normal;
}

#logo-2 {
    top: -10px;
    animation: loading2 3s linear infinite normal;
}

#logo-3 {
    top: -20px;
    animation: loading1 2s linear infinite normal;
}

@keyframes loading1 {
  0% {background: white;opacity: 0;top: -120px;}
  50% {background:#f44;opacity: 1;top: -50px;}
  65% {background:#f44;opacity: 1;top: -20px;}
  75% {background:#f44;opacity: 1;top: -20px;}
  100% {background: white;opacity: 0;top: 50px;}
}

@keyframes loading2 {
  0% {background: white;opacity: 0;top: -120px;}
  50% {background:#f44;opacity: 1;top: -50px;}
  65% {background:#f44;opacity: 1;top: -10px;}
  75% {background:#f44;opacity: 1;top: -10px;}
  100% {background: white;opacity: 0;top: 50px;}
}

@keyframes loading3 {
  0% {background: white;opacity: 0;top: -120px;}
  50% {background:#f44;opacity: 1;top: -50px;}
  65% {background:#f44;opacity: 1;top: 0px;}
  75% {background:#f44;opacity: 1;top: 0px;}
  100% {background: white;opacity: 0;top: 50px;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <div class="logo" id="logo-1"></div>
  <div class="logo" id="logo-2"></div>
  <div class="logo" id="logo-3"></div>
</div></code>```

Note: logo-3 should come first and stop, then logo-2 come and stop,
  then logo-1 come and stop then logo-3 should go first, then logo-2
  then logo-1, one by one.

Original logo is:

答:
There is no way to stop a CSS animation in-between and then continue, hence i have used little JavaScript.

What we do is, we divide all three animations into two portions, the first one for all three runs and then the second one. I have divided animations and then activate those animations using classes with JavaScript. This solution is not complex, it's just lengthy.

function animateLogo() {
    logo1 = document.getElementById('logo-1');
    logo2 = document.getElementById('logo-2');
    logo3 = document.getElementById('logo-3');

    if(logo1.classList.contains('anim31')) {
       logo1.classList.remove('anim31');
       logo1.classList.add('anim32');
    } else {
        logo1.classList.add('anim31');
        logo1.classList.remove('anim32');
    }

    if(logo2.classList.contains('anim21')) {
       logo2.classList.remove('anim21');
       logo2.classList.add('anim22');
    } else {
        logo2.classList.add('anim21');
        logo2.classList.remove('anim22');
    }

    if(logo3.classList.contains('anim11')) {
       logo3.classList.remove('anim11');
       logo3.classList.add('anim12');
    } else {
        logo3.classList.add('anim11');
        logo3.classList.remove('anim12');
    }

}

setInterval(animateLogo, 3000); // The time is the amount of milliseconds our longest animation will take i.e 3s```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.logo {
    width: 50px;
    height: 50px;
    background: whitesmoke;
    transform: rotate(45deg);
    position: absolute;
    border-radius: 5px;
    border: 2px solid white;
}

#logo {
    width: 500px;
    height: 500px;
    margin: auto;
    margin-top: 100px;
    position: relative;
}

#logo-1 {
    top: 0px;
}

#logo-1.anim31 {
    animation: loading31 3s linear forwards normal;
}

#logo-1.anim32 {
    animation: loading32 1s linear forwards normal;
}

@keyframes loading31 {
    0% {
        background: white;
        opacity: 0;
        top: -120px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -50px;
    }
    75% {
        top: -50px;
    }
    100% {
        background: #f44;
        opacity: 1;
        top: 0px;
    }
}

@keyframes loading32 {
    0% {
        background: #f44;
        opacity: 1;
        top: 0px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: 0px;
    }
    100% {
        background: white;
        opacity: 0;
        top: 50px;
    }
}

#logo-2 {
    top: -10px;
}

#logo-2.anim21 {
    animation: loading21 2s linear forwards normal;
}

#logo-2.anim22 {
    animation: loading22 2s linear forwards normal;
}

@keyframes loading21 {
    0% {
        background: white;
        opacity: 0;
        top: -120px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -50px;
    }
    75% {
        top: -50px;
    }
    100% {
        background: #f44;
        opacity: 1;
        top: -10px;
    }
}

@keyframes loading22 {
    0% {
        background: #f44;
        opacity: 1;
        top: -10px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -10px;
    }
    100% {
        background: white;
        opacity: 0;
        top: 50px;
    }
}

#logo-3 {
    top: -20px;
}

#logo-3.anim11 {
    animation: loading11 1s linear forwards normal;
}

#logo-3.anim12 {
    animation: loading12 3s linear forwards normal;
}

@keyframes loading11 {
    0% {
        background: white;
        opacity: 0;
        top: -120px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -50px;
    }
    75% {
        top: -50px;
    }
    100% {
        background: #f44;
        opacity: 1;
        top: -20px;
    }
}

@keyframes loading12 {
    0% {
        background: #f44;
        opacity: 1;
        top: -20px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -20px;
    }
    100% {
        background: white;
        opacity: 0;
        top: 50px;
    }
}</code>```

```

I hope this is the expected result. If not, please comment below and i will edit the answer.

P.S: Play around with the timing of animations to make it faster/slower.

Body:
I'm trying to animate my logo using css, what I want is each logo fade in from top then stop in a certain point, then fade out to bottom, but couldn't make this, is this possible?

.logo {
    width: 50px;
    height: 50px;
    background: whitesmoke;
    transform: rotate(45deg);
    position: absolute;
    border-radius: 5px;
    border: 2px solid white;
}

#logo {
    width: 500px;
    height: 500px;
    margin: auto;
    margin-top: 100px;
    position: relative;
}

#logo-1 {
    top: 0px;
    animation: loading3 4s linear infinite normal;
}

#logo-2 {
    top: -10px;
    animation: loading2 3s linear infinite normal;
}

#logo-3 {
    top: -20px;
    animation: loading1 2s linear infinite normal;
}

@keyframes loading1 {
  0% {background: white;opacity: 0;top: -120px;}
  50% {background:#f44;opacity: 1;top: -50px;}
  65% {background:#f44;opacity: 1;top: -20px;}
  75% {background:#f44;opacity: 1;top: -20px;}
  100% {background: white;opacity: 0;top: 50px;}
}

@keyframes loading2 {
  0% {background: white;opacity: 0;top: -120px;}
  50% {background:#f44;opacity: 1;top: -50px;}
  65% {background:#f44;opacity: 1;top: -10px;}
  75% {background:#f44;opacity: 1;top: -10px;}
  100% {background: white;opacity: 0;top: 50px;}
}

@keyframes loading3 {
  0% {background: white;opacity: 0;top: -120px;}
  50% {background:#f44;opacity: 1;top: -50px;}
  65% {background:#f44;opacity: 1;top: 0px;}
  75% {background:#f44;opacity: 1;top: 0px;}
  100% {background: white;opacity: 0;top: 50px;}
}

Note: logo-3 should come first and stop, then logo-2 come and stop,
  then logo-1 come and stop then logo-3 should go first, then logo-2
  then logo-1, one by one.

Original logo is:

Body:
There is no way to stop a CSS animation in-between and then continue, hence i have used little JavaScript.

What we do is, we divide all three animations into two portions, the first one for all three runs and then the second one. I have divided animations and then activate those animations using classes with JavaScript. This solution is not complex, it's just lengthy.

function animateLogo() {
    logo1 = document.getElementById('logo-1');
    logo2 = document.getElementById('logo-2');
    logo3 = document.getElementById('logo-3');

    if(logo1.classList.contains('anim31')) {
       logo1.classList.remove('anim31');
       logo1.classList.add('anim32');
    } else {
        logo1.classList.add('anim31');
        logo1.classList.remove('anim32');
    }

    if(logo2.classList.contains('anim21')) {
       logo2.classList.remove('anim21');
       logo2.classList.add('anim22');
    } else {
        logo2.classList.add('anim21');
        logo2.classList.remove('anim22');
    }

    if(logo3.classList.contains('anim11')) {
       logo3.classList.remove('anim11');
       logo3.classList.add('anim12');
    } else {
        logo3.classList.add('anim11');
        logo3.classList.remove('anim12');
    }

}

setInterval(animateLogo, 3000); // The time is the amount of milliseconds our longest animation will take i.e 3s

.logo {
    width: 50px;
    height: 50px;
    background: whitesmoke;
    transform: rotate(45deg);
    position: absolute;
    border-radius: 5px;
    border: 2px solid white;
}

#logo {
    width: 500px;
    height: 500px;
    margin: auto;
    margin-top: 100px;
    position: relative;
}

#logo-1 {
    top: 0px;
}

#logo-1.anim31 {
    animation: loading31 3s linear forwards normal;
}

#logo-1.anim32 {
    animation: loading32 1s linear forwards normal;
}

@keyframes loading31 {
    0% {
        background: white;
        opacity: 0;
        top: -120px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -50px;
    }
    75% {
        top: -50px;
    }
    100% {
        background: #f44;
        opacity: 1;
        top: 0px;
    }
}

@keyframes loading32 {
    0% {
        background: #f44;
        opacity: 1;
        top: 0px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: 0px;
    }
    100% {
        background: white;
        opacity: 0;
        top: 50px;
    }
}

#logo-2 {
    top: -10px;
}

#logo-2.anim21 {
    animation: loading21 2s linear forwards normal;
}

#logo-2.anim22 {
    animation: loading22 2s linear forwards normal;
}

@keyframes loading21 {
    0% {
        background: white;
        opacity: 0;
        top: -120px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -50px;
    }
    75% {
        top: -50px;
    }
    100% {
        background: #f44;
        opacity: 1;
        top: -10px;
    }
}

@keyframes loading22 {
    0% {
        background: #f44;
        opacity: 1;
        top: -10px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -10px;
    }
    100% {
        background: white;
        opacity: 0;
        top: 50px;
    }
}

#logo-3 {
    top: -20px;
}

#logo-3.anim11 {
    animation: loading11 1s linear forwards normal;
}

#logo-3.anim12 {
    animation: loading12 3s linear forwards normal;
}

@keyframes loading11 {
    0% {
        background: white;
        opacity: 0;
        top: -120px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -50px;
    }
    75% {
        top: -50px;
    }
    100% {
        background: #f44;
        opacity: 1;
        top: -20px;
    }
}

@keyframes loading12 {
    0% {
        background: #f44;
        opacity: 1;
        top: -20px;
    }
    65% {
        background: #f44;
        opacity: 1;
        top: -20px;
    }
    100% {
        background: white;
        opacity: 0;
        top: 50px;
    }
}

<body>
    <div id="logo">
        <div class="logo anim31" id="logo-1"></div>
        <div class="logo anim21" id="logo-2"></div>
        <div class="logo anim11" id="logo-3"></div>
    </div>
</body>

I hope this is the expected result. If not, please comment below and i will edit the answer.

P.S: Play around with the timing of animations to make it faster/slower.


问:
How to wait untill Observable Observer is created
I'm trying to build messaging system with Observable. My code look like this, pretty simple.
But I has slide problem, sometimes method newMessage calls before storageObserver is created, and I'm getting this error

Cannot read property 'next' of null

```<code>  private storageObserver: any;
  public storage: any;

  constructor(private auth: AuthenticationService, private http: HttpClient)
  {
    this.storage = Observable.create(observer => {
      this.storageObserver = observer;
    });
  }

  newMessage(message: any) {
    this.storageObserver.next(message);
  }
</code>```

Obviously I can check in newMessage like this

```<code>newMessage(message: any) {
    if(this.storageObserver == null) {
      setTimeout(() => {
         this.storageObserver.next(message);
      }, 500)
    } else {
      this.storageObserver.next(message);
    }
}
</code>```

But I don't really like this type of hacks. Is any proper way to wait till observer is created?

答:
I suspect you want to be able to 'feed' the observable manually, for as long as you want, but there is another approach to do that.

I prefer to write it like this:

```<code>private storageSubject: Subject<any>;

constructor(private auth: AuthenticationService, private http: HttpClient) {
    this.storageSubject = new Subject<any>();
    this.storage$ = this.storageSubject.asObservable();
}

// This is a public observable that can be subscribed to.
// Do not forget to unsubscribe.
storage$: Observable<any>;

newMessage(message: any) {
    this.storageSubject.next(message);
}
</code>```

StackBlitz example

Note: If you want the observable to have an initial value, you can use BehaviorSubject<any>. It will always give the last value immediately after subscribtion, which can be more useful if you want the value to have some form of state.

Body:
I'm trying to build messaging system with Observable. My code look like this, pretty simple.
But I has slide problem, sometimes method newMessage calls before storageObserver is created, and I'm getting this error

Cannot read property 'next' of null

  private storageObserver: any;
  public storage: any;

  constructor(private auth: AuthenticationService, private http: HttpClient)
  {
    this.storage = Observable.create(observer => {
      this.storageObserver = observer;
    });
  }

  newMessage(message: any) {
    this.storageObserver.next(message);
  }

Obviously I can check in newMessage like this

newMessage(message: any) {
    if(this.storageObserver == null) {
      setTimeout(() => {
         this.storageObserver.next(message);
      }, 500)
    } else {
      this.storageObserver.next(message);
    }
}

But I don't really like this type of hacks. Is any proper way to wait till observer is created?

Body:
I suspect you want to be able to 'feed' the observable manually, for as long as you want, but there is another approach to do that.

I prefer to write it like this:

private storageSubject: Subject<any>;

constructor(private auth: AuthenticationService, private http: HttpClient) {
    this.storageSubject = new Subject<any>();
    this.storage$ = this.storageSubject.asObservable();
}

// This is a public observable that can be subscribed to.
// Do not forget to unsubscribe.
storage$: Observable<any>;

newMessage(message: any) {
    this.storageSubject.next(message);
}

StackBlitz example

Note: If you want the observable to have an initial value, you can use BehaviorSubject<any>. It will always give the last value immediately after subscribtion, which can be more useful if you want the value to have some form of state.


问:
Check if a new Activity is started with Espresso by click on view
I have a button when click on this, start activity A.

```<code> startActivityForResult(Intent(this, A::class.java)
</code>```

I need to check in an esspresso test when click on the button, start activity A or not?

```<code>onView(withId(R.id.button))
       .check(matches(isDisplayed()))
       .check(matches(isEnabled()))
       .perform(click())

        // check is this A Activity start or not?
</code>```

答:
You can use espresso-intents package.

First, try to add the latest version into your build.gradle:

```<code>   androidTestImplementation "androidx.test.espresso:espresso-intents:3.1.1"
</code>```

Then, use IntentsTestRule to check whether your intent is started or not:

```<code>    @get:Rule
    val intentRule = IntentsTestRule(MainActivity::class.java)

    @Test
    fun verify_FakeActivity_is_started() {
        onView(withId(R.id.button))
            .check(matches(isDisplayed()))
            .check(matches(isEnabled()))
            .perform(click())

        intended(hasComponent(FakeActivity::class.java.name))
    }
</code>```

Body:
I have a button when click on this, start activity A.

 startActivityForResult(Intent(this, A::class.java)

I need to check in an esspresso test when click on the button, start activity A or not?

onView(withId(R.id.button))
       .check(matches(isDisplayed()))
       .check(matches(isEnabled()))
       .perform(click())

        // check is this A Activity start or not?

Body:
You can use espresso-intents package.

First, try to add the latest version into your build.gradle:

   androidTestImplementation "androidx.test.espresso:espresso-intents:3.1.1"

Then, use IntentsTestRule to check whether your intent is started or not:

    @get:Rule
    val intentRule = IntentsTestRule(MainActivity::class.java)

    @Test
    fun verify_FakeActivity_is_started() {
        onView(withId(R.id.button))
            .check(matches(isDisplayed()))
            .check(matches(isEnabled()))
            .perform(click())

        intended(hasComponent(FakeActivity::class.java.name))
    }


问:
Display button doesn't show anything even if I did everything correctly (I think)
I never worked with WPF or designing interfaces. I have been learning C# for a while and now I'm trying to make a program for school. We had to build a console project, but I'm trying to build one in WPF so I learn something new today.

I've read some tutorials and websites and that's how I think it is working. But when I click on Calculate, nothing happens.

For now I've begin by displaying the input from that text. After that I have to do the real programming, extracting the a,b numbers from the input, etc.

But for now I want to display the text so I know it works.

Here is the code:

```<code><Window x:Class="mate.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:mate"
    mc:Ignorable="d"
    Title="Calculator radacini" Height="450" Width="800">
<Grid>
    <TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="Calculator radacini - Octavian Niculescu, 11C" VerticalAlignment="Top" FontFamily="Proxima Nova Alt Rg"/>
    <TextBlock HorizontalAlignment="Center" Margin="0,50,0,0" TextWrapping="Wrap" Text="f:[a, b] -> R, f(x) = ln x - x + 2" VerticalAlignment="Top" FontFamily="Proxima Nova Alt Rg"/>
    <Image x:Name="grafic_functie" HorizontalAlignment="Center" Height="205" VerticalAlignment="Center" Width="343" Source="Untitled.png"/>
    <TextBox x:Name="input" HorizontalAlignment="Center" Height="20" TextWrapping="Wrap" Text="Introdu a, b, intregi" VerticalAlignment="Top" Width="120" Margin="0,71,0,0" FontFamily="Proxima Nova Alt Rg"/>
    <Button HorizontalAlignment="Center" Content="Calculeaza radacinile!" Margin="0,0,0,45" VerticalAlignment="Bottom" Width="155" FontFamily="Proxima Nova Alt Rg"/>
</Grid>
</code>```

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace mate
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string str;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            str = input.Text;
            MessageBox.Show(str);
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}
</code>```

Why does pressing on that button doesn't display anything?
Thanks.

答: You must add Click = "Button_Click" event to your button tag too.

Body:
I never worked with WPF or designing interfaces. I have been learning C# for a while and now I'm trying to make a program for school. We had to build a console project, but I'm trying to build one in WPF so I learn something new today.

I've read some tutorials and websites and that's how I think it is working. But when I click on Calculate, nothing happens.

For now I've begin by displaying the input from that text. After that I have to do the real programming, extracting the a,b numbers from the input, etc.

But for now I want to display the text so I know it works.

Here is the code:

<Window x:Class="mate.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:mate"
    mc:Ignorable="d"
    Title="Calculator radacini" Height="450" Width="800">
<Grid>
    <TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" Text="Calculator radacini - Octavian Niculescu, 11C" VerticalAlignment="Top" FontFamily="Proxima Nova Alt Rg"/>
    <TextBlock HorizontalAlignment="Center" Margin="0,50,0,0" TextWrapping="Wrap" Text="f:[a, b] -> R, f(x) = ln x - x + 2" VerticalAlignment="Top" FontFamily="Proxima Nova Alt Rg"/>
    <Image x:Name="grafic_functie" HorizontalAlignment="Center" Height="205" VerticalAlignment="Center" Width="343" Source="Untitled.png"/>
    <TextBox x:Name="input" HorizontalAlignment="Center" Height="20" TextWrapping="Wrap" Text="Introdu a, b, intregi" VerticalAlignment="Top" Width="120" Margin="0,71,0,0" FontFamily="Proxima Nova Alt Rg"/>
    <Button HorizontalAlignment="Center" Content="Calculeaza radacinile!" Margin="0,0,0,45" VerticalAlignment="Bottom" Width="155" FontFamily="Proxima Nova Alt Rg"/>
</Grid>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace mate
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        string str;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            str = input.Text;
            MessageBox.Show(str);
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}

Why does pressing on that button doesn't display anything?
Thanks.


问:
Installing pgAdmin on Ubuntu - not working
I wanted to install PGAdmin on my Ubuntu 16.04.  I used the following steps from a youtube tutorial (https://www.youtube.com/watch?v=p6_aDUMVsug):

Install virtual environment and required packages:

```<code> 1) sudo apt-get install build-essential libssl-dev libffi-dev python-dev libgmp3-dev
 2) sudo apt-get install virtualenv python-pip libpq-dev python-dev
 3) cd opt
 4) mkdir environmentpy
 5) cd environmentpy
 6  virtualenv pgadmin4
 7) cd pgadmin4
 8) source bin/activate
</code>```

Download and install PGadmin4:

```<code>9) wget https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v1.3/pip/pgadmin4-1.3-py2.py3-none-any.whl
10) sudo pip install pgadmin4-1.3-py2.py3-none-any.whl
11) cd lib/python2.7/site-packages/pgadmin4
12) touch config_local.py
</code>```

Configuration:

```<code>13) echo “SERVER_MODE = False” >> /lib/python2.7/site-packages/pgadmin4/config_local.py
14) python pgAdmin4.py
</code>```

Apparently something went wrong around step 9 or 10 because when I tried to change dir, like step 11, it said "No such file or directory" (which is true).

Some errors are:

A) flask-babel 0.11.1 has requirement Babel>=2.3, but you'll have babel 1.3 which is incompatible.

B) testtools 2.3.0 has requirement extras>=1.0.0, but you'll have extras 0.0.3 which is incompatible.

After running 'pip install pgadmin4-1.3-py2.py3-none-any.whl' :

C) Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/opt/environmentpy/pgadmin4/lib/python2.7/site-packages/pytz-2014.10.dist-info'
Consider using the --user option or check the permissions.

For error C, I used sudo which gives me:

The directory '/home/user/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/user/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement 'pgadmin4-1.3-py2.py3-none-any.whl' looks like a filename, but the file does not exist.

I have tried other ways to fix it too, but I know is already a large explanation. I just want to have PGAdmin installed correctly and working.  If someone know an efficient way to do it, I will appreciate the help.  If I have to un-install and install again in a different way, please let me know the steps.

答:
Use these following commands, this will solve the error:

sudo apt-get install postgresql

sudo apt-get install python-psycopg2

sudo apt-get install libpq-dev

A)For error: flask-babel 0.11.1 has requirement Babel>=2.3, but you'll have babel 1.3 which is incompatible.

pip install flask-htmlmin

For Error: testtools 2.3.0 has requirement extras>=1.0.0, but you'll have extras 0.0.3 which is incompatible.

enter:

wget https://files.pythonhosted.org/packages/03/e9/e915af1f97914cd0bc21e125fd1bfd4106de614a275e4b6866d9ac/extras-1.00-py2.py3-none-any.whl

Body:
I wanted to install PGAdmin on my Ubuntu 16.04.  I used the following steps from a youtube tutorial (https://www.youtube.com/watch?v=p6_aDUMVsug):

Install virtual environment and required packages:

 1) sudo apt-get install build-essential libssl-dev libffi-dev python-dev libgmp3-dev
 2) sudo apt-get install virtualenv python-pip libpq-dev python-dev
 3) cd opt
 4) mkdir environmentpy
 5) cd environmentpy
 6  virtualenv pgadmin4
 7) cd pgadmin4
 8) source bin/activate

Download and install PGadmin4:

9) wget https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v1.3/pip/pgadmin4-1.3-py2.py3-none-any.whl
10) sudo pip install pgadmin4-1.3-py2.py3-none-any.whl
11) cd lib/python2.7/site-packages/pgadmin4
12) touch config_local.py

Configuration:

13) echo “SERVER_MODE = False” >> /lib/python2.7/site-packages/pgadmin4/config_local.py
14) python pgAdmin4.py

Apparently something went wrong around step 9 or 10 because when I tried to change dir, like step 11, it said "No such file or directory" (which is true).

Some errors are:

A) flask-babel 0.11.1 has requirement Babel>=2.3, but you'll have babel 1.3 which is incompatible.

B) testtools 2.3.0 has requirement extras>=1.0.0, but you'll have extras 0.0.3 which is incompatible.

After running 'pip install pgadmin4-1.3-py2.py3-none-any.whl' :

C) Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/opt/environmentpy/pgadmin4/lib/python2.7/site-packages/pytz-2014.10.dist-info'
Consider using the --user option or check the permissions.

For error C, I used sudo which gives me:

The directory '/home/user/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/user/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement 'pgadmin4-1.3-py2.py3-none-any.whl' looks like a filename, but the file does not exist.

I have tried other ways to fix it too, but I know is already a large explanation. I just want to have PGAdmin installed correctly and working.  If someone know an efficient way to do it, I will appreciate the help.  If I have to un-install and install again in a different way, please let me know the steps.


问:
how to display all the days between 2 dates in PHP
I want to display all the day of date between 2 dates

```<code>echo "<tr>";
echo "<td>" . $i++ . "</td>";
echo "<td>" . $row['instructorname'] . "</td>";
echo "<td>" . $row['batchname'] . "</td>";
echo '<td>'; for($i=$startdate;$i<=$todate;$i++){ echo $i.'</br>' ;} echo '</td>';

echo "<td><a href='sendmessage.php?batchname=".$row['batchname']." & $i'><button type='button'name='enable'class='btn btn-primary'>Send Message</button></a> </td>";
echo "</tr>";
</code>```

how to display day of each value of $i

答:
You can calculate the days between to dates to define a function.
Apply this code:

```<code><?php echo '<td>'; echo dateDifference($startdate ,$startdate ).'</td>'; ?>
</code>```

Now try with dateDifference function code.

```<code><?php
function dateDifference($startdate , $startdate , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);

    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}
?>
</code>```

Body:
I want to display all the day of date between 2 dates

echo "
";
echo "" . $i++ . "	";
echo "" . $row['instructorname'] . "	";
echo "" . $row['batchname'] . "	";
echo ''; for($i=$startdate;$i<=$todate;$i++){ echo $i.'
' ;} echo '	';

echo "<button type='button'name='enable'class='btn btn-primary'>Send Message</button> 	";
echo "
";

how to display day of each value of $i

Body:
You can calculate the days between to dates to define a function.
Apply this code:

<?php echo '<td>'; echo dateDifference($startdate ,$startdate ).'</td>'; ?>

Now try with dateDifference function code.

<?php
function dateDifference($startdate , $startdate , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);

    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}
?>


问:
Why does using pipes and map fail on a list of data frames?
I have tibbles nested in a list with an identifier column as well. I would like to run anonymous functions on each nested tibble. However, when I use a pipe to refer to my main df and then to the list that contains my data map does not work.

```<code># Creating the df
df_nested <- iris %>% group_by(Species) %>% nest()

# Does not work
# df_nested %>%
# map(data, nrow)

# Works
map(df_nested$data, nrow)
</code>```

I would like to understand why doesn't the code work with using a pipe.

答:
That is because when using pipes (%>%) the first argument is passed by default from LHS.

When you are doing

```<code>df_nested %>% map(data, nrow)
</code>```

you get

```<code>#$Species
#[1] ".x[[i]]" "nrow"

#$data
#[1] ".x[[i]]" "nrow"

#Warning messages:
#1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
#2: In .f(.x[[i]], ...) : data set ‘nrow’ not found
#3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
#4: In .f(.x[[i]], ...) : data set ‘nrow’ not found
</code>```

which is same as

```<code>map(df_nested, data, nrow)
</code>```

If you want to use pipes you might need

```<code>df_nested$data %>% map(nrow)

#[[1]]
#[1] 50

#[[2]]
#[1] 50

#[[3]]
#[1] 50
</code>```

Body:
I have tibbles nested in a list with an identifier column as well. I would like to run anonymous functions on each nested tibble. However, when I use a pipe to refer to my main df and then to the list that contains my data map does not work.

# Creating the df
df_nested <- iris %>% group_by(Species) %>% nest()

# Does not work
# df_nested %>%
# map(data, nrow)

# Works
map(df_nested$data, nrow)

I would like to understand why doesn't the code work with using a pipe.

Body:
That is because when using pipes (%>%) the first argument is passed by default from LHS.

When you are doing

df_nested %>% map(data, nrow)

you get

#$Species
#[1] ".x[[i]]" "nrow"

#$data
#[1] ".x[[i]]" "nrow"

#Warning messages:
#1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
#2: In .f(.x[[i]], ...) : data set ‘nrow’ not found
#3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
#4: In .f(.x[[i]], ...) : data set ‘nrow’ not found

which is same as

map(df_nested, data, nrow)

If you want to use pipes you might need

df_nested$data %>% map(nrow)

#[[1]]
#[1] 50

#[[2]]
#[1] 50

#[[3]]
#[1] 50


问:
Understanding undocumented Vue.js attributes ( Vue + Pug )
So i was just browsing through certain vue.js code HERE. and came across the following code below:

```<code>menu-dropdown.task-dropdown(
  v-if="!isRunningYesterdailies",
  :right="task.type === 'reward'",
  ref="taskDropdown",
  v-b-tooltip.hover.top="$t('options')"
)
</code>```

I don't quite understand this attribute :right that is inserted in the code ? What is it doing and what is its purpose , i am new to Vue.js , but by looking around a bit i was able to find documentation for the rest of the attributes except this attribute called :right ? Can anybody shed some light on this ?

答:
I don't know Pug well, but it seems to me that the pasted Pug code creates a menu-dropdown element with those given attributes. right attribute is bound to a dynamic value from the Vue model using the v-bind: directive's shorthand :.

I searched for menu-dropdown component's definition in the repository you linked, and find this file:
https://github.com/HabitRPG/habitica/blob/develop/website/client/components/ui/customMenuDropdown.vue

This is where the right attribute is defined as a Vue prop:

```<code><script>
export default {
  props: {
    right: Boolean,
    ...
</code>```

You can read more about props in the Vue documentation.

Body:
So i was just browsing through certain vue.js code HERE. and came across the following code below:

menu-dropdown.task-dropdown(
  v-if="!isRunningYesterdailies",
  :right="task.type === 'reward'",
  ref="taskDropdown",
  v-b-tooltip.hover.top="$t('options')"
)

I don't quite understand this attribute :right that is inserted in the code ? What is it doing and what is its purpose , i am new to Vue.js , but by looking around a bit i was able to find documentation for the rest of the attributes except this attribute called :right ? Can anybody shed some light on this ?

Body:
I don't know Pug well, but it seems to me that the pasted Pug code creates a menu-dropdown element with those given attributes. right attribute is bound to a dynamic value from the Vue model using the v-bind: directive's shorthand :.

I searched for menu-dropdown component's definition in the repository you linked, and find this file:
https://github.com/HabitRPG/habitica/blob/develop/website/client/components/ui/customMenuDropdown.vue

This is where the right attribute is defined as a Vue prop:

<script>
export default {
  props: {
    right: Boolean,
    ...

You can read more about props in the Vue documentation.


问:
Open new HTML page in the same tab via Javascript
I have tried a half dozen ways to open a page in the same tab upon clicking a button and none of them work on FireFox or Edge:

```<code>window.location ="advance.html";
</code>```

nothing happens

```<code>window.location ="/advance.html";
</code>```

nothing happens

```<code>window.location.href ="advance.html";
</code>```

nothing happens

```<code>window.location.href ="/advance.html";
</code>```

nothing happens

```<code>window.open("advance.html", _self);
</code>```

nothing happens

```<code>window.open("advance.html");
</code>```

opens page in new tab

Been working on it for an hour trying every suggestion and nothing works.

What am I missing here?

EDIT:
Since people are asking for the context (I know the username and password are in plain text, I'm just trying to get this part working first):

```<code><script language="javascript">
    function goHome()
    {
        window.location = 'index.html';
    };

    function login(form)
    {
        if(form.company.value == "advance" && form.password.value == "1234")
        {
            window.location.href ="advance.html";
        }
        else if(form.company.value == "" || form.password.value == "")
        {
        }
        else
        {
            alert("Incorrect Usename/Password combination please try again.");
            form.password.value = "";
        }
    }
</code>```

答:
I think the problem is in your window.open("advance.html", _self);. You have to quote the "_self". window.open("advance.html", "_self"); this code should work.
Also you can use location parameter in it. Like `location.assign("advance.html"). It will open it in a new window.

Body:
I have tried a half dozen ways to open a page in the same tab upon clicking a button and none of them work on FireFox or Edge:

window.location ="advance.html";

nothing happens

window.location ="/advance.html";

nothing happens

window.location.href ="advance.html";

nothing happens

window.location.href ="/advance.html";

nothing happens

window.open("advance.html", _self);

nothing happens

window.open("advance.html");

opens page in new tab

Been working on it for an hour trying every suggestion and nothing works.

What am I missing here?

EDIT:
Since people are asking for the context (I know the username and password are in plain text, I'm just trying to get this part working first):


问:
Redirect to a file STDOUT first and then STDERR
I have a gawk code like this.

```<code>#!/usr/bin/gawk -f

1 {
    for (i=0;i<5;i++){
        print $0
        print $0, i > "/dev/stderr"
    }
}
</code>```

I want to redirect to a file tmp, first the stdout and then the stderr. I tried this:

gawk -f Documents/gawk_script.awk ./file &> tmp
```
<p>But this call append to the file first stderr. I don't want to divide them into two files, so I'm asking if there's a way to do that.</p>
<p>In ./file there's such a line:</p>
```hello
hello
howareyou
well
well
```
<p>while in tmp file</p>
```hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
howareyou
howareyou
howareyou
howareyou
howareyou
well
well
well
well
well
well
well
well
well
well
well
hello 0
hello 1
hello 2
hello 3
hello 4
hello 0
hello 1
hello 2
hello 3
hello 4
howareyou 0
howareyou 1
howareyou 2
howareyou 3
howareyou 4
well 0
well 1
well 2
well 3
well 4
well 0
well 1
well 2
well 3
well 4
```

答:
This is a small example:

I am not sure what you mean, if I understand it...

If you want to redirect stdout to file_out , redirect stderr to file_err , you can do this...

```<code>command > file_out 2> file_err
</code>```

Body:
I have a gawk code like this.

#!/usr/bin/gawk -f

1 {
    for (i=0;i<5;i++){
        print $0
        print $0, i > "/dev/stderr"
    }
}

I want to redirect to a file tmp, first the stdout and then the stderr. I tried this:

gawk -f Documents/gawk_script.awk ./file &> tmp

But this call append to the file first stderr. I don't want to divide them into two files, so I'm asking if there's a way to do that.

In ./file there's such a line:

hello
hello
howareyou
well
well

while in tmp file

hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
howareyou
howareyou
howareyou
howareyou
howareyou
well
well
well
well
well
well
well
well
well
well
well
hello 0
hello 1
hello 2
hello 3
hello 4
hello 0
hello 1
hello 2
hello 3
hello 4
howareyou 0
howareyou 1
howareyou 2
howareyou 3
howareyou 4
well 0
well 1
well 2
well 3
well 4
well 0
well 1
well 2
well 3
well 4

Body:
This is a small example:

I am not sure what you mean, if I understand it...

If you want to redirect stdout to file_out , redirect stderr to file_err , you can do this...

command > file_out 2> file_err


问:
NoSuchElementException: No Line Found with hasNextLine
I have included a hasNextLine exception, but I am still receiving the NoSuchElementException error

I am creating a palindrome program that scans from a file. I can get it to scan from the file, but it only returns the non-palindrome words, and returns an err of NoSuchElementException: No Line Found, even though I have included a hasNextLine.

```<code>case 3:
            System.out.println("Palindrome problem.");

    while (input.hasNextLine()) {
        String text, reverse = input.nextLine();
        text = input.nextLine();
        int length = text.length();
        for ( int i = length - 1; i >= 0; i-- )
        reverse = reverse + text.charAt(i);
            if (text.equals(reverse))
            System.out.println(text + "is a palindrome.");
                else
                System.out.println(text + "isn't a palindrome.");
    }
            break;
</code>```

I would like the code to read the entire file and return both palindromes and non-palindrome words

答:
It's because you are calling the input.nextLine() twice here:

```<code>String text, reverse = input.nextLine();
text = input.nextLine();
</code>```

When text = input.nextLine(); is executed the line is already consumed.

Body:
I have included a hasNextLine exception, but I am still receiving the NoSuchElementException error

I am creating a palindrome program that scans from a file. I can get it to scan from the file, but it only returns the non-palindrome words, and returns an err of NoSuchElementException: No Line Found, even though I have included a hasNextLine.

case 3:
            System.out.println("Palindrome problem.");

    while (input.hasNextLine()) {
        String text, reverse = input.nextLine();
        text = input.nextLine();
        int length = text.length();
        for ( int i = length - 1; i >= 0; i-- )
        reverse = reverse + text.charAt(i);
            if (text.equals(reverse))
            System.out.println(text + "is a palindrome.");
                else
                System.out.println(text + "isn't a palindrome.");
    }
            break;

I would like the code to read the entire file and return both palindromes and non-palindrome words

Body:
It's because you are calling the input.nextLine() twice here:

String text, reverse = input.nextLine();
text = input.nextLine();

When text = input.nextLine(); is executed the line is already consumed.


问:
Nodejs - Create modules from string with the npm package 'module'
I want to load a custom module using the npm package 'module', to be able to require it like any other local folder that exports something.

I cannot find any documentation on the use of the package https://www.npmjs.com/package/module

I tried to use it without any documentation on it, but i simply cannot as i dont understand how you use it.

```<code>    let myFunction = module.wrap(`module.exports = () => console.log("hej")`);```
```

答:
I think you are trying to create a module of your own to be able to use it at multiple places within your project ( correct me if I am wrong).

SO you can do that like :
In utils/custom.js

```<code> module.exports = {
    logThis: "Hi"
}
</code>```

OR

```<code>var a={
 logThis:function (){
  console.log('HI')
}
module.exports=a;
</code>```

And then in the file where you want to access this :
 In app.js

```<code>let custom=require('./utils/custom.js')
</code>```

Body:
I want to load a custom module using the npm package 'module', to be able to require it like any other local folder that exports something.

I cannot find any documentation on the use of the package https://www.npmjs.com/package/module

I tried to use it without any documentation on it, but i simply cannot as i dont understand how you use it.

    let myFunction = module.wrap(`module.exports = () => console.log("hej")`);```

Body:
I think you are trying to create a module of your own to be able to use it at multiple places within your project ( correct me if I am wrong).

SO you can do that like :
In utils/custom.js

 module.exports = {
    logThis: "Hi"
}

OR

var a={
 logThis:function (){
  console.log('HI')
}
module.exports=a;

And then in the file where you want to access this :
 In app.js

let custom=require('./utils/custom.js')