问:
Create Airflow connections on Cloud Composer using gcloud CLI
I am trying to create airflow connections on Cloud Composer using gcloud CLI.
I follow the document and run the following comment.
https://cloud.google.com/composer/docs/how-to/managing/connections#creating_new_airflow_connections

```<code>gcloud composer environments run my-env \
  --project my-project \
  --location asia-northeast1 \
  connections -- --add \
  --conn_id=my-conn-id \
  --conn_type=google_cloud_platform \
  --conn_extra '{"extra\__google\_cloud\_platform\__project": "my-project", \
  "extra\__google\_cloud\_platform\__key_path": "/home/airflow/gcs/data/keys/my-key.json", \
  "extra\__google\_cloud\_platform\__scope": "https://www.googleapis.com/auth/cloud-platform"}'

kubeconfig entry generated for asia-northeast1-my-env-44718514-gke.
Executing within the following kubectl namespace: default
W0525 22:51:11.244104   93234 flags.go:39] conn_extra is DEPRECATED and will be removed in
a future version. Use conn-extra instead.
W0525 22:51:11.244246   93234 flags.go:39] conn_extra is DEPRECATED and will be removed in
a future version. Use conn-extra instead.
W0525 22:51:11.244256   93234 flags.go:39] conn_extra is DEPRECATED and will be removed in
a future version. Use conn-extra instead.

[2019-05-25 14:51:13,215] {settings.py:176} INFO - setting.configure_orm():
Using pool settings. pool_size=5, pool_recycle=1800
[2019-05-25 14:51:13,598] {default_celery.py:80} WARNING - You have configured a
result_backend of redis://airflow-redis-service:6379/0, it is highly recommended to use an
alternative result_backend (i.e. a database).
[2019-05-25 14:51:13,600] {__init__.py:51} INFO - Using executor CeleryExecutor
[2019-05-25 14:51:13,680] {app.py:51} WARNING - Using default Composer Environment Variables.
Overrides have not been applied.
[2019-05-25 14:51:13,688] {configuration.py:516} INFO - Reading the config from
/etc/airflow/airflow.cfg
[2019-05-25 14:51:13,698] {configuration.py:516} INFO - Reading the config from
/etc/airflow/airflow.cfg
</code>```

The connection is successfully created but project ID, key file path and scope are empty. So the connection is invalid.

When I manually created, those properties are not empty. Am I missing something?

Composer image: composer-1.5.0-airflow-1.10.1

答:
I am not able to replicate it. When I run the following command the connection does get added with the extras field:</p>

```<code>gcloud composer environments run my-env \
  --project my-project \
  --location europe-west1 \
  connections -- --add \
  --conn_id=my-conn-id \
  --conn_type=google_cloud_platform \
  --conn_extra='{"extra__google_cloud_platform__project": "my-project", "extra__google_cloud_platform__key_path":"/tesf"}
</code>```

Body:
I am trying to create airflow connections on Cloud Composer using gcloud CLI.
I follow the document and run the following comment.
https://cloud.google.com/composer/docs/how-to/managing/connections#creating_new_airflow_connections

gcloud composer environments run my-env \
  --project my-project \
  --location asia-northeast1 \
  connections -- --add \
  --conn_id=my-conn-id \
  --conn_type=google_cloud_platform \
  --conn_extra '{"extra\__google\_cloud\_platform\__project": "my-project", \
  "extra\__google\_cloud\_platform\__key_path": "/home/airflow/gcs/data/keys/my-key.json", \
  "extra\__google\_cloud\_platform\__scope": "https://www.googleapis.com/auth/cloud-platform"}'

kubeconfig entry generated for asia-northeast1-my-env-44718514-gke.
Executing within the following kubectl namespace: default
W0525 22:51:11.244104   93234 flags.go:39] conn_extra is DEPRECATED and will be removed in
a future version. Use conn-extra instead.
W0525 22:51:11.244246   93234 flags.go:39] conn_extra is DEPRECATED and will be removed in
a future version. Use conn-extra instead.
W0525 22:51:11.244256   93234 flags.go:39] conn_extra is DEPRECATED and will be removed in
a future version. Use conn-extra instead.

[2019-05-25 14:51:13,215] {settings.py:176} INFO - setting.configure_orm():
Using pool settings. pool_size=5, pool_recycle=1800
[2019-05-25 14:51:13,598] {default_celery.py:80} WARNING - You have configured a
result_backend of redis://airflow-redis-service:6379/0, it is highly recommended to use an
alternative result_backend (i.e. a database).
[2019-05-25 14:51:13,600] {__init__.py:51} INFO - Using executor CeleryExecutor
[2019-05-25 14:51:13,680] {app.py:51} WARNING - Using default Composer Environment Variables.
Overrides have not been applied.
[2019-05-25 14:51:13,688] {configuration.py:516} INFO - Reading the config from
/etc/airflow/airflow.cfg
[2019-05-25 14:51:13,698] {configuration.py:516} INFO - Reading the config from
/etc/airflow/airflow.cfg

The connection is successfully created but project ID, key file path and scope are empty. So the connection is invalid.

When I manually created, those properties are not empty. Am I missing something?

Composer image: composer-1.5.0-airflow-1.10.1

Body:
I am not able to replicate it. When I run the following command the connection does get added with the extras field:

gcloud composer environments run my-env \
  --project my-project \
  --location europe-west1 \
  connections -- --add \
  --conn_id=my-conn-id \
  --conn_type=google_cloud_platform \
  --conn_extra='{"extra__google_cloud_platform__project": "my-project", "extra__google_cloud_platform__key_path":"/tesf"}


来源: stackexchange

问:
Go API in container not returning any response
I have a simple API written in GO using Mux.

When running locally it works, however I am trying to containerize this app.

My main.go looks like this

```<code>package main

import (
    "net/http"
    "time"
    "log"
    "github.com/gorilla/mux"
    "github.com/<username>/tweet-media-api/controllers"
)

func main() {

    r := mux.NewRouter()

    c := controllers.Controller{}

    r.HandleFunc("/", c.BaseRoute()).Methods("GET")
    r.HandleFunc("/healthz", c.HealthzRoute()).Methods("GET")

    srv := &http.Server{
        Handler:      r,
        Addr:         "127.0.0.1:8080",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    log.Fatal(srv.ListenAndServe())
}
</code>```

and my project is basically set out like this

I am using go version go1.11.4 darwin/amd64 and my project is using go modules.

I have tried to create a multi stage Dockerfile as below

```<code># build stage
FROM golang:alpine AS build-env
ADD . /src
RUN apk update && apk upgrade && apk add --no-cache git
RUN cd /src && go build -o goapp

# final stage
FROM alpine
WORKDIR /app
COPY --from=build-env /src/goapp /app/
EXPOSE 8080
ENTRYPOINT ./goapp
</code>```

I run docker build . -t my-app in the root of the project and this completes with

```<code>Successfully built ebb41cfbef59
Successfully tagged my-app:latest
</code>```

However when I run docker run -p 8080:8080 my-app there is no output from the terminal and a curl request on http://localhost:8080/ returns no response. This is also the same for a browser request.

I am very new to Docker and confused as to why this build is not working.

I know that my container is running my app as I added

```<code>fmt.Println("Running")
</code>```

and this was printed to the console.

答:
I think you need to remove the host portion from your Addr property.

```<code>srv := &http.Server{
    Handler:      r,
    Addr:         ":8080",
    WriteTimeout: 15 * time.Second,
    ReadTimeout:  15 * time.Second,
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple API written in GO using Mux.

When running locally it works, however I am trying to containerize this app.

My main.go looks like this

package main

import (
    "net/http"
    "time"
    "log"
    "github.com/gorilla/mux"
    "github.com/<username>/tweet-media-api/controllers"
)

func main() {

    r := mux.NewRouter()

    c := controllers.Controller{}

    r.HandleFunc("/", c.BaseRoute()).Methods("GET")
    r.HandleFunc("/healthz", c.HealthzRoute()).Methods("GET")

    srv := &http.Server{
        Handler:      r,
        Addr:         "127.0.0.1:8080",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    log.Fatal(srv.ListenAndServe())
}

and my project is basically set out like this

I am using go version go1.11.4 darwin/amd64 and my project is using go modules.

I have tried to create a multi stage Dockerfile as below

# build stage
FROM golang:alpine AS build-env
ADD . /src
RUN apk update && apk upgrade && apk add --no-cache git
RUN cd /src && go build -o goapp

# final stage
FROM alpine
WORKDIR /app
COPY --from=build-env /src/goapp /app/
EXPOSE 8080
ENTRYPOINT ./goapp

I run docker build . -t my-app in the root of the project and this completes with

Successfully built ebb41cfbef59
Successfully tagged my-app:latest

However when I run docker run -p 8080:8080 my-app there is no output from the terminal and a curl request on http://localhost:8080/ returns no response. This is also the same for a browser request.

I am very new to Docker and confused as to why this build is not working.

I know that my container is running my app as I added

fmt.Println("Running")

and this was printed to the console.

Body:
I think you need to remove the host portion from your Addr property.

srv := &http.Server{
    Handler:      r,
    Addr:         ":8080",
    WriteTimeout: 15 * time.Second,
    ReadTimeout:  15 * time.Second,
}


问:
Intellij Scala not recognizing operators
I'm using the Play Framework with Scala, developing using IntelliJ IDEA Community 13. I've got Play running from a terminal; that's all working. However, IntelliJ isn't recognizing some of the operators used on strings.

Here's my code:

```<code>package controllers

import play.api.mvc._
import play.api.libs.json._

object Application extends Controller {

  def index = Action {
    Redirect(routes.Application.tasks)
  }

  def tasks = TODO

  def newTask = TODO

  def deleteTask(id: Long) = TODO

  def sayHello = Action(parse.json) { request =>
    (request.body \ "name").asOpt[String].map { name =>
      Ok(Json.toJson(
        Map("status" -> "OK", "message" -> ("Hello " + name)) // this line
      ))
    }.getOrElse {
      BadRequest("Missing parameter [name]")
    }
  }

}
</code>```

It compiles and runs fine in Play. However, IntelliJ marks the + and -> operators as invalid, giving me a "Cannot resolve symbol +" when I hover.

I know this is more of an inconvenience than anything else, but it's really bothering me. What do I have to import or configure in order to get IntelliJ to recognize those operators?

答:
I have faced the same problem when I was using mkString method in scala. And the intellij was throwing compiler alert as

cannot recognise symbol mkString

But when I applied toString method before using the mkString method. The alert was gone and the code compiled successfully

ContentLicense: CC BY-SA 3.0

Body:
I'm using the Play Framework with Scala, developing using IntelliJ IDEA Community 13. I've got Play running from a terminal; that's all working. However, IntelliJ isn't recognizing some of the operators used on strings.

Here's my code:

package controllers

import play.api.mvc._
import play.api.libs.json._

object Application extends Controller {

  def index = Action {
    Redirect(routes.Application.tasks)
  }

  def tasks = TODO

  def newTask = TODO

  def deleteTask(id: Long) = TODO

  def sayHello = Action(parse.json) { request =>
    (request.body \ "name").asOpt[String].map { name =>
      Ok(Json.toJson(
        Map("status" -> "OK", "message" -> ("Hello " + name)) // this line
      ))
    }.getOrElse {
      BadRequest("Missing parameter [name]")
    }
  }

}

It compiles and runs fine in Play. However, IntelliJ marks the + and -> operators as invalid, giving me a "Cannot resolve symbol +" when I hover.

I know this is more of an inconvenience than anything else, but it's really bothering me. What do I have to import or configure in order to get IntelliJ to recognize those operators?


问:
right to left scrollbar at the bottom of the table html
In the following fiddle I create a table where I need it to be right to left.
Everything is fine except that the scrollbar at the bottom  of the table initially is in the left of the page and so the user can not see the first column.

FiddleDemo

How can I set the initial position of the scrollbar to be in the right and I can see the first column.

The following is the code in the fiddle link.

HTML

```<code><table>
    <tr>
        <th>RTL Header 1</th>
        <th>RTL Header 2</th>
        <th>RTL Header 3</th>
        <th>RTL Header 4</th>
        <th>RTL Header 5</th>
        <th>RTL Header 6</th>
        <th>RTL Header 7</th>
        <th>RTL Header 8</th>
        <th>RTL Header 9</th>
        <th>RTL Header 10</th>
        <th>RTL Header 11</th>
        <th>RTL Header 12</th>
        <th>RTL Header 13</th>
        <th>RTL Header 14</th>
    </tr>
    <tr>
        <td>RTL Content 1</td>
        <td>RTL Content 2</td>
        <td>RTL Content 3</td>
        <td>RTL Content 4</td>
        <td>RTL Content 5</td>
        <td>RTL Content 6</td>
        <td>RTL Content 7</td>
        <td>RTL Content 8</td>
        <td>RTL Content 9</td>
        <td>RTL Content 10</td>
        <td>RTL Content 11</td>
        <td>RTL Content 12</td>
        <td>RTL Content 13</td>
        <td>RTL Content 14</td>
    </tr>
</table>
</code>```

CSS

```<code>table {
  direction: rtl;
  font-family: Vazir;
  border-collapse: collapse;
  width: 100%;
}

th {
  direction: rtl;
  width: 100%;
  border: 1px solid #848080;
  text-align: center;
  padding: 8px;
  white-space: nowrap;
}
td{
    direction: rtl;
    width: 100%;
    border: 1px solid #848080;
    text-align: center;
    padding: 8px;
    white-space: nowrap;
}
td:last-child{
    width:100%;
}
th:last-child{
    width:100%;
}
tr:nth-child(even) {
  background-color: #dddddd;
}
</code>```

答:
First rule of taking any piece of maintable code down -> go DRY, which means do not repeat yourself.

You do not have to state direction:rtl on every single child element, make use of the inheritance and avoid confusing behaviors.

I've just made your own code cleaner by removing all those direction properties on every child element and having it exerted on the correct parent element, and now it works as expected.

```<code>table {
  font-family: Vazir;
  border-collapse: collapse;
  width: 100%;
}

th {
  width: 100%;
  border: 1px solid #848080;
  text-align: center;
  padding: 8px;
  white-space: nowrap;
  direction: rtl; --> this is enough alrady :)
}

td {
  width: 100%;
  border: 1px solid #848080;
  text-align: center;
  padding: 8px;
  white-space: nowrap;
}

td:last-child {
  width: 100%;
}

th:last-child {
  width: 100%;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</code>```

Body:
In the following fiddle I create a table where I need it to be right to left.
Everything is fine except that the scrollbar at the bottom  of the table initially is in the left of the page and so the user can not see the first column.

FiddleDemo

How can I set the initial position of the scrollbar to be in the right and I can see the first column.

The following is the code in the fiddle link.

HTML

        RTL Header 1
        RTL Header 2
        RTL Header 3
        RTL Header 4
        RTL Header 5
        RTL Header 6
        RTL Header 7
        RTL Header 8
        RTL Header 9
        RTL Header 10
        RTL Header 11
        RTL Header 12
        RTL Header 13
        RTL Header 14

        RTL Content 1
        RTL Content 2
        RTL Content 3
        RTL Content 4
        RTL Content 5
        RTL Content 6
        RTL Content 7
        RTL Content 8
        RTL Content 9
        RTL Content 10
        RTL Content 11
        RTL Content 12
        RTL Content 13
        RTL Content 14

CSS

table {
  direction: rtl;
  font-family: Vazir;
  border-collapse: collapse;
  width: 100%;
}

th {
  direction: rtl;
  width: 100%;
  border: 1px solid #848080;
  text-align: center;
  padding: 8px;
  white-space: nowrap;
}
td{
    direction: rtl;
    width: 100%;
    border: 1px solid #848080;
    text-align: center;
    padding: 8px;
    white-space: nowrap;
}
td:last-child{
    width:100%;
}
th:last-child{
    width:100%;
}
tr:nth-child(even) {
  background-color: #dddddd;
}

Body:
First rule of taking any piece of maintable code down -> go DRY, which means do not repeat yourself.

You do not have to state direction:rtl on every single child element, make use of the inheritance and avoid confusing behaviors.

I've just made your own code cleaner by removing all those direction properties on every child element and having it exerted on the correct parent element, and now it works as expected.

table {
  font-family: Vazir;
  border-collapse: collapse;
  width: 100%;
}

th {
  width: 100%;
  border: 1px solid #848080;
  text-align: center;
  padding: 8px;
  white-space: nowrap;
  direction: rtl; --> this is enough alrady :)
}

td {
  width: 100%;
  border: 1px solid #848080;
  text-align: center;
  padding: 8px;
  white-space: nowrap;
}

td:last-child {
  width: 100%;
}

th:last-child {
  width: 100%;
}

tr:nth-child(even) {
  background-color: #dddddd;
}


问:
Why remove multiple input text dynamically doesn't work?
My html like this :

```<code><h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
    <p>
        <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
    </p>
</div>
</code>```

My javascript like this :

```<code>$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').length + 1;

        $('#addScnt').on('click', function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
                i++;
                return false;
        });

        $('#remScnt').on('click', function() {
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});
</code>```

My demo and full script like this : http://jsfiddle.net/4nvc0jmb/

If I click add input text then it works, but if I click remove input text, it does not work. I check on the console, but there is no error

How can I solve this problem?

答:
Element-ids should be unique, so better use the class or an other property to identify your elements (if you have multiple).

You also need to register the event-lsitener on an object that is already in the document. and filter that event-listener with the kind of objects you want to use this event-listener... otherwise the event-lsitener is only available for objects that are present at time of registering that event-listener.

What i changed to make it run:

I changed the button id to class.

Registered the event-listener on the document-element, and filtered for that button-class.

$(function() {

  var scntDiv = $('#p_scents');
  var i = $('#p_scents p').length + 1;

  $('#addScnt').on('click', function() {
    $('
<input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /> Remove
').appendTo(scntDiv);
    i++;
    return false;
  });

  $(document).on('click', '.remScnt', function() {
    if( i > 2 ) {
      $(this).parents('p').remove();
      i--;
    }
    return false;
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* { font-family:Arial; }
h2 { padding:0 0 5px 5px; }
h2 a { color: #224f99; }
a { color:#999; text-decoration: none; }
a:hover { color:#802727; }
p { padding:0 0 5px 0; }

input { padding:5px; border:1px solid #999; border-radius:4px; -moz-border-radius:4px; -web-kit-border-radius:4px; -khtml-border-radius:4px; }</code>```

Add Another Input Box

    <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />

```

Body:
My html like this :

Add Another Input Box

        <input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />

My javascript like this :

$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').length + 1;

        $('#addScnt').on('click', function() {
                $('
<input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /> Remove
').appendTo(scntDiv);
                i++;
                return false;
        });

        $('#remScnt').on('click', function() {
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});

My demo and full script like this : http://jsfiddle.net/4nvc0jmb/

If I click add input text then it works, but if I click remove input text, it does not work. I check on the console, but there is no error

How can I solve this problem?

Body:
Element-ids should be unique, so better use the class or an other property to identify your elements (if you have multiple).

You also need to register the event-lsitener on an object that is already in the document. and filter that event-listener with the kind of objects you want to use this event-listener... otherwise the event-lsitener is only available for objects that are present at time of registering that event-listener.

What i changed to make it run:

I changed the button id to class.

Registered the event-listener on the document-element, and filtered for that button-class.

$(function() {

  var scntDiv = $('#p_scents');
  var i = $('#p_scents p').length + 1;

  $('#addScnt').on('click', function() {
    $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
    i++;
    return false;
  });

  $(document).on('click', '.remScnt', function() {
    if( i > 2 ) {
      $(this).parents('p').remove();
      i--;
    }
    return false;
  });

});

* { font-family:Arial; }
h2 { padding:0 0 5px 5px; }
h2 a { color: #224f99; }
a { color:#999; text-decoration: none; }
a:hover { color:#802727; }
p { padding:0 0 5px 0; }

input { padding:5px; border:1px solid #999; border-radius:4px; -moz-border-radius:4px; -web-kit-border-radius:4px; -khtml-border-radius:4px; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>
<div id="p_scents">
  <p>
    <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
  </p>
</div>


问:
How can I store an input value in web local storege using javascript or jquery?
I have an input like below.
I want to keep its value after the page is refreshed.
notice that I have the name attribute, not class or ID.

```<code><input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>
</code>```

```<code><script type="text/javascript">
var nameArr = ["name"];
nameArr.forEach(function(el){
  document.getElementsByName(el)[0].value = getSavedValue(el);
})

function saveValue(e) {
  var name = e.target.name;
  var val = e.target.value;
  localStorage.setItem(name, val);
}

function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
    return "";
  }
  return localStorage.getItem(v);
}
</script>
</code>```

it only works for 1 input.I want something that works on unlimited number of inputs.

答:
Change parameter of saveValue to event:

<input type="text" name="name" onkeyup="saveValue(event)"/>

Since there are many elements with different names, maintain an array:

```<code>var nameArr = ["name"]; // Add more elements here
nameArr.forEach(function(el){
  document.getElementsByName(el)[0].value = getSavedValue(el);
})
</code>```

Inside saveValue use e.target, instead of e

```<code>var name = e.target.name;
var val = e.target.value;
</code>```

These should get the code working. Here's a working Codepen

Body:
I have an input like below.
I want to keep its value after the page is refreshed.
notice that I have the name attribute, not class or ID.

<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>

it only works for 1 input.I want something that works on unlimited number of inputs.

Body:
Change parameter of saveValue to event:

<input type="text" name="name" onkeyup="saveValue(event)"/>

Since there are many elements with different names, maintain an array:

var nameArr = ["name"]; // Add more elements here
nameArr.forEach(function(el){
  document.getElementsByName(el)[0].value = getSavedValue(el);
})

Inside saveValue use e.target, instead of e

var name = e.target.name;
var val = e.target.value;

These should get the code working. Here's a working Codepen


问:
Parse JSON with Gson. Difficult JSON structure without keys
How can I create the correct object for the following structure?

JSON without any keys and with arrays in arrays in arrays:

```<code>   {
    "1": [
          [
             [1.111, 2.222]
             [1.111, 2.222]
             ...
          ],
          [
             [1.111, 2.222]
             ...
          ]
       ],
    "2": [
          [
             [1.111, 2.222]
             ...
          ],
          [
             [1.111, 2.222]
             ...
          ]
       ],
    ...
    }
</code>```

答:
I have similar problem but i have a little bit diffrent JSON and i have problem to use your solution with Map. Example (Map>).

My JSON structure:

```<code>{
   "2019-05-26": {
        "lastUpdate": "2019-05-26 06:05:02",
        "routes":[
            {
              "routeId": 107,
              "agencyId": 18
            },
            {
              "routeId": 222,
              "agencyId": 22
            }
       ]
    },
"2019-05-27": {
        "lastUpdate": "2019-05-27 06:05:02",
        "routes":[
            {
              "routeId": 33,
              "agencyId": 14
            },
            {
              "routeId": 345,
              "agencyId": 2232
            }
       ]
    }
}
</code>```

How to use this JSON ? I would like to parse it to my POJOs.

Body:
How can I create the correct object for the following structure?

JSON without any keys and with arrays in arrays in arrays:

   {
    "1": [
          [
             [1.111, 2.222]
             [1.111, 2.222]
             ...
          ],
          [
             [1.111, 2.222]
             ...
          ]
       ],
    "2": [
          [
             [1.111, 2.222]
             ...
          ],
          [
             [1.111, 2.222]
             ...
          ]
       ],
    ...
    }

Body:
I have similar problem but i have a little bit diffrent JSON and i have problem to use your solution with Map. Example (Map>).

My JSON structure:

{
   "2019-05-26": {
        "lastUpdate": "2019-05-26 06:05:02",
        "routes":[
            {
              "routeId": 107,
              "agencyId": 18
            },
            {
              "routeId": 222,
              "agencyId": 22
            }
       ]
    },
"2019-05-27": {
        "lastUpdate": "2019-05-27 06:05:02",
        "routes":[
            {
              "routeId": 33,
              "agencyId": 14
            },
            {
              "routeId": 345,
              "agencyId": 2232
            }
       ]
    }
}

How to use this JSON ? I would like to parse it to my POJOs.


问:
Routing to static html page in /public
How can I route /foo to display /public/foo.html in Rails?

答:
You can do this:

Add this, into your routes.rb file.

```<code>match '/foo', :to => redirect('/foo.html')
</code>```

Update

In Rails 4, it should use "get", not "match":

```<code>get '/foo', :to => redirect('/foo.html')
</code>```

thanks Grant Birchmeier

Title: Routing to static html page in /public

Body:
You can do this:

Add this, into your routes.rb file.

match '/foo', :to => redirect('/foo.html')

Update

In Rails 4, it should use "get", not "match":

get '/foo', :to => redirect('/foo.html')

thanks Grant Birchmeier


问:
MySQL server requested caching_sha2_password for a user with standard password
I have MySQL database up and running with the caching_sha2_password authentication.

It allows for creating users with the standard password authentication (mysql_native_password) but when trying to connect from a remote host with standard auth the user I'm getting 'The server requested authentication method unknown to the client [caching_sha2_password]...' error anyway.

Is it possible to use the legacy authentication for selected users even if the server supports caching_sha2_password.

The reason would be e. g. using strong authentication for the root and standard for the other accounts with limited access to single schemas.

(Version 8.0.16 GPL)

答:
You can specify the authentication method for each user individually in the plugin column of the mysql.user table. Check the documentation 6.2.3 Grant Tables - The user and db Tables:

The server uses the plugin named in the plugin column of an account row to authenticate connection attempts for the account.


问:
Globbing Absolute Paths With Pathlib
In python3, when operating on unknown (user-input) file paths, I need to support wildcards such as ./r*/*.dat.  The plan was to use something like this (simplified):

```<code>paths = []
for test in userinputs:
   paths.extend(pathlib.Path().glob(test))
</code>```

This works great for relative paths; however, when the user provides an absolute path (which they should be allowed to do), the code fails:

NotImplementedError: Non-relative patterns are unsupported

If it's a "simple" glob, like /usr/bin/*, I can do something like:

```<code>test = pathlib.Path("/usr/bin/*")
sources.extend(test.parent.glob(test.name))
</code>```

However, like my first path example, I need to account for wildcards in any of the parts of the path, such as /usr/b*/*.

Is there an elegant solution for this?  I feel like I'm missing something obvious.

答:
Path() takes a parameter for its starting dir.
Why not test the input to see if an absolute path and then init Path() as the root dir? something like:

```<code>for test in userinputs:
    if test[0] == '/':
        paths.extend(pathlib.Path('/').glob(test[1:]))
    else:
        paths.extend(pathlib.Path().glob(test))
</code>```

Title: Globbing Absolute Paths With Pathlib

Body:
In python3, when operating on unknown (user-input) file paths, I need to support wildcards such as ./r*/*.dat.  The plan was to use something like this (simplified):

paths = []
for test in userinputs:
   paths.extend(pathlib.Path().glob(test))

This works great for relative paths; however, when the user provides an absolute path (which they should be allowed to do), the code fails:

NotImplementedError: Non-relative patterns are unsupported

If it's a "simple" glob, like /usr/bin/*, I can do something like:

test = pathlib.Path("/usr/bin/*")
sources.extend(test.parent.glob(test.name))

However, like my first path example, I need to account for wildcards in any of the parts of the path, such as /usr/b*/*.

Is there an elegant solution for this?  I feel like I'm missing something obvious.

Body:
Path() takes a parameter for its starting dir.
Why not test the input to see if an absolute path and then init Path() as the root dir? something like:

for test in userinputs:
    if test[0] == '/':
        paths.extend(pathlib.Path('/').glob(test[1:]))
    else:
        paths.extend(pathlib.Path().glob(test))


问:
Can use joblib dump many object?
I have this code. Can I save 'pca' and 'svm_clf' to one file by using joblib.dump? If not, is there any other way to do this?</p>

```<code>from sklearn.svm import SVC
from sklearn.externals import joblib
from sklearn import decomposition
from sklearn import svm

X = [[1,3,4,5,6,7,8,7,0],[1,3,4,5,6,7,9,5,1]]
Y = [1,0]
#pca
pca = decomposition.PCA(0.98)
X_new = pca.fit_transform(X)
svm_clf = svm.LinearSVC()
#svm model
svm_clf = SVC(C=1, kernel='rbf')
svm_clf.fit(X_new, Y)
#save model
joblib.dump(pca, 'model.sav')
joblib.dump(svm_clf, 'model.sav')
</code>```

答:
You can simply use:

```<code>joblib.dump([pca, svm_clf], 'model.sav', compress=1)
</code>```

And then use the models like:

```<code>pca, svm_clf = joblib.load('model.sav')
</code>```

Probably a nicer way is to define a pipeline if you want to use these two models together and dump the pipeline:

```<code>from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(pca, svm_clf)
joblib.dump(pipeline, 'model.sav')
</code>```

Title: Can use joblib dump many object?

Body:
I have this code. Can I save 'pca' and 'svm_clf' to one file by using joblib.dump? If not, is there any other way to do this?

from sklearn.svm import SVC
from sklearn.externals import joblib
from sklearn import decomposition
from sklearn import svm

X = [[1,3,4,5,6,7,8,7,0],[1,3,4,5,6,7,9,5,1]]
Y = [1,0]
#pca
pca = decomposition.PCA(0.98)
X_new = pca.fit_transform(X)
svm_clf = svm.LinearSVC()
#svm model
svm_clf = SVC(C=1, kernel='rbf')
svm_clf.fit(X_new, Y)
#save model
joblib.dump(pca, 'model.sav')
joblib.dump(svm_clf, 'model.sav')

Body:
You can simply use:

joblib.dump([pca, svm_clf], 'model.sav', compress=1)

And then use the models like:

pca, svm_clf = joblib.load('model.sav')

Probably a nicer way is to define a pipeline if you want to use these two models together and dump the pipeline:

from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(pca, svm_clf)
joblib.dump(pipeline, 'model.sav')


问:
Sanitizing JSON Strings without \
Given successful query from SQL SELECT result, there are json output with \n and \ . That makes me confusions and obstacles to deserialise the json string into array of objects. Would you please tell me the way to replace all those json strings without newlines , spaces, and also blackslashes \ ?

```<code>  dicts = [dict(row) for row in result]
  j = json.dumps(dicts ,  sort_keys=True,
  indent=None,
  default=default , separators=(',', ':'))

  return {
    'result':  j
  }
</code>```

Here is my output json with many back slashes \

```<code>{"result": "[{\"_access\":[{\"level\":\"read\",\"public\":true}],\"_created_at\":\"2019-05-26T09:57:10.494525\",\"_created_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_database_id\":\"\",\"_id\":\"3f674e29-29ba-4dcf-b9d9-f99a3c35866e\",\"_owner_id\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_updated_at\":\"2019-05-26T10:01:14.691527\",\"_updated_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"book_label\":\"B198\",\"deleted_at\":null,\"deleted_by\":null,\"free_assign_date\":null,\"free_assign_end_date\":null,\"is_completed\":false,\"is_free_assigned\":true,\"progress_chapter\":1,\"total_chapters\":2,\"user_label\":\"user10\"}]"}
</code>```

答: The ["result"] entry in the dict is a string. You just simply need to parse it. json.dumps does the opposite of what you are looking for - converts JSON to a string. You want json.loads, which converts a string to JSON data.

Title: Sanitizing JSON Strings without \

Body:
Given successful query from SQL SELECT result, there are json output with \n and \ . That makes me confusions and obstacles to deserialise the json string into array of objects. Would you please tell me the way to replace all those json strings without newlines , spaces, and also blackslashes \ ?

  dicts = [dict(row) for row in result]
  j = json.dumps(dicts ,  sort_keys=True,
  indent=None,
  default=default , separators=(',', ':'))

  return {
    'result':  j
  }

Here is my output json with many back slashes \

{"result": "[{\"_access\":[{\"level\":\"read\",\"public\":true}],\"_created_at\":\"2019-05-26T09:57:10.494525\",\"_created_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_database_id\":\"\",\"_id\":\"3f674e29-29ba-4dcf-b9d9-f99a3c35866e\",\"_owner_id\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_updated_at\":\"2019-05-26T10:01:14.691527\",\"_updated_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"book_label\":\"B198\",\"deleted_at\":null,\"deleted_by\":null,\"free_assign_date\":null,\"free_assign_end_date\":null,\"is_completed\":false,\"is_free_assigned\":true,\"progress_chapter\":1,\"total_chapters\":2,\"user_label\":\"user10\"}]"}


问:
selecting a list of files as build input
I would like to restrict the number of files to include in my build src to a select few.
Directly passing the list of files to src or srcs isn't allowed as an archive or a directory is expected.
I couldn't find a function to do this and builtins.filterSource does not seem to work for me (no idea why -- the intermediate derivation containing the filtered files ends up empty):

```<code>    files = [
        ./Cargo.toml
        ./Cargo.lock
        ./cpu.rs
    ];
    src = builtins.filterSource (p: t: builtins.elem p files) ./.;
</code>```

Note: I'm using the rustPlatform builder but I don't think it matters.

答:
filterSource passes the full path as a string.
in order to compare the paths of your list with it you need to convert the string to a path:

$ cd /Users/fghibellini/code/nix
$ nix-instantiate --eval -E './a == "/Users/fghibellini/code/nix/a"'
false
$ nix-instantiate --eval -E './a == (/. + "/Users/fghibellini/code/nix/a")'
true
```

<p>i.e. the following code should work fine:</p>

```files = [
    ./Cargo.toml
    ./Cargo.lock
    ./cpu.rs
];
src = builtins.filterSource (p: t: builtins.elem (/. + p) files) ./.;
```

You can use builtins.typeOf and builtins.trace to debug such issues.

Body:
I would like to restrict the number of files to include in my build src to a select few.
Directly passing the list of files to src or srcs isn't allowed as an archive or a directory is expected.
I couldn't find a function to do this and builtins.filterSource does not seem to work for me (no idea why -- the intermediate derivation containing the filtered files ends up empty):

    files = [
        ./Cargo.toml
        ./Cargo.lock
        ./cpu.rs
    ];
    src = builtins.filterSource (p: t: builtins.elem p files) ./.;

Note: I'm using the rustPlatform builder but I don't think it matters.

Body:
filterSource passes the full path as a string.
in order to compare the paths of your list with it you need to convert the string to a path:

$ cd /Users/fghibellini/code/nix
$ nix-instantiate --eval -E './a == "/Users/fghibellini/code/nix/a"'
false
$ nix-instantiate --eval -E './a == (/. + "/Users/fghibellini/code/nix/a")'
true

i.e. the following code should work fine:

files = [
    ./Cargo.toml
    ./Cargo.lock
    ./cpu.rs
];
src = builtins.filterSource (p: t: builtins.elem (/. + p) files) ./.;

You can use builtins.typeOf and builtins.trace to debug such issues.


问:
Construct a Deterministic Finite Automata (DFA) for the language 1*01 (11)*(0 U 1)*,
Construct a Deterministic Finite Automata (DFA) for the language where the set of all strings are of the form 1*01 (11)*(0 U 1)*, that contain 01 as a substring

答:
Without providing the direct answer, you should know the building blocks to be able to arrive there. Given that you know how finite automata work (otherwise read 'Languages and Machines' by Sudkamp), the DFA has a transitation for every symbol in every state:

Unlike for non-deterministic finite automata or NFA that we encounter in the next section, for a DFA in each state q ∈ Q and for every symbol a ∈ Σ the next state,
  which is the state δ(q, a), is determined by the transition function δ. 1

Note: if you are a visual thinker and you wonder how the diagrams in these books are constructed, here is an example visualisation.

Body:
Without providing the direct answer, you should know the building blocks to be able to arrive there. Given that you know how finite automata work (otherwise read 'Languages and Machines' by Sudkamp), the DFA has a transitation for every symbol in every state:

Unlike for non-deterministic finite automata or NFA that we encounter in the next section, for a DFA in each state q ∈ Q and for every symbol a ∈ Σ the next state,
  which is the state δ(q, a), is determined by the transition function δ. 1

Note: if you are a visual thinker and you wonder how the diagrams in these books are constructed, here is <a href="https://dreampuf.github.io/GraphvizOnline/#digraph%20dfa%20%7B%0D%0A%20rankdir%3DLR%3B%0D%0A%20%20%22%22%20%5Bshape%3Dnone%5D%0D%0A%20%20%22start%22%20%5Bshape%3Dcircle%2C%20style%3Dfilled%2C%20fillcolor%3Dyellow%5D%0D%0A%20%20%22s1%22%20%5Bshape%3Ddoublecircle%5D%0D%0A%20%20%22s2%22%20%5Bshape%3Dcircle%5D%0D%0A%20%20%22s3%22%20%5Bshape%3Dcircle%5D%0D%0A%0D%0A%20%20%22s1%22%20-%3E%20%22s1%22%20%5Blabel%3D%220%2C%201%22%5D%0D%0A%20%20%22s2%22%20-%3E%20%22s2%22%20%5Blabel%3D%221%22%5D%0D%0A%20%20%22%22%20-%3E%20%22start%22%0D%0A%20%20%22s2%22%20-%3E%20%22s3%22%20%5Blabel%3D%220%22%5D%0D%0A%20%20%22s3%22%20-%3E%20%22s1%22%20%5Blabel%3D%220%22%5D%0D%0A%20%20%22s3%22%20-%3E%20%22s4%22%20%5Blabel%3D%221%22%5D%0D%0A%20%20%22start%22%20-%3E%20%22s1%22%20%5Blabel%3D%220%22%5D%0D%0A%20%20%22start%22%20-%3E%20%22s2%22%20%5Blabel%3D%221%22%5D%0D%0A%7D" rel="nofollow noreferrer">an example visualisation.


问:
Unable to understand lambdas AND longstream methods
I have such code example.

```<code>import java.util.LinkedList;
import java.util.List;
import java.util.stream.LongStream;

public class RemovedNumbers {

    public static List<long[]> removNb(long n) {
        System.out.println(n);
        long sum = ((n + 1) * n / 2);
        long minMultiplication = sum - 2 * n + 1;
        long minCandidate = (long) Math.sqrt(minMultiplication);

        LinkedList<long[]> list = new LinkedList<>();

        LongStream.rangeClosed(minCandidate, n)
                  .mapToObj(a -> new long[]{a, calculateB(a, sum)})
                  .filter(longs -> longs[0] > longs[1])
                  .filter(longs -> longs[1] <= n)
                  .filter(longs -> longs[0] * longs[1] == sum - longs[0] - longs[1])
                  .forEach(longs -> addArrays(list, longs));

        return list;
    }

    private static long calculateB(long a, long sum) {
        return (sum - a) / (a + 1);
    }

    private static void addArrays(final LinkedList<long[]> list, final long[] longs) {
        list.addFirst(new long[]{longs[1], longs[0]});
        list.add(longs);
    }
}
</code>```

This code is complicated for me in LongStream part.
I don't get some points, so I need a help:

I examine LongStream class.

This class uses four methods: rangeClosed, mapToObj, filter, forEach (their description I found on Java docs). Unfortunately, now I am starting to examine java 1.8 version,  so I can't understand how it works and what's happens.

Where is appeared "a" in mapToObj? What is it? I don't see var "a" declaration in previous part of code.

As I've got lambda is made by such scheme: (arguments) -> (body). So the "a" is an argument, "new long[]..." - is a body. This part isn't causes any question for me. But the next one, whereis "longs" - argument, "longs[0] > longs[1]" - body, causes some questions. What is the var "longs"? It hasn't declaration in the past! HOW it appears? How it works?

Am I right that LongStream class can be writes in one line? Like: LongStream.rangeClosed().filter().filter().filter().forEach(); ?

Am I right that all methods execute consequently? By each other? The first rangeClosed, then mapToObj, then filter... or is there another order?

Thanks a lot!

答:
Your third point kind of answers your second point - a is the parameter of the lambda expression passed to mapToObj.

If you can understand that, then your fourth point should be easy to understand as well. longs is the parameter for the lambda expression passed to filter. Remember that you can name your parameter names whatever you like. I guess the reason why the author of the code renamed the parameter to longs is because in the previous line, each long in the stream is mapped into a long[], so now it's a stream of long arrays.

Am I right that LongStream class can be writes in one line?

Yes, but you would end up with a super long line of code, so we almost never do that.

Am I right that all methods execute consequently? By each other? The first rangeClosed, then mapToObj, then filter... or is there another order?

The methods get called in that order, but the operations they do won't run immediately. This is the cool part of streams. The longs will only be mapToObj'ed and filter'ed when you do forEach, a terminal operation. In other words, mapToObj and filter are kind of like saying "this is what this stream should do..." and when you do forEach, you are saying "now do it!"

If you still don't get what streams are doing, try to think of them as a production line in a factory. At the start, you have longs on the conveyer belts. And then they pass through a machine, transforming each of them into a long[]. After that, they pass through three filters. These filters will push them off the conveyer belt unless the long arrays fulfil some condition.

EDIT:

If you want to write this code without lambdas, you can write it with anonymous classes instead:

```<code>LongStream.rangeClosed(minCandidate, n)
        .mapToObj(new LongFunction<long[]>() {
            @Override
            public long[] apply(long a) {
                return new long[]{a, calculateB(a, sum)};
            }
        })
        .filter(new Predicate<long[]>() {
            @Override
            public boolean test(long[] longs) {
                return longs[0] > longs[1] &&
                        longs[1] <= n &&
                        longs[0] * longs[1] == sum - longs[0] - longs[1];
            }
        })
        .forEach(new Consumer<long[]>() {
            @Override
            public void accept(long[] longs) {
                addArrays(list, longs);
            }
        });
</code>```

Body:
I have such code example.

import java.util.LinkedList;
import java.util.List;
import java.util.stream.LongStream;

public class RemovedNumbers {

    public static List<long[]> removNb(long n) {
        System.out.println(n);
        long sum = ((n + 1) * n / 2);
        long minMultiplication = sum - 2 * n + 1;
        long minCandidate = (long) Math.sqrt(minMultiplication);

        LinkedList<long[]> list = new LinkedList<>();

        LongStream.rangeClosed(minCandidate, n)
                  .mapToObj(a -> new long[]{a, calculateB(a, sum)})
                  .filter(longs -> longs[0] > longs[1])
                  .filter(longs -> longs[1] <= n)
                  .filter(longs -> longs[0] * longs[1] == sum - longs[0] - longs[1])
                  .forEach(longs -> addArrays(list, longs));

        return list;
    }

    private static long calculateB(long a, long sum) {
        return (sum - a) / (a + 1);
    }

    private static void addArrays(final LinkedList<long[]> list, final long[] longs) {
        list.addFirst(new long[]{longs[1], longs[0]});
        list.add(longs);
    }
}

This code is complicated for me in LongStream part.
I don't get some points, so I need a help:

I examine LongStream class.

This class uses four methods: rangeClosed, mapToObj, filter, forEach (their description I found on Java docs). Unfortunately, now I am starting to examine java 1.8 version,  so I can't understand how it works and what's happens.

Where is appeared "a" in mapToObj? What is it? I don't see var "a" declaration in previous part of code.

As I've got lambda is made by such scheme: (arguments) -> (body). So the "a" is an argument, "new long[]..." - is a body. This part isn't causes any question for me. But the next one, whereis "longs" - argument, "longs[0] > longs[1]" - body, causes some questions. What is the var "longs"? It hasn't declaration in the past! HOW it appears? How it works?

Am I right that LongStream class can be writes in one line? Like: LongStream.rangeClosed().filter().filter().filter().forEach(); ?

Am I right that all methods execute consequently? By each other? The first rangeClosed, then mapToObj, then filter... or is there another order?

Thanks a lot!

Body:
Your third point kind of answers your second point - a is the parameter of the lambda expression passed to mapToObj.

If you can understand that, then your fourth point should be easy to understand as well. longs is the parameter for the lambda expression passed to filter. Remember that you can name your parameter names whatever you like. I guess the reason why the author of the code renamed the parameter to longs is because in the previous line, each long in the stream is mapped into a long[], so now it's a stream of long arrays.

Am I right that LongStream class can be writes in one line?

Yes, but you would end up with a super long line of code, so we almost never do that.

Am I right that all methods execute consequently? By each other? The first rangeClosed, then mapToObj, then filter... or is there another order?

The methods get called in that order, but the operations they do won't run immediately. This is the cool part of streams. The longs will only be mapToObj'ed and filter'ed when you do forEach, a terminal operation. In other words, mapToObj and filter are kind of like saying "this is what this stream should do..." and when you do forEach, you are saying "now do it!"

If you still don't get what streams are doing, try to think of them as a production line in a factory. At the start, you have longs on the conveyer belts. And then they pass through a machine, transforming each of them into a long[]. After that, they pass through three filters. These filters will push them off the conveyer belt unless the long arrays fulfil some condition.

EDIT:

If you want to write this code without lambdas, you can write it with anonymous classes instead:

LongStream.rangeClosed(minCandidate, n)
        .mapToObj(new LongFunction<long[]>() {
            @Override
            public long[] apply(long a) {
                return new long[]{a, calculateB(a, sum)};
            }
        })
        .filter(new Predicate<long[]>() {
            @Override
            public boolean test(long[] longs) {
                return longs[0] > longs[1] &&
                        longs[1] <= n &&
                        longs[0] * longs[1] == sum - longs[0] - longs[1];
            }
        })
        .forEach(new Consumer<long[]>() {
            @Override
            public void accept(long[] longs) {
                addArrays(list, longs);
            }
        });


问:
SAPUI5 oData V4 Read Object
How to read the object in UI5 with oData V4?
Basically I want to get the JSON object from the URL service:

Ths is my onInit function in the controller.

```<code>onInit: function() {
var this_ = this;

this.getView().addEventDelegate({
    onBeforeShow: function(evt) {

        var oModel = new sap.ui.model.json.JSONModel();
        oModel = sap.ui.getCore().getModel("appid");

        var app_id = oModel.getData().app_id;

        this_.getView().bindElement({
            path: "zearnModel>/zearn_summary(" + app_id + ")"
        });

    }
});
</code>```

}

答:
From the documentation:

The OData V4 model only supports data access using bindings. It does not provide any direct access to the data.

To get the raw JSON object, all you can do is use jQuery's ajax features to request the data:

```<code>$.get({
    url: "<your_service_url>/zearn_summary(" + app_id + ")",
    success: function(data) {
        // your success logic
    },
    error: function(error) {
        // your error logic
    }
});
</code>```

Title: SAPUI5 oData V4 Read Object

Body:
How to read the object in UI5 with oData V4?
Basically I want to get the JSON object from the URL service:

Ths is my onInit function in the controller.

onInit: function() {
var this_ = this;

this.getView().addEventDelegate({
    onBeforeShow: function(evt) {

        var oModel = new sap.ui.model.json.JSONModel();
        oModel = sap.ui.getCore().getModel("appid");

        var app_id = oModel.getData().app_id;

        this_.getView().bindElement({
            path: "zearnModel>/zearn_summary(" + app_id + ")"
        });

    }
});

}

Body:
From the documentation:

The OData V4 model only supports data access using bindings. It does not provide any direct access to the data.

To get the raw JSON object, all you can do is use jQuery's ajax features to request the data:

$.get({
    url: "<your_service_url>/zearn_summary(" + app_id + ")",
    success: function(data) {
        // your success logic
    },
    error: function(error) {
        // your error logic
    }
});


问:
using exec to execute a system command in a new process
I am trying to spawn a process that executes a system command, while my own program still proceeds and two processes will run in parallel. I am working on linux.

I looked up online and sounds like I should use exec() family. But it doesn't work quite as what I expected. For example, in the following code, I only see "before" being printed, ,but not "done".

I am curious if I am issing anything?

```<code>#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
   cout << "done" << endl;
}
</code>```

[UPDATE]

Thank you for your guys comments. Now my program looks like this. Everything works fine except at the end, I have to press enter to finish the program. I am not sure why I have to press the last enter?

```<code>#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   int pid = fork();
   cout << pid << endl;
   if (pid==0) {
      execl("/bin/ls", "ls", "-r", "-t", "-l", (char *) 0);
   }
   cout << "done" << endl;
}
</code>```

答:
You're missing a call to fork. All exec does is replace the current process image with that of the new program. Use fork to spawn a copy of your current process. Its return value will tell you whether it's the child or the original parent that's running. If it's the child, call exec.

Once you've made that change, it only appears that you need to press Enter for the programs to finish. What's actually happening is this: The parent process forks and executes the child process. Both processes run, and both processes print to stdout at the same time. Their output is garbled. The parent process has less to do than the child, so it terminates first. When it terminates, your shell, which was waiting for it, wakes and prints the usual prompt. Meanwhile, the child process is still running. It prints more file entries. Finally, it terminates. The shell isn't paying attention to the child process (its grandchild), so the shell has no reason to re-print the prompt. Look more carefully at the output you get, and you should be able to find your usual command prompt buried in the ls output above.

The cursor appears to be waiting for you to press a key. When you do, the shell prints a prompt, and all looks normal. But as far as the shell was concerned, all was already normal. You could have typed another command before. It would have looked a little strange, but the shell would have executed it normally because it only receives input from the keyboard, not from the child process printing additional characters to the screen.

If you use a program like top in a separate console window, you can watch and confirm that both programs have already finished running before you have to press Enter.

Body:
I am trying to spawn a process that executes a system command, while my own program still proceeds and two processes will run in parallel. I am working on linux.

I looked up online and sounds like I should use exec() family. But it doesn't work quite as what I expected. For example, in the following code, I only see "before" being printed, ,but not "done".

I am curious if I am issing anything?

#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
   cout << "done" << endl;
}

[UPDATE]

Thank you for your guys comments. Now my program looks like this. Everything works fine except at the end, I have to press enter to finish the program. I am not sure why I have to press the last enter?

#include <unistd.h>
#include <iostream>

using namespace std;

main()
{
   cout << "before" << endl;
   int pid = fork();
   cout << pid << endl;
   if (pid==0) {
      execl("/bin/ls", "ls", "-r", "-t", "-l", (char *) 0);
   }
   cout << "done" << endl;
}


问:
Order Results by a Column’s Rows
The reply selected as the best answer in this thread was helpful. But, it seems “ORDER BY FIELD” is not supported in SQLite.

Using this example, how can I set a specific order to the rows in the Month column?

答:
There is no ORDER BY FIELD in SQLite.

Instead you can do it with conditional ordering:

```<code>ORDER BY CASE month
    WHEN 'JAN' THEN 1
    WHEN 'FEB' THEN 2
    WHEN 'MAR' THEN 3
    WHEN 'APR' THEN 4
    WHEN 'MAY' THEN 5
    WHEN 'JUN' THEN 6
END
</code>```

or by using INSTR():

```<code>ORDER BY INSTR('JAN,FEB,MAR,APR,MAY,JUN', month)
</code>```

you can omit the commas or replace with any other separator.

Title: Order Results by a Column’s Rows

Body:
There is no ORDER BY FIELD in SQLite.

Instead you can do it with conditional ordering:

ORDER BY CASE month
    WHEN 'JAN' THEN 1
    WHEN 'FEB' THEN 2
    WHEN 'MAR' THEN 3
    WHEN 'APR' THEN 4
    WHEN 'MAY' THEN 5
    WHEN 'JUN' THEN 6
END

or by using INSTR():

ORDER BY INSTR('JAN,FEB,MAR,APR,MAY,JUN', month)

you can omit the commas or replace with any other separator.


问:
Remote Access to Local ASP.NET Core Applications From IP Address?
I want to (call)debug my asp.net core application from remote computer or mobile device? please help me. In standard .net add this code in .vs\config\applicationhost.config when change <binding protocol="http" bindingInformation="*:21918:localhost" /> to <binding protocol="http" bindingInformation="*:21918:*" />  its worked.

```<code>           <site name="project" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="F:\users\Api" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:21918:*" />
                </bindings>
            </site>
</code>```

答:
you can follow the instructions below on how to solve your problem and go through all these problems.
1- Be sure you don’t ave any open Visual Studio instance.

2- Open the file  %userprofile%\Documenti\IISExpress\config\applicationhost.config  , being %userprofile% your user folder – like  C:\Users\YourUsername\.

3-Look for the entry corresponding to the web application we want to modify and change its binding element in the following way:
<binding protocol="http" bindingInformation="*:<port>:*" /> All we need to do there is to replace a couple of localhost with *, leaving the automatically assigned <port> as it is. If you really need to change that port, replace it with another valid, free TCP port (like 8080) and perform the following step. Otherwise, skip it and go to the step next to it.

4-If you changed the automatically assigned TCP port you also need to open your web application project (.csproj) and solution (.sln) files and ensure there are no references to the previous port: they can be there or not depending on your choosen project type (Web Application, MVC App, Web Site, etc.). If that’s the case, replace the old port with the new one.

5-Open a Command Prompt (with Administrator permissions) and type the following:
netsh http add urlacl url=http://*:<port>/ user=everyone Putting the application TCP port in place of . If you get an error messae (1789) it means that the Everyone user group is not present on your system, something who can occur in some Windows localizations. If that’s the case, just replace everyone with the corresponding user group name. Instead than doing this step you could also try and execute Visual Studio with administrator permissions.

6-Open Windows Firewall advanced configuration panel and add an inbound rule to enable the inbound traffic for the application IISExpress.exe OR for the TCP port used by your web application. If you disabled it for another product, do the same with it. If you ain’t using any – are you sure? – you can either take the chance to fill the void and then perform the above or just skip this step.

Once you did this you can launch Visual Studio and run your application in Debug or Release mode: you should be able to access it from any external, network-connected device using the following web address:
http://<lan-ip-address>:<port>/

Body:
I want to (call)debug my asp.net core application from remote computer or mobile device? please help me. In standard .net add this code in .vs\config\applicationhost.config when change <binding protocol="http" bindingInformation="*:21918:localhost" /> to <binding protocol="http" bindingInformation="*:21918:*" />  its worked.

           <site name="project" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="F:\users\Api" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:21918:*" />
                </bindings>
            </site>


问:
Does spring boot come in to picture only while creating the project?
I've been learning spring boot for a while and as per my understanding, we use spring boot only to create the project along with dependencies and embedded servers. It doesn't have much of a role while working on the project or after the project is created.

I mean, if i were to work on an enterprise application for a company, chances are that, there is already a project created using springboot and I don't have to really use spring boot anywhere while working on that project.

Is my understanding correct?

I've tired googling, but did not find a clear answer.

答:
No. You may still need to use the following spring-boot features after creating a project :

Externalise the application properties

Test the application using testing utilities and annotations provided by spring-boot

Use its auto-configuration feature to quickly configure if you need to enhance your application with other library/framework afterwards.

Use its developer tool to make you have a better Dev experience (e.g  automatic restart the app when code changes , hot-reload static content etc.)

Use Actuator to monitor your application health and gather metrics.


问:
Matching based on various types and object attributes
I have a list of objects from which I'm trying to filter objects based on selected criteria returning a list of matches. The attributes are strings, integers, floats and objects. The problem I have is trying to filter based on object attributes, I'd like to do this:

findOrder(d, signal='CO', contract.symbol=1)

I cannot simply compare the objects by themselves as I only need to match based on the most important attributes and the attributes differ on various objects.

Thus far I can successfully flatten the objects into a dict and then do a simple dictionary comparison. Yet this is very ugly and I suspect slow:

findOrder(d, signal='CO', contractSymbol=1)

```<code>class emptyObj(object):
    def __init__(self, a, b):
        self.Symbol = a
        self.Order = b
s = emptyObj(a=1, b=2)

class toObj(object):
    def __init__(self, d): [setattr(self, a, b) for a, b in d.items()]

def findOrder(d, **kwargs):
    def flatten(di):
        ls = []
        for o in di:
            e = {}
            for k, v in o.__dict__.items():
                if isinstance(v, (int, float, str, tuple, list, dict)):
                    e[k] = v
                else:
                    for attr, val in v.__dict__.items(): e[str(k)+str(attr)] = val
            ls.append(e)
        return ls

    g = flatten(d)
    l = [k for k in g if kwargs.items() <= k.items()]
    if l: return l

d = [toObj({'id':1250, 'signal': 'CO', 'contract': s}),
     toObj({'id':1252, 'signal': 'LO', 'contract': s})]

print(findOrder(d, signal='CO'))
</code>```

Is there a more optimal and straightforward way to do this?

答:
If you’re trying to filter objects by attribute, use either filter or a list comprehension with a function that checks attributes:

```<code>def check_attrs(**kw):
    def wrapper(obj):
        return all(getattr(obj, k) == v for k, v in kw.items())
    return wrapper
</code>```

Then you filter the objects:

```<code>filtered = list(filter(check_attrs(signal='CO'), objects))
</code>```

Or...

```<code>filtered = [obj for obj in objects
            if check_attrs(signal='CO')(obj)]
</code>```

Body:
I have a list of objects from which I'm trying to filter objects based on selected criteria returning a list of matches. The attributes are strings, integers, floats and objects. The problem I have is trying to filter based on object attributes, I'd like to do this:

findOrder(d, signal='CO', contract.symbol=1)

I cannot simply compare the objects by themselves as I only need to match based on the most important attributes and the attributes differ on various objects.

Thus far I can successfully flatten the objects into a dict and then do a simple dictionary comparison. Yet this is very ugly and I suspect slow:

findOrder(d, signal='CO', contractSymbol=1)

class emptyObj(object):
    def __init__(self, a, b):
        self.Symbol = a
        self.Order = b
s = emptyObj(a=1, b=2)

class toObj(object):
    def __init__(self, d): [setattr(self, a, b) for a, b in d.items()]

def findOrder(d, **kwargs):
    def flatten(di):
        ls = []
        for o in di:
            e = {}
            for k, v in o.__dict__.items():
                if isinstance(v, (int, float, str, tuple, list, dict)):
                    e[k] = v
                else:
                    for attr, val in v.__dict__.items(): e[str(k)+str(attr)] = val
            ls.append(e)
        return ls

    g = flatten(d)
    l = [k for k in g if kwargs.items() <= k.items()]
    if l: return l

d = [toObj({'id':1250, 'signal': 'CO', 'contract': s}),
     toObj({'id':1252, 'signal': 'LO', 'contract': s})]

print(findOrder(d, signal='CO'))

Is there a more optimal and straightforward way to do this?

Body:
If you’re trying to filter objects by attribute, use either filter or a list comprehension with a function that checks attributes:

def check_attrs(**kw):
    def wrapper(obj):
        return all(getattr(obj, k) == v for k, v in kw.items())
    return wrapper

Then you filter the objects:

filtered = list(filter(check_attrs(signal='CO'), objects))

Or...

filtered = [obj for obj in objects
            if check_attrs(signal='CO')(obj)]


问:
Set a variable to what json_encode() outputs in PHP
json_encode() returns a string...

So shouldn't the following code work?

```<code>class TestClass {
    private $test = json_encode("test");
}
</code>```

PHP outputs

```<code>Parse error: syntax error, unexpected '(', expecting ',' or ';' in /home/testuser/public_html/test.php on line 10
</code>```

答:
You can not assign expression or any variable while declaring class property. The literal constants such as __FILE__ are allowed here.

they have to be a literal value, such as a string, or a constant.

There all work.

```<code>private $test= 98;
private $test= "test value";
private $test= CONSTANT;
private $test= __FILE__;
</code>```

But these will not

```<code>private $test= 98*2;
private $test= "test value"."some other value";
</code>```

You can use constructor

```<code> function __construct() {
        $this->test = json_encode("test");
    }
</code>```

Body:
json_encode() returns a string...

So shouldn't the following code work?

class TestClass {
    private $test = json_encode("test");
}

PHP outputs

Parse error: syntax error, unexpected '(', expecting ',' or ';' in /home/testuser/public_html/test.php on line 10

Body:
You can not assign expression or any variable while declaring class property. The literal constants such as __FILE__ are allowed here.

they have to be a literal value, such as a string, or a constant.

There all work.

private $test= 98;
private $test= "test value";
private $test= CONSTANT;
private $test= __FILE__;

But these will not

private $test= 98*2;
private $test= "test value"."some other value";

You can use constructor

 function __construct() {
        $this->test = json_encode("test");
    }


问:
What are limitations of reader macros in Common Lisp
I have my own Lisp interpreter in JavaScript that I work for some time now, and now I want to implement reader macros like in Common Lisp.

I've created Streams (almost working except for special symbols like ,@ , ` ') but it freezes the browser for a few seconds when it's loading the page with included scripts (lisp files that have 400 lines of code). This is because my Streams are based on substring function. If I first split tokens and then use TokenStream that iterate over tokens, it works fine.

So my question is this, is string streams really something that is in Common Lisp? Can you add reader macros that create whole new syntax like Python inside CL, this simplify to question can I implement """ macro (not sure if you can have 3 characters as reader macro) or other character that will implement template literal inside lisp for instance:

```<code>(let ((foo 10) (bar 20))
  {lorem ipsum ${baz} and ${foo}})
</code>```

or

```<code>(let ((foo 10) (bar 20))
  ""lorem ipsum ${baz} and ${foo}"")
</code>```

or

```<code>(let ((foo 10) (bar 20))
  :"lorem ipsum ${baz} and ${foo}")
</code>```

would yield string

```<code>"lorem ipsum 10 and 20"
</code>```

is something like this possible in Common Lisp and how hard would be to implement #\{ or #\: as reader macro?

The only way I can think of to have template literals in Lisp is something like this:

```<code>  (let ((foo 10) (bar 20))
    (tag "lorem ipsum ${baz} and ${foo}")))
</code>```

where tag is macro that return strings with ${} as free variable. Can reader macro also return lisp code that is evaluated?

And another question can you implement reader macros like this:

```<code>(list :foo:bar)

(list foo:bar)
</code>```

where : is reader macro and if it's before symbols it convert symbol to

```<code>foo.bar
</code>```

and if it's inside it throw error. I'm asking this because with token based macros :foo:bar and foo:bar will be symbols and will not be processed by my reader macros.

and one more question can reader macro be put in one line and second line use it? This will definitely be only possible with string streams and from what I've tested not possible with interpreter written in JavaScript.

答:
There are some limitations in the sense that it is pretty hard to, for instance, intervene in the interpretation of tokens in any way short of 'implement your own token interpreter from scratch'.  But, well, you could if you wanted to do just that: the problem is that your code would need to deal with numbers & things as well as the existing code does and things like floating-point parsing are pretty fiddly to get right.

But the macro functions associated with macro characters get the stream that is being read, and they are free to read as much or as little of the stream as they like, and return any kind of object (or no object, which is how comments are implemented).

I would strongly recommend reading chapters 2 & 23 of the hyperspec, and then playing with an implementation.  When you play with the implementation be aware that it is just astonishingly easy to completely wedge things by mucking around with the reader.  At the minimum I would suggest code like this:

```<code>(defparameter *my-readtable* (copy-readtable nil))

;;; Now muck around with *my-readtable*, *not* the default readtable
;;;

(defun experimentally-read ((&key (stream *standard-input*)
                                  (readtable *my-raedtable*)))
  (let ((*readtable* readtable))
    (read stream)))
</code>```

This gives you at least some chance to recover from catastrophe: if you can once abort experimentally-read then you are back in a position where *readtable* is something sensible.

Here is a fairly useless example which shows how much you can subvert the syntax with macro characters: a macro character definition which will cause ( ...) to be read as a string.  This may not be fully debugged, and as I say I can see no use for it.

```<code>(defun mindless-parenthesized-string-reader (stream open-paren)
  ;; Cause parenthesized groups to be read as strings:
  ;; - (a b) -> "a b"
  ;; - (a (b c) d) -> "a (b c) d"
  ;; - (a \) b) -> "a ) b"
  ;; This serves no useful purpose that I can see.  Escapes (with #\))
  ;; and nested parens are dealt with.
  ;;
  ;; Real Programmers would write this with LOOP, but that was too
  ;; hard for me.  This may well not be completely right.
  (declare (ignore open-paren))
  (labels ((collect-it (escaping depth accum)
             (let ((char (read-char stream t nil t)))
               (if escaping
                   (collect-it nil depth (cons char accum))
                 (case char
                   ((#\\)
                    (collect-it t depth accum))
                   ((#\()
                    (collect-it nil (1+ depth) (cons char accum)))
                   ((#\))
                    (if (zerop depth)
                        (coerce (nreverse accum) 'string)
                      (collect-it nil (1- depth) (cons char accum))))
                   (otherwise
                      (collect-it nil depth (cons char accum))))))))
    (collect-it nil 0 '())))

(defvar *my-readtable* (copy-readtable nil))

(set-macro-character #\( #'mindless-parenthesized-string-reader
                     nil *my-readtable*)

(defun test-my-rt (&optional (stream *standard-input*))
  (let ((*readtable* *my-readtable*))
    (read stream)))
</code>```

And now

```<code>> (test-my-rt)
12
12

> (test-my-rt)
x
x

> (test-my-rt)
(a string (with some parens) and \) and the end)
"a string (with some parens) and ) and the end"
</code>```

Body:
I have my own Lisp interpreter in JavaScript that I work for some time now, and now I want to implement reader macros like in Common Lisp.

I've created Streams (almost working except for special symbols like ,@ , ` ') but it freezes the browser for a few seconds when it's loading the page with included scripts (lisp files that have 400 lines of code). This is because my Streams are based on substring function. If I first split tokens and then use TokenStream that iterate over tokens, it works fine.

So my question is this, is string streams really something that is in Common Lisp? Can you add reader macros that create whole new syntax like Python inside CL, this simplify to question can I implement """ macro (not sure if you can have 3 characters as reader macro) or other character that will implement template literal inside lisp for instance:

(let ((foo 10) (bar 20))
  {lorem ipsum ${baz} and ${foo}})

or

(let ((foo 10) (bar 20))
  ""lorem ipsum ${baz} and ${foo}"")

or

(let ((foo 10) (bar 20))
  :"lorem ipsum ${baz} and ${foo}")

would yield string

"lorem ipsum 10 and 20"

is something like this possible in Common Lisp and how hard would be to implement #\{ or #\: as reader macro?

The only way I can think of to have template literals in Lisp is something like this:

  (let ((foo 10) (bar 20))
    (tag "lorem ipsum ${baz} and ${foo}")))

where tag is macro that return strings with ${} as free variable. Can reader macro also return lisp code that is evaluated?

And another question can you implement reader macros like this:

(list :foo:bar)

(list foo:bar)

where : is reader macro and if it's before symbols it convert symbol to

foo.bar

and if it's inside it throw error. I'm asking this because with token based macros :foo:bar and foo:bar will be symbols and will not be processed by my reader macros.

and one more question can reader macro be put in one line and second line use it? This will definitely be only possible with string streams and from what I've tested not possible with interpreter written in JavaScript.

Body:
There are some limitations in the sense that it is pretty hard to, for instance, intervene in the interpretation of tokens in any way short of 'implement your own token interpreter from scratch'.  But, well, you could if you wanted to do just that: the problem is that your code would need to deal with numbers & things as well as the existing code does and things like floating-point parsing are pretty fiddly to get right.

But the macro functions associated with macro characters get the stream that is being read, and they are free to read as much or as little of the stream as they like, and return any kind of object (or no object, which is how comments are implemented).

I would strongly recommend reading chapters 2 & 23 of the hyperspec, and then playing with an implementation.  When you play with the implementation be aware that it is just astonishingly easy to completely wedge things by mucking around with the reader.  At the minimum I would suggest code like this:

(defparameter *my-readtable* (copy-readtable nil))

;;; Now muck around with *my-readtable*, *not* the default readtable
;;;

(defun experimentally-read ((&key (stream *standard-input*)
                                  (readtable *my-raedtable*)))
  (let ((*readtable* readtable))
    (read stream)))

This gives you at least some chance to recover from catastrophe: if you can once abort experimentally-read then you are back in a position where *readtable* is something sensible.

Here is a fairly useless example which shows how much you can subvert the syntax with macro characters: a macro character definition which will cause ( ...) to be read as a string.  This may not be fully debugged, and as I say I can see no use for it.

(defun mindless-parenthesized-string-reader (stream open-paren)
  ;; Cause parenthesized groups to be read as strings:
  ;; - (a b) -> "a b"
  ;; - (a (b c) d) -> "a (b c) d"
  ;; - (a \) b) -> "a ) b"
  ;; This serves no useful purpose that I can see.  Escapes (with #\))
  ;; and nested parens are dealt with.
  ;;
  ;; Real Programmers would write this with LOOP, but that was too
  ;; hard for me.  This may well not be completely right.
  (declare (ignore open-paren))
  (labels ((collect-it (escaping depth accum)
             (let ((char (read-char stream t nil t)))
               (if escaping
                   (collect-it nil depth (cons char accum))
                 (case char
                   ((#\\)
                    (collect-it t depth accum))
                   ((#\()
                    (collect-it nil (1+ depth) (cons char accum)))
                   ((#\))
                    (if (zerop depth)
                        (coerce (nreverse accum) 'string)
                      (collect-it nil (1- depth) (cons char accum))))
                   (otherwise
                      (collect-it nil depth (cons char accum))))))))
    (collect-it nil 0 '())))

(defvar *my-readtable* (copy-readtable nil))

(set-macro-character #\( #'mindless-parenthesized-string-reader
                     nil *my-readtable*)

(defun test-my-rt (&optional (stream *standard-input*))
  (let ((*readtable* *my-readtable*))
    (read stream)))

And now

> (test-my-rt)
12
12

> (test-my-rt)
x
x

> (test-my-rt)
(a string (with some parens) and \) and the end)
"a string (with some parens) and ) and the end"


答:
I mean, if i were to work on an enterprise application for a company, chances are that, there is already a project created using springboot and I don't have to really use spring boot anywhere while working on that project.

I think you can say pretty much the same about any framework out there. I can't agree with this statement in general.

Every framework (including spring boot) provides a set of features that you may opt to use or not to use in your project.

So yes, for each existing microservice you'll have a @SpringBootApplication class.
Also probably set of configurations / practices how to work with configurations.
You'll already have also spring beans on existing project.

However software constantly evolves (otherwise it doesn't make sense to hire programmers, you know).

So when you (as a new employee) need to create a new micro service then, congratulations, you're using Spring boot features.

Other day-to-day tasks include (just a couple of example out of the head):

Create Integration Tests (@SpringBootTest)

Define new configuration Properties

Use Actuator

Use Metrics + define new metrics

Reconfigure Logging

Writing Liquidbase/Flyway migrations

Integrate new set of beans (Configurations)

Use Autoconfigurations

and so on and so forth.

If you want to really understand what you're doing while implementing these tasks you should know how do relevant features provided by spring boot work.

Title: Does spring boot come in to picture only while creating the project?

Body:
I've been learning spring boot for a while and as per my understanding, we use spring boot only to create the project along with dependencies and embedded servers. It doesn't have much of a role while working on the project or after the project is created.

I mean, if i were to work on an enterprise application for a company, chances are that, there is already a project created using springboot and I don't have to really use spring boot anywhere while working on that project.

Is my understanding correct?

I've tired googling, but did not find a clear answer.


问:
Delay when calling setState multiple times
I am developing an application that has two listings. When you click on a product from the first listing the second listing is incremented.

My problem is that there is a delay in clicking the products in the first listing. It takes milliseconds. And I discovered that the delay occurs when setState is called. SetState causes a slight delay.

if I comment the setState everything works without delay.

my code

```<code>selectProduct(item, quantidade){

  ....

  this.setState({ itensNota });
}
</code>```

my problem

I do not know the reason for the problem. I believe the problem happens due to the react native rendering the entire screen every time the setState is called. But I do not know how to solve this problem. The customer complained about the delay and I need to solve this problem. can anybody help me?

**************** EDIT ****************

my complete code

https://github.com/renatosistemasvc/temo/blob/master/subir.js

答:
The code seems OK. One thing that might make the performance better is to make selectProduct async. This way, it returns right away and the list items won't be so slow when being pressed, although the update of the other list will still take some time:

```<code>selectProduct = async (item, quantidade) => { ... }
</code>```

Other things that you should take into consideration are:

Disable  the remote debugger. Sometimes React Native apps are a bit slow when debugging remotely.

Test the app in another device (preferably a better one). If it behaves fine in that device, then it's the device you're using currently that is causing the problem, because of its low parameters.

Body:
I am developing an application that has two listings. When you click on a product from the first listing the second listing is incremented.

My problem is that there is a delay in clicking the products in the first listing. It takes milliseconds. And I discovered that the delay occurs when setState is called. SetState causes a slight delay.

if I comment the setState everything works without delay.

my code

selectProduct(item, quantidade){

  ....

  this.setState({ itensNota });
}

my problem

I do not know the reason for the problem. I believe the problem happens due to the react native rendering the entire screen every time the setState is called. But I do not know how to solve this problem. The customer complained about the delay and I need to solve this problem. can anybody help me?

**************** EDIT ****************

my complete code

https://github.com/renatosistemasvc/temo/blob/master/subir.js

Body:
The code seems OK. One thing that might make the performance better is to make selectProduct async. This way, it returns right away and the list items won't be so slow when being pressed, although the update of the other list will still take some time:

selectProduct = async (item, quantidade) => { ... }

Other things that you should take into consideration are:

Disable  the remote debugger. Sometimes React Native apps are a bit slow when debugging remotely.

Test the app in another device (preferably a better one). If it behaves fine in that device, then it's the device you're using currently that is causing the problem, because of its low parameters.


问:
Any reasons for the E-commerce angular app's product pages showing different source code when viewing it in the browser view source?
Recently, I have noticed this type of issue in an angular app. Any reasons for this issue? Any tools to track it?

Issue: E-commerce angular app earlier created product pages showing different source code when viewing it in the browser view source.

Actual Result: Different type of view source is showing for earlier created products. But newly created products showing the correct source code. When changing the earlier created product's URL, it is then showing the correct source code.

Expected Result: All the product pages should show the correct source code.

Note: No Server side cached (Varnished or Memcached), CDN or GTM custom HTML tags have implemented. Hosted with the Amazon hosting.

Thanks.

答:
Finally, I found the root cause of this issue. I just want to share it with you, just in case if you would face a similar situation and look for the solutions.

I have found earlier pre-rendered static HTML pages in the server root folder with the same URL path.

```<code>Ex: /products/productname/index.html
</code>```

Hence, when we are viewing the browser view source, it is showing that old static HTML page content instead of the correct source code. This issue got resolved after removing those old static HTML pages. I hope this might be helpful to someone else too.

Thanks.

Body:
Finally, I found the root cause of this issue. I just want to share it with you, just in case if you would face a similar situation and look for the solutions.

I have found earlier pre-rendered static HTML pages in the server root folder with the same URL path.

Ex: /products/productname/index.html

Hence, when we are viewing the browser view source, it is showing that old static HTML page content instead of the correct source code. This issue got resolved after removing those old static HTML pages. I hope this might be helpful to someone else too.

Thanks.


答:
Each lambda expression implements a functional interface, or to be more specific, it implements the single abstract method of that functional interface.

Therefore, in a -> new long[]{a, calculateB(a, sum)}, a is the argument of the method implemented by the functional interface. Since mapToObj accepts an argument of type LongFunction, this lambda expression implements the R apply(long value) method of that interface, which means that lambda expression can also be written as (long a) -> new long[]{a, calculateB(a, sum)}.

This mapToObj call transforms the LongStream to a Stream<long[]>, so the lambda expression of the following filter call - longs -> longs[0] > longs[1] can also be written as (long[] longs) -> longs[0] > longs[1] - it implements the functional interface Predicate<long[]>, which means it implements boolean test(long[] t).

Yes, you can write this entire stream pipeline in a single line, but it would be more readable split into multiple lines.

Am I right that all methods execute consequently? By each other? The first rangeClosed, then mapToObj, then filter... or is there another order

Not exactly. While each intermediate method produces an output used as input to the next method, the evaluation of these methods only begins once the terminal operation - forEach in this case - is executed. And these operations don't necessarily process all the elements of the Stream. For example, if the terminal operation would be firstFirst() instead of forEach, the pipeline would only process enough elements until the first element that passes all the filters is found.

Title: Unable to understand lambdas AND longstream methods

Body:
I have such code example.

import java.util.LinkedList;
import java.util.List;
import java.util.stream.LongStream;

public class RemovedNumbers {

    public static List<long[]> removNb(long n) {
        System.out.println(n);
        long sum = ((n + 1) * n / 2);
        long minMultiplication = sum - 2 * n + 1;
        long minCandidate = (long) Math.sqrt(minMultiplication);

        LinkedList<long[]> list = new LinkedList<>();

        LongStream.rangeClosed(minCandidate, n)
                  .mapToObj(a -> new long[]{a, calculateB(a, sum)})
                  .filter(longs -> longs[0] > longs[1])
                  .filter(longs -> longs[1] <= n)
                  .filter(longs -> longs[0] * longs[1] == sum - longs[0] - longs[1])
                  .forEach(longs -> addArrays(list, longs));

        return list;
    }

    private static long calculateB(long a, long sum) {
        return (sum - a) / (a + 1);
    }

    private static void addArrays(final LinkedList<long[]> list, final long[] longs) {
        list.addFirst(new long[]{longs[1], longs[0]});
        list.add(longs);
    }
}

This code is complicated for me in LongStream part.
I don't get some points, so I need a help:

I examine LongStream class.

This class uses four methods: rangeClosed, mapToObj, filter, forEach (their description I found on Java docs). Unfortunately, now I am starting to examine java 1.8 version,  so I can't understand how it works and what's happens.

Where is appeared "a" in mapToObj? What is it? I don't see var "a" declaration in previous part of code.

As I've got lambda is made by such scheme: (arguments) -> (body). So the "a" is an argument, "new long[]..." - is a body. This part isn't causes any question for me. But the next one, whereis "longs" - argument, "longs[0] > longs[1]" - body, causes some questions. What is the var "longs"? It hasn't declaration in the past! HOW it appears? How it works?

Am I right that LongStream class can be writes in one line? Like: LongStream.rangeClosed().filter().filter().filter().forEach(); ?

Am I right that all methods execute consequently? By each other? The first rangeClosed, then mapToObj, then filter... or is there another order?

Thanks a lot!


问:
Why isn't my nb-search appearing in my page?
I created a homepage that has a navbar which I intended on putting nebular search in since I really liked it's design but for some reason after following their instructions I still couldn't get it to appear.</p>

```<code><nb-layout>
<nb-layout-header fixed>
    <nb-search type="rotate-layout></nb-search>
</nb-layout-header>
</nb-layout>
</code>```

答:
Most likely cause of your issue

https://github.com/akveo/nebular/issues/1275

You need to add "./node_modules/nebular-icons/scss/nebular-icons.scss"
to angular.json

This makes the search icon appear.

In depth

I managed to get this working by following the getting started tutorial https://akveo.github.io/nebular/docs/guides/install-based-on-starter-kit#production-bundle

I decided to use the html from their website:

```<code>  <nb-layout>
    <nb-layout-header fixed>
      <nb-search type="rotate-layout"></nb-search>

    </nb-layout-header>

    <nb-sidebar>
    </nb-sidebar>

    <nb-layout-column>
      <nb-card accent="info">
        <nb-card-header>You searched for:</nb-card-header>
        <nb-card-body>
          <h3>{{ value || '-' }}</h3>
        </nb-card-body>
      </nb-card>
    </nb-layout-column>
  </nb-layout>
</code>```

The tricky thing with this is making sure to import all the correct modules:
NbThemeModule.forRoot({ name: 'default' }), was put in when I installed @nebula/themes

```<code>import {
  NbThemeModule,
  NbLayoutModule,
  NbCardModule,
  NbSidebarModule,
  NbSidebarService,
  NbSearchModule,
} from '@nebular/theme';

@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    NbThemeModule.forRoot({ name: 'default' }),
    NbLayoutModule,
    NbCardModule,
    NbSidebarModule,
    NbSearchModule
  ],
  providers: [NbSidebarService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Again re-using the example code on the website:

```<code>@Component({
  ...
})
export class TestComponent implements OnInit {

  value = '';

  constructor(private searchService: NbSearchService) {

    this.searchService.onSearchSubmit()
      .subscribe((data: any) => {
        this.value = data.term;
      })

  }

  ngOnInit() {
  }

}
</code>```

Body:
I created a homepage that has a navbar which I intended on putting nebular search in since I really liked it's design but for some reason after following their instructions I still couldn't get it to appear.

<nb-layout>
<nb-layout-header fixed>
    <nb-search type="rotate-layout></nb-search>
</nb-layout-header>
</nb-layout>

Body:
Most likely cause of your issue

https://github.com/akveo/nebular/issues/1275

You need to add "./node_modules/nebular-icons/scss/nebular-icons.scss"
to angular.json

This makes the search icon appear.

In depth

I managed to get this working by following the getting started tutorial https://akveo.github.io/nebular/docs/guides/install-based-on-starter-kit#production-bundle

I decided to use the html from their website:

  <nb-layout>
    <nb-layout-header fixed>
      <nb-search type="rotate-layout"></nb-search>

    </nb-layout-header>

    <nb-sidebar>
    </nb-sidebar>

    <nb-layout-column>
      <nb-card accent="info">
        <nb-card-header>You searched for:</nb-card-header>
        <nb-card-body>
          <h3>{{ value || '-' }}</h3>
        </nb-card-body>
      </nb-card>
    </nb-layout-column>
  </nb-layout>

The tricky thing with this is making sure to import all the correct modules:
NbThemeModule.forRoot({ name: 'default' }), was put in when I installed @nebula/themes

import {
  NbThemeModule,
  NbLayoutModule,
  NbCardModule,
  NbSidebarModule,
  NbSidebarService,
  NbSearchModule,
} from '@nebular/theme';

@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    NbThemeModule.forRoot({ name: 'default' }),
    NbLayoutModule,
    NbCardModule,
    NbSidebarModule,
    NbSearchModule
  ],
  providers: [NbSidebarService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Again re-using the example code on the website:

@Component({
  ...
})
export class TestComponent implements OnInit {

  value = '';

  constructor(private searchService: NbSearchService) {

    this.searchService.onSearchSubmit()
      .subscribe((data: any) => {
        this.value = data.term;
      })

  }

  ngOnInit() {
  }

}


问:
Kivy and Google Play 64-bit
As you may know, from August 1, 2019 all Android-releases must be compliant with the Google Play 64-bit requirement.
Will Kivy + Buildozer allow us to create such apps?

Thank you in advance!

答:
From the comments, here's an open issue on the Kivy repository about plans for Kivy to support Google's upcoming 64-bit binary requirement. Here's a comment from one of the devs:

In https://android-developers.googleblog.com/2017/12/improving-app-security-and-performance.html:

In August 2019, Play will require that new apps and app updates with native libraries provide 64-bit versions in addition to their 32-bit versions.

I think we should default to arm64-v8a to prevent issues later, and start thinking how we can do multiple targets compilation and embedded them in one APK.

...which has three thumbs-ups.

Title: Kivy and Google Play 64-bit


答:
Am I right that LongStream class can be writes in one line?

What you're witnessing here is method chaining. This is where method after method can get chained to eachother. This can be done for almost all classes.

Everything else is pretty much answered by Sweeper.


问:
PHP array_search
Is there any function which will accomplish the equivalent of array_search with a $needle that is an array? Like, this would be an ideal solution:

```<code>$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack
$search = array_search( $needle, $haystack );
</code>```

If no function, any other functions that accept needles which may be arrays that I can use to create a custom function?

答:
This might help build your function:</p>

```<code>$intersection = array_intersect($needle, $haystack);

if ($intersection) // $haystack has at least one of $needle

if (count($intersection) == count($needle)) // $haystack has every needle
</code>```

Title: PHP array_search

Body:
Is there any function which will accomplish the equivalent of array_search with a $needle that is an array? Like, this would be an ideal solution:

$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack
$search = array_search( $needle, $haystack );

If no function, any other functions that accept needles which may be arrays that I can use to create a custom function?

Body:
This might help build your function:

$intersection = array_intersect($needle, $haystack);

if ($intersection) // $haystack has at least one of $needle

if (count($intersection) == count($needle)) // $haystack has every needle


问:
Is there an easy way of migrating from Amazon Redshift to Microsoft Azure Data Warehouse?
I want to migrate from Amazon Redshift to Microsoft Azure. Is there an easy way of doing this copy?</p>

答:
There are a lot of ways to get data into redshift.
But even inside amazon there's only one way getting data out of redshift:

unload to s3

https://docs.aws.amazon.com/redshift/latest/dg/r_UNLOAD.html

On the other hand microsoft appears to provide a connector
For migrating:

https://learn.microsoft.com/en-us/azure/data-factory/connector-amazon-redshift