问:
Getting Developer Metadata using Google Script API on Google Apps Script
I am trying to get the developer metadata about a spreadsheet using the Google Script API, as found on this website.

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata/search

I have tried the following, however I am getting no response back?  Can anyone see where I am going wrong?

```<code>    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var fileId = ss.getId();
    var token = ScriptApp.getOAuthToken();

    var paramsPost = {
        method: 'post',
        headers: {
            Authorization: 'Bearer ' + token
        },
        muteHttpExceptions: true,
        contentType: 'application/json',
        payload: JSON.stringify({
            dataFilters: [{
                developerMetadataLookup: {
                    locationType: 'COLUMN'
                }
            }]
        })
    };

    var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + fileId + '?developerMetadata:search';
    var res = UrlFetchApp.fetch(url, paramsPost);
    var data = JSON.parse(res.getContentText());
</code>```

答:
In order to use the method of spreadsheets.developerMetadata.search of Sheets API, please modify the endpoint as follows.

From:

```<code>var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + fileId + '?developerMetadata:search';
</code>```

To:

```<code>var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + fileId + '/developerMetadata:search';
</code>```

? of '?developerMetadata:search' is /.

Reference:

spreadsheets.developerMetadata.search

Body:
I am trying to get the developer metadata about a spreadsheet using the Google Script API, as found on this website.

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.developerMetadata/search

I have tried the following, however I am getting no response back?  Can anyone see where I am going wrong?

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var fileId = ss.getId();
    var token = ScriptApp.getOAuthToken();

    var paramsPost = {
        method: 'post',
        headers: {
            Authorization: 'Bearer ' + token
        },
        muteHttpExceptions: true,
        contentType: 'application/json',
        payload: JSON.stringify({
            dataFilters: [{
                developerMetadataLookup: {
                    locationType: 'COLUMN'
                }
            }]
        })
    };

    var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + fileId + '?developerMetadata:search';
    var res = UrlFetchApp.fetch(url, paramsPost);
    var data = JSON.parse(res.getContentText());

Body:
In order to use the method of spreadsheets.developerMetadata.search of Sheets API, please modify the endpoint as follows.

From:

var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + fileId + '?developerMetadata:search';

To:

var url = 'https://sheets.googleapis.com/v4/spreadsheets/' + fileId + '/developerMetadata:search';

? of '?developerMetadata:search' is /.

Reference:

spreadsheets.developerMetadata.search


来源: stackexchange

问:
How to bind css class in vue js template within a v-for loop?
How do I name my td class the name of the step in this example?

```<code><td v-for="steps in item.steps" v:bind:class="item.steps.name">
 {{ item.steps.name }}
</td>
</code>```

In this example, my class gets literally named items.steps.name rather than the return value.  Everything else works.

答: Use v-bind:class not v:bind:class

ContentLicense: CC BY-SA 4.0

Body:
How do I name my td class the name of the step in this example?

 {{ item.steps.name }}

In this example, my class gets literally named items.steps.name rather than the return value.  Everything else works.

Body: Use v-bind:class not v:bind:class


问:
Spring HATEOAS / MockMvc / JsonPath best practices
I'm writing unit tests for Spring HATEOAS backend using MockMvc and JsonPath.
To test the links contained in a response I'm doing something like:

```<code>@Test
public void testListEmpty() throws Exception {
    mockMvc.perform(get("/rest/customers"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.links", hasSize(1))) // make sure links only contains self link
            .andExpect(jsonPath("$.links[?(@.rel=='self')]", hasSize(1))) //  make sure the self link exists 1 time
            .andExpect(jsonPath("$.links[?(@.rel=='self')].href", contains("http://localhost/rest/customers{?page,size,sort}"))) // test self link is correct
            .andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", is("http://localhost/rest/customers{?page,size,sort}"))) // alternative to test self link is correct
            .andExpect(jsonPath("$.content", hasSize(0))); // make sure no content elements exists
}
</code>```

However I wonder if there are some best practices I should use to make it easier for myself like:

Testing link contains http://localhost does not feel right. Can I use some Spring MovkMvc helper to determine the host?

With JsonPath it's difficult to test if an array contains an element where 2 attributes have certain value.
Like that the array should contain a self link with a certain value.
Is there a better way to test that then above
This will also come into play when testing validation errors for fields with error messages.

I've see technique like below in some blog posts:

```<code>.andExpect(jsonPath("$.fieldErrors[*].path", containsInAnyOrder("title", "description")))
.andExpect(jsonPath("$.fieldErrors[*].message", containsInAnyOrder(
    "The maximum length of the description is 500 characters.",
    "The maximum length of the title is 100 characters.")));
</code>```

But this does not guarantee at all that title has the specific error message.
It could also be that the title has incorrectly the "The maximum length of the description is 500 characters." but the test will succeed.

答:
One approach that addresses the http://localhost concern without sacrificing the need to test two attribute constraints on an array element is to use the org.hamcrest.CoreMatchers.hasItem(org.hamcrest.Matcher nestedMatcher) matcher. The test you showed above now becomes:

```<code>.andExpect(jsonPath("$.links[?(@.rel=='self')].href", hasItem(endsWith("/rest/customers{?page,size,sort}"))))
.andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", hasItem(endsWith("/rest/customers{?page,size,sort}"))))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing unit tests for Spring HATEOAS backend using MockMvc and JsonPath.
To test the links contained in a response I'm doing something like:

@Test
public void testListEmpty() throws Exception {
    mockMvc.perform(get("/rest/customers"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.links", hasSize(1))) // make sure links only contains self link
            .andExpect(jsonPath("$.links[?(@.rel=='self')]", hasSize(1))) //  make sure the self link exists 1 time
            .andExpect(jsonPath("$.links[?(@.rel=='self')].href", contains("http://localhost/rest/customers{?page,size,sort}"))) // test self link is correct
            .andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", is("http://localhost/rest/customers{?page,size,sort}"))) // alternative to test self link is correct
            .andExpect(jsonPath("$.content", hasSize(0))); // make sure no content elements exists
}

However I wonder if there are some best practices I should use to make it easier for myself like:

Testing link contains http://localhost does not feel right. Can I use some Spring MovkMvc helper to determine the host?

With JsonPath it's difficult to test if an array contains an element where 2 attributes have certain value.
Like that the array should contain a self link with a certain value.
Is there a better way to test that then above
This will also come into play when testing validation errors for fields with error messages.

I've see technique like below in some blog posts:

.andExpect(jsonPath("$.fieldErrors[*].path", containsInAnyOrder("title", "description")))
.andExpect(jsonPath("$.fieldErrors[*].message", containsInAnyOrder(
    "The maximum length of the description is 500 characters.",
    "The maximum length of the title is 100 characters.")));

But this does not guarantee at all that title has the specific error message.
It could also be that the title has incorrectly the "The maximum length of the description is 500 characters." but the test will succeed.

Body:
One approach that addresses the http://localhost concern without sacrificing the need to test two attribute constraints on an array element is to use the org.hamcrest.CoreMatchers.hasItem(org.hamcrest.Matcher nestedMatcher) matcher. The test you showed above now becomes:

.andExpect(jsonPath("$.links[?(@.rel=='self')].href", hasItem(endsWith("/rest/customers{?page,size,sort}"))))
.andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", hasItem(endsWith("/rest/customers{?page,size,sort}"))))


问:
I am trying to get a text box that assigns input data to a var and then runs the function to convert it to a YouTube embed url and displays that
Im setting up a website that will display a youtube video with modal-bootstrap but my modal needs embed youtube and i have a separate page that has a function that will convert it and display it but i have to put the watch link in the code and want that to pull from the text box on the page and not have to change the code every time.

I have tried multiple different functions to communicate with each other and also tried to change my modal to pull from watch url but youtube denies the request. I have been everywhere from stackoverflow, w3, jsfiddle, codepen, and googled the crap out of it but no luck.

Im working with this fiddle as a base before i put it on the page:

http://jsfiddle.net/hangman5950/51gz6syu

I need the variable "myID" to to pull from what's in the text box then run that in the function and i feel like it's super simple but I haven't messed with any of this in years so i don't know anything. jajajaja

my text box and display of video and embed id:

```<code><input type="text" id="wat" value="">

<button onclick="myFunction()">Convert</button>

<p id="emb"></p>

<script>
function myFunction() {
 var x = document.getElementById("wat").value;
  document.getElementById("emb").innerHTML = x;
}
 </script>
</code>```

YouTube ID:

Embed code:

my css:

```<code> #myId {
    color: orange;
 }
</code>```

my js:

```<code>function getId(url) {
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)
([^#\&\?]*).*/;
     var match = url.match(regExp);

    if (match && match[2].length == 11) {
         return match[2];
     } else {
        return 'error';
    }
 }

 var myId = getId('wat');

 $('#myId').html(myId);

$('#myCode').html('<iframe width="560" height="315"
src="//www.youtube.com/embed/' + myId + '" frameborder="0"
  allowfullscreen></iframe>');
</code>```

I am expecting the box to be assigned to a "emb" and then display the video and the results but instead i get error after error

答:
I made this work, hope this is what you need:

```<code>function getId(){
    var id = document.getElementById("wat").value;
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = id.match(regExp);
        if (match && match[2].length == 11) {
           var myId = match[2];
            $('#emb').html('<iframe width="560" height="315" src="https://www.youtube.com/embed/' + myId + '" frameborder="0" allowfullscreen></iframe>');
         }else{
           return 'Error';
        }
}
</code>```

And the HTML

```<code><input type="text" id="wat" value="">

<button id="convert" onclick="getId()">Convert</button>

<p id="emb"></p>
</code>```

Body:
Im setting up a website that will display a youtube video with modal-bootstrap but my modal needs embed youtube and i have a separate page that has a function that will convert it and display it but i have to put the watch link in the code and want that to pull from the text box on the page and not have to change the code every time.

I have tried multiple different functions to communicate with each other and also tried to change my modal to pull from watch url but youtube denies the request. I have been everywhere from stackoverflow, w3, jsfiddle, codepen, and googled the crap out of it but no luck.

Im working with this fiddle as a base before i put it on the page:

http://jsfiddle.net/hangman5950/51gz6syu

I need the variable "myID" to to pull from what's in the text box then run that in the function and i feel like it's super simple but I haven't messed with any of this in years so i don't know anything. jajajaja

my text box and display of video and embed id:

<input type="text" id="wat" value="">

<button onclick="myFunction()">Convert</button>

YouTube ID:

Embed code:

my css:

 #myId {
    color: orange;
 }

my js:

function getId(url) {
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)
([^#\&\?]*).*/;
     var match = url.match(regExp);

    if (match && match[2].length == 11) {
         return match[2];
     } else {
        return 'error';
    }
 }

 var myId = getId('wat');

 $('#myId').html(myId);

$('#myCode').html('');

I am expecting the box to be assigned to a "emb" and then display the video and the results but instead i get error after error

Body:
I made this work, hope this is what you need:

function getId(){
    var id = document.getElementById("wat").value;
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = id.match(regExp);
        if (match && match[2].length == 11) {
           var myId = match[2];
            $('#emb').html('<iframe width="560" height="315" src="https://www.youtube.com/embed/' + myId + '" frameborder="0" allowfullscreen></iframe>');
         }else{
           return 'Error';
        }
}

And the HTML

<input type="text" id="wat" value="">

<button id="convert" onclick="getId()">Convert</button>

<p id="emb"></p>


问:
Enumerating all walks in a graph
Given a term representation of an edge of a graph, i.e.:

```<code>edge(a, b).
edge(b, c).
</code>```

I would like to construct a predicate path/1 which succeeds iff its sole argument is a valid path in this graph (that is, for every two adjacent terms X, Y, edge(X, Y) holds). Given a variable, it should enumerate all walks (which could have repeated nodes). My first try:

```<code>path([X, Y]) :- edge(X, Y).
path([X, Y, Z | T]) :-
  path([Y, Z | T]),
  edge(X, Y).
</code>```

It works as intended except for the case where it is supplied an acyclic graph - path finds all solutions and then halts, unable to construct any other path. On the other hand, swapping first and second term will result in many walks being skipped, due to the DFS nature of Prolog resolution.

My second attempt:

```<code>path(P) :- length(P, L), L >= 2, (path(P, L) *-> true ; (!, fail)).

path([X, Y], 2) :- edge(X, Y).
path([X, Y, Z | T], L) :-
  L >= 3,
  L1 is L - 1,
  edge(X, Y),
  path([Y, Z | T], L1).
</code>```

It works as intended, but using a soft cut feels a bit forced. I was wondering if there was an easier way to accomplish this, perhaps a simpler simulation of a soft cut is possible in this particular scenario?

答:
Given your graph definition:

```<code>edge(a, b).
edge(b, c).
</code>```

Something like ought to do you:

```<code>path(P) :-
  node(X),
  walk(X,_,P)
  .

walk(A,B,P) :-
  walk(A,B,[],V),
  reverse(V,R),
  P = [A|R]
  .

walk( A, B, T, V ) :-
  edge(A,X),
  not( member(X,T) ),
  (
    ( B = X , V = [B|T] )
  ;
    walk( X, B, [A|T], V )
  )
  .

%
% enumerate the distinct nodes in edge/2 via backtracking
%
node(N) :-
  setof( X , edge(X,_);edge(_,X) , Ns ),
  node( Ns , N )
  .

node( [N|_] , N ).
node( [_|Ns] , N ) :- ( Ns , N ).
</code>```

Title: Enumerating all walks in a graph

Body:
Given a term representation of an edge of a graph, i.e.:

edge(a, b).
edge(b, c).

I would like to construct a predicate path/1 which succeeds iff its sole argument is a valid path in this graph (that is, for every two adjacent terms X, Y, edge(X, Y) holds). Given a variable, it should enumerate all walks (which could have repeated nodes). My first try:

path([X, Y]) :- edge(X, Y).
path([X, Y, Z | T]) :-
  path([Y, Z | T]),
  edge(X, Y).

It works as intended except for the case where it is supplied an acyclic graph - path finds all solutions and then halts, unable to construct any other path. On the other hand, swapping first and second term will result in many walks being skipped, due to the DFS nature of Prolog resolution.

My second attempt:

path(P) :- length(P, L), L >= 2, (path(P, L) *-> true ; (!, fail)).

path([X, Y], 2) :- edge(X, Y).
path([X, Y, Z | T], L) :-
  L >= 3,
  L1 is L - 1,
  edge(X, Y),
  path([Y, Z | T], L1).

It works as intended, but using a soft cut feels a bit forced. I was wondering if there was an easier way to accomplish this, perhaps a simpler simulation of a soft cut is possible in this particular scenario?

Body:
Given your graph definition:

edge(a, b).
edge(b, c).

Something like ought to do you:

path(P) :-
  node(X),
  walk(X,_,P)
  .

walk(A,B,P) :-
  walk(A,B,[],V),
  reverse(V,R),
  P = [A|R]
  .

walk( A, B, T, V ) :-
  edge(A,X),
  not( member(X,T) ),
  (
    ( B = X , V = [B|T] )
  ;
    walk( X, B, [A|T], V )
  )
  .

%
% enumerate the distinct nodes in edge/2 via backtracking
%
node(N) :-
  setof( X , edge(X,_);edge(_,X) , Ns ),
  node( Ns , N )
  .

node( [N|_] , N ).
node( [_|Ns] , N ) :- ( Ns , N ).


问:
Is there a way to reference data contained in fields on related record using formula field?
I want to display the taxcode custom field on invoice records

According to Netsuite Help, the format for the formula would be like that:
{taxcode.customfieldid}, knowing that (taxcode is the field id for the taxcode field on the lines of invoice record. customfieldid is the field id for the custom field on the TaxCode record)

PS: customfieldid is a free-text

I have tried possibilities like:
{invoice.item.taxcode.customfieldid}
{item.taxcode.customfieldid}

But I still get this error "ERROR: Field 'taxcode.customfieldid' Not Found"

how can I fix this? Can anyone provide some guidance on this issue?

答:
Generally Netsuite will only look one level away from the record you are on.

In your case you should create a new transaction line field (say custcol_tax_extra) and source that from the taxcode so when a tax code is selected that value is pulled up onto the line.

Then your xml:

```<code><#list record.item as item>${item.custcol_tax_extra}...
</code>```

Body:
Generally Netsuite will only look one level away from the record you are on.

In your case you should create a new transaction line field (say custcol_tax_extra) and source that from the taxcode so when a tax code is selected that value is pulled up onto the line.

Then your xml:

<#list record.item as item>${item.custcol_tax_extra}...


问:
Detect if the internet connection is offline?
How can I detect if the internet connection is offline in JavaScript?</p>

答:
I had to make a web app (ajax based) for a customer who works a lot with schools, these schools have often a bad internet connection I use this simple function to detect if there is a connection, works very well!

I use CodeIgniter and Jquery:

```<code>function checkOnline() {
    setTimeout("doOnlineCheck()", 20000);
}

function doOnlineCheck() {
    //if the server can be reached it returns 1, other wise it times out
    var submitURL = $("#base_path").val() + "index.php/menu/online";

    $.ajax({
        url : submitURL,
        type : "post",
        dataType : "msg",
        timeout : 5000,
        success : function(msg) {
            if(msg==1) {
                $("#online").addClass("online");
                $("#online").removeClass("offline");
            } else {
                $("#online").addClass("offline");
                $("#online").removeClass("online");
            }
            checkOnline();
        },
        error : function() {
            $("#online").addClass("offline");
            $("#online").removeClass("online");
            checkOnline();
        }
    });
}
</code>```

OwnerDisplayName: Daniel Silveira

LastEditorDisplayName: keparo

Body:
I had to make a web app (ajax based) for a customer who works a lot with schools, these schools have often a bad internet connection I use this simple function to detect if there is a connection, works very well!

I use CodeIgniter and Jquery:

function checkOnline() {
    setTimeout("doOnlineCheck()", 20000);
}

function doOnlineCheck() {
    //if the server can be reached it returns 1, other wise it times out
    var submitURL = $("#base_path").val() + "index.php/menu/online";

    $.ajax({
        url : submitURL,
        type : "post",
        dataType : "msg",
        timeout : 5000,
        success : function(msg) {
            if(msg==1) {
                $("#online").addClass("online");
                $("#online").removeClass("offline");
            } else {
                $("#online").addClass("offline");
                $("#online").removeClass("online");
            }
            checkOnline();
        },
        error : function() {
            $("#online").addClass("offline");
            $("#online").removeClass("online");
            checkOnline();
        }
    });
}


问:
Matplotlib is not rendering gradient under the curve correctly when directly saving
I'm using some sample code I got from:
https://stackoverflow.com/a/29331211/9469766

I'm attempting to save as pdf but whenever I do the gradient colors are formatted incorrectly. But if I simply show instead of saving or save the file as .png instead, the gradients appear correctly. Which leads me to believe that its the .pdf format that's the issue. Are there specific parameters that I need to set when saving as pdf?

Expected Image Output:

Actual Image Output

My code:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Polygon
np.random.seed(1977)
import os

def main():
    home_dir = os.path.expanduser('~/Desktop/test2.pdf')
    x, y = generate_data(100)
    for _ in range(5):
        gradient_fill(*generate_data(100))
    # plt.show()
    plt.savefig(home_dir, rasterized = True, dpi=300)
    plt.close()

def generate_data(num):
    x = np.linspace(0, 100, num)
    y = np.random.normal(0, 1, num).cumsum()
    return x, y

def gradient_fill(x, y, fill_color=None, ax=None, **kwargs):
    """
    """
    if ax is None:
        ax = plt.gca()

    line, = ax.plot(x, y, **kwargs)
    if fill_color is None:
        fill_color = line.get_color()

    zorder = line.get_zorder()
    alpha = line.get_alpha()
    alpha = 1.0 if alpha is None else alpha

    z = np.empty((100, 1, 4), dtype=float)
    rgb = mcolors.colorConverter.to_rgb(fill_color)
    z[:,:,:3] = rgb
    z[:,:,-1] = np.linspace(0, alpha, 100)[:,None]

    xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
    im = ax.imshow(z, aspect='auto', extent=[xmin, xmax, ymin, ymax],
                   origin='lower', zorder=zorder)

    xy = np.column_stack([x, y])
    xy = np.vstack([[xmin, ymin], xy, [xmax, ymin], [xmin, ymin]])
    clip_path = Polygon(xy, facecolor='none', edgecolor='none', closed=True)
    ax.add_patch(clip_path)
    im.set_clip_path(clip_path)

    ax.autoscale(True)
    return line, im

main()
</code>```

答:
The problem is the same as in https://github.com/matplotlib/matplotlib/issues/7151.

The solution is to use the "image.composite_image" rc parameter and set it to False.

```<code>plt.rcParams["image.composite_image"] =False
</code>```

Body:
I'm using some sample code I got from:
https://stackoverflow.com/a/29331211/9469766

I'm attempting to save as pdf but whenever I do the gradient colors are formatted incorrectly. But if I simply show instead of saving or save the file as .png instead, the gradients appear correctly. Which leads me to believe that its the .pdf format that's the issue. Are there specific parameters that I need to set when saving as pdf?

Expected Image Output:

Actual Image Output

My code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Polygon
np.random.seed(1977)
import os

def main():
    home_dir = os.path.expanduser('~/Desktop/test2.pdf')
    x, y = generate_data(100)
    for _ in range(5):
        gradient_fill(*generate_data(100))
    # plt.show()
    plt.savefig(home_dir, rasterized = True, dpi=300)
    plt.close()

def generate_data(num):
    x = np.linspace(0, 100, num)
    y = np.random.normal(0, 1, num).cumsum()
    return x, y

def gradient_fill(x, y, fill_color=None, ax=None, **kwargs):
    """
    """
    if ax is None:
        ax = plt.gca()

    line, = ax.plot(x, y, **kwargs)
    if fill_color is None:
        fill_color = line.get_color()

    zorder = line.get_zorder()
    alpha = line.get_alpha()
    alpha = 1.0 if alpha is None else alpha

    z = np.empty((100, 1, 4), dtype=float)
    rgb = mcolors.colorConverter.to_rgb(fill_color)
    z[:,:,:3] = rgb
    z[:,:,-1] = np.linspace(0, alpha, 100)[:,None]

    xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
    im = ax.imshow(z, aspect='auto', extent=[xmin, xmax, ymin, ymax],
                   origin='lower', zorder=zorder)

    xy = np.column_stack([x, y])
    xy = np.vstack([[xmin, ymin], xy, [xmax, ymin], [xmin, ymin]])
    clip_path = Polygon(xy, facecolor='none', edgecolor='none', closed=True)
    ax.add_patch(clip_path)
    im.set_clip_path(clip_path)

    ax.autoscale(True)
    return line, im

main()

Body:
The problem is the same as in https://github.com/matplotlib/matplotlib/issues/7151.

The solution is to use the "image.composite_image" rc parameter and set it to False.

plt.rcParams["image.composite_image"] =False


问:
New BrowserWindow loadFile not defined when webpacked
I'm trying to use webpack 4 for my electron app.

```<code>{
  "devDependencies": {
    "clean-webpack-plugin": "^0.1.19",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.18.0",
    "webpack-cli": "^3.1.0"
  },
  "dependencies": {
    "electron": "^2.0.9",
    "lodash": "^4.17.10"
  }
}
</code>```

My webpack.config.js is (notice target is electron-main):

```<code>const path = require('path');

module.exports = {
    mode: 'development',
    entry: {
        main: './main/index.js'
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    target: 'electron-main'
}
</code>```

I did:

npm init -y

Added to package.json "main": "dist/main.bundle.js".

Created ./main/index.js with contents from electron quick start - https://electronjs.org/docs/tutorial/first-app - (just changed require to import and path to app/index.html):

```<code>import { app, BrowserWindow } from 'electron'

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;

function createWindow() {
    // Create the browser window.
    win = new BrowserWindow({ width: 800, height: 600 });

    // and load the index.html of the app.
    win.loadFile('app/index.html');

    // Open the DevTools.
    win.webContents.openDevTools();

    // Emitted when the window is closed.
    win.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        win = null
    });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
        createWindow();
    }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
</code>```

I created dist/app/index.html with content:

    Hello World!

Hello World!

    We are using node document.write(process.versions.node),
    Chrome document.write(process.versions.chrome),
    and Electron document.write(process.versions.electron).

I run npx webpack and its succesful.

However when I do electron . I get win.loadFile is undefined. Here is screenshot:

https://i.imgur.com/mSJhK4y.png

答:
Maybe this setup with Electron, React, Sass and Webpack 4 will give you some ideas... https://github.com/wende60/Electron-Webpack4-React-Sass

regards, jo

Body:
I'm trying to use webpack 4 for my electron app.

{
  "devDependencies": {
    "clean-webpack-plugin": "^0.1.19",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.18.0",
    "webpack-cli": "^3.1.0"
  },
  "dependencies": {
    "electron": "^2.0.9",
    "lodash": "^4.17.10"
  }
}

My webpack.config.js is (notice target is electron-main):

const path = require('path');

module.exports = {
    mode: 'development',
    entry: {
        main: './main/index.js'
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    target: 'electron-main'
}

I did:

npm init -y

Added to package.json "main": "dist/main.bundle.js".

Created ./main/index.js with contents from electron quick start - https://electronjs.org/docs/tutorial/first-app - (just changed require to import and path to app/index.html):

import { app, BrowserWindow } from 'electron'

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;

function createWindow() {
    // Create the browser window.
    win = new BrowserWindow({ width: 800, height: 600 });

    // and load the index.html of the app.
    win.loadFile('app/index.html');

    // Open the DevTools.
    win.webContents.openDevTools();

    // Emitted when the window is closed.
    win.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        win = null
    });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
        createWindow();
    }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

I created dist/app/index.html with content:

    Hello World!

Hello World!

    We are using node document.write(process.versions.node),
    Chrome document.write(process.versions.chrome),
    and Electron document.write(process.versions.electron).

I run npx webpack and its succesful.

However when I do electron . I get win.loadFile is undefined. Here is screenshot:

https://i.imgur.com/mSJhK4y.png


问:
How to fix "m=video 9 UDP/TLS/RTP/SAVPF 0" issus in Android/Webrtc/PeerConnection/createOffer
How to get/enable the webrtc/video-coding-format? (Android)

I'm trying to create sdp-offer with media/vidio, but it seems no support fmt returned:

```<code>m=video 9 UDP/TLS/RTP/SAVPF 0
</code>```

It works with data-channel & audio stream in one app (2-peer-connections).

Part of Code:

```<code>// Media Constraint
MediaConstraints pcConstraints = new MediaConstraints();
pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("offerToReceiveAudio", "true"));
pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("offerToReceiveVideo", "true"));

MediaStream mediaStream = factory.createLocalMediaStream("MediaStream-"+name);
// Audio
AudioSource audioSource = factory.createAudioSource(new MediaConstraints());
mediaStream.addTrack(factory.createAudioTrack("Audio-"+name, audioSource));
// Video
videoTrackFromCamera = createVideoTrackFromCamera("Video-"+name);
if(videoTrackFromCamera!=null){
    surfaceViewRenderer.init(rootEglBase.getEglBaseContext(), null);
    surfaceViewRenderer.setMirror(true);
    surfaceViewRenderer.setEnableHardwareScaler(true);
    surfaceViewRenderer.setEnabled(true);
    videoTrackFromCamera.addSink(surfaceViewRenderer);
    mediaStream.addTrack(videoTrackFromCamera);
}

pc.addStream(mediaStream);
pc.createAnswer(sdpObserver, pcConstraints);
</code>```

onCreateSuccess(SessionDescription), Type=Offer, Description:

```<code>v=0
o=- 1829788378060179036 2 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE audio video data
a=msid-semantic: WMS MediaStream-First
m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 102 0 8 106 105 13 110 112 113 126
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:Muza
a=ice-pwd:npxXusvEWRQtpS/hjmAoPGn+
a=ice-options:trickle renomination
a=fingerprint:sha-256 79:5F:F6:2A:42:53:41:38:C4:EC:15:0D:4E:D1:6C:3A:66:39:57:2B:78:BE:5B:2D:70:94:96:AA:98:86:D4:B1
a=setup:actpass
a=mid:audio
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
a=extmap:2 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=sendrecv
a=rtcp-mux
a=rtpmap:111 opus/48000/2
a=rtcp-fb:111 transport-cc
a=fmtp:111 minptime=10;useinbandfec=1
a=rtpmap:103 ISAC/16000
a=rtpmap:104 ISAC/32000
a=rtpmap:9 G722/8000
a=rtpmap:102 ILBC/8000
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:106 CN/32000
a=rtpmap:105 CN/16000
a=rtpmap:13 CN/8000
a=rtpmap:110 telephone-event/48000
a=rtpmap:112 telephone-event/32000
a=rtpmap:113 telephone-event/16000
a=rtpmap:126 telephone-event/8000
a=ssrc:3451329273 cname:Jjbwj2+OSGEvw+Xc
a=ssrc:3451329273 msid:MediaStream-First Audio-First
a=ssrc:3451329273 mslabel:MediaStream-First
a=ssrc:3451329273 label:Audio-First
m=video 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:Muza
a=ice-pwd:npxXusvEWRQtpS/hjmAoPGn+
a=ice-options:trickle renomination
a=fingerprint:sha-256 79:5F:F6:2A:42:53:41:38:C4:EC:15:0D:4E:D1:6C:3A:66:39:57:2B:78:BE:5B:2D:70:94:96:AA:98:86:D4:B1
a=setup:actpass
a=mid:video
a=extmap:14 urn:ietf:params:rtp-hdrext:toffset
a=extmap:13 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=extmap:3 urn:3gpp:video-orientation
a=extmap:2 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay
a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type
a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing
a=extmap:8 http://tools.ietf.org/html/draft-ietf-avtext-framemarking-07
a=extmap:9 http://www.webrtc.org/experiments/rtp-hdrext/color-space
a=sendrecv
a=rtcp-mux
a=rtcp-rsize
a=ssrc:2429683820 cname:Jjbwj2+OSGEvw+Xc
a=ssrc:2429683820 msid:MediaStream-First Video-First
a=ssrc:2429683820 mslabel:MediaStream-First
a=ssrc:2429683820 label:Video-First
m=application 9 DTLS/SCTP 5000
c=IN IP4 0.0.0.0
a=ice-ufrag:Muza
a=ice-pwd:npxXusvEWRQtpS/hjmAoPGn+
a=ice-options:trickle renomination
a=fingerprint:sha-256 79:5F:F6:2A:42:53:41:38:C4:EC:15:0D:4E:D1:6C:3A:66:39:57:2B:78:BE:5B:2D:70:94:96:AA:98:86:D4:B1
a=setup:actpass
a=mid:data
a=sctpmap:5000 webrtc-datachannel 1024
</code>```

答:
It seems you have to set the VideoDecoderFactory and the VideoEncoderFactory when creating the PeerConnectionFactory:

```<code>WebRTCPeerConnectionDelegate(Context context) {
    this.context = context;
    PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(this.context)
            .setEnableInternalTracer(false)
            .createInitializationOptions());
    EglBase.Context eglContext = EglBase.create().getEglBaseContext();
    VideoDecoderFactory videoDecoderFactory = new DefaultVideoDecoderFactory(eglContext);
    VideoEncoderFactory videoEncoderFactory = new DefaultVideoEncoderFactory(eglContext, true, true);
    peerConnectionFactory = PeerConnectionFactory.builder()
            .setVideoDecoderFactory(videoDecoderFactory)
            .setVideoEncoderFactory(videoEncoderFactory)
            .createPeerConnectionFactory();
}
</code>```

Body:
How to get/enable the webrtc/video-coding-format? (Android)

I'm trying to create sdp-offer with media/vidio, but it seems no support fmt returned:

m=video 9 UDP/TLS/RTP/SAVPF 0

It works with data-channel & audio stream in one app (2-peer-connections).

Part of Code:

// Media Constraint
MediaConstraints pcConstraints = new MediaConstraints();
pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("offerToReceiveAudio", "true"));
pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("offerToReceiveVideo", "true"));

MediaStream mediaStream = factory.createLocalMediaStream("MediaStream-"+name);
// Audio
AudioSource audioSource = factory.createAudioSource(new MediaConstraints());
mediaStream.addTrack(factory.createAudioTrack("Audio-"+name, audioSource));
// Video
videoTrackFromCamera = createVideoTrackFromCamera("Video-"+name);
if(videoTrackFromCamera!=null){
    surfaceViewRenderer.init(rootEglBase.getEglBaseContext(), null);
    surfaceViewRenderer.setMirror(true);
    surfaceViewRenderer.setEnableHardwareScaler(true);
    surfaceViewRenderer.setEnabled(true);
    videoTrackFromCamera.addSink(surfaceViewRenderer);
    mediaStream.addTrack(videoTrackFromCamera);
}

pc.addStream(mediaStream);
pc.createAnswer(sdpObserver, pcConstraints);

onCreateSuccess(SessionDescription), Type=Offer, Description:

v=0
o=- 1829788378060179036 2 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE audio video data
a=msid-semantic: WMS MediaStream-First
m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 102 0 8 106 105 13 110 112 113 126
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:Muza
a=ice-pwd:npxXusvEWRQtpS/hjmAoPGn+
a=ice-options:trickle renomination
a=fingerprint:sha-256 79:5F:F6:2A:42:53:41:38:C4:EC:15:0D:4E:D1:6C:3A:66:39:57:2B:78:BE:5B:2D:70:94:96:AA:98:86:D4:B1
a=setup:actpass
a=mid:audio
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
a=extmap:2 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=sendrecv
a=rtcp-mux
a=rtpmap:111 opus/48000/2
a=rtcp-fb:111 transport-cc
a=fmtp:111 minptime=10;useinbandfec=1
a=rtpmap:103 ISAC/16000
a=rtpmap:104 ISAC/32000
a=rtpmap:9 G722/8000
a=rtpmap:102 ILBC/8000
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:106 CN/32000
a=rtpmap:105 CN/16000
a=rtpmap:13 CN/8000
a=rtpmap:110 telephone-event/48000
a=rtpmap:112 telephone-event/32000
a=rtpmap:113 telephone-event/16000
a=rtpmap:126 telephone-event/8000
a=ssrc:3451329273 cname:Jjbwj2+OSGEvw+Xc
a=ssrc:3451329273 msid:MediaStream-First Audio-First
a=ssrc:3451329273 mslabel:MediaStream-First
a=ssrc:3451329273 label:Audio-First
m=video 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:Muza
a=ice-pwd:npxXusvEWRQtpS/hjmAoPGn+
a=ice-options:trickle renomination
a=fingerprint:sha-256 79:5F:F6:2A:42:53:41:38:C4:EC:15:0D:4E:D1:6C:3A:66:39:57:2B:78:BE:5B:2D:70:94:96:AA:98:86:D4:B1
a=setup:actpass
a=mid:video
a=extmap:14 urn:ietf:params:rtp-hdrext:toffset
a=extmap:13 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=extmap:3 urn:3gpp:video-orientation
a=extmap:2 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay
a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type
a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing
a=extmap:8 http://tools.ietf.org/html/draft-ietf-avtext-framemarking-07
a=extmap:9 http://www.webrtc.org/experiments/rtp-hdrext/color-space
a=sendrecv
a=rtcp-mux
a=rtcp-rsize
a=ssrc:2429683820 cname:Jjbwj2+OSGEvw+Xc
a=ssrc:2429683820 msid:MediaStream-First Video-First
a=ssrc:2429683820 mslabel:MediaStream-First
a=ssrc:2429683820 label:Video-First
m=application 9 DTLS/SCTP 5000
c=IN IP4 0.0.0.0
a=ice-ufrag:Muza
a=ice-pwd:npxXusvEWRQtpS/hjmAoPGn+
a=ice-options:trickle renomination
a=fingerprint:sha-256 79:5F:F6:2A:42:53:41:38:C4:EC:15:0D:4E:D1:6C:3A:66:39:57:2B:78:BE:5B:2D:70:94:96:AA:98:86:D4:B1
a=setup:actpass
a=mid:data
a=sctpmap:5000 webrtc-datachannel 1024

Body:
It seems you have to set the VideoDecoderFactory and the VideoEncoderFactory when creating the PeerConnectionFactory:

WebRTCPeerConnectionDelegate(Context context) {
    this.context = context;
    PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions.builder(this.context)
            .setEnableInternalTracer(false)
            .createInitializationOptions());
    EglBase.Context eglContext = EglBase.create().getEglBaseContext();
    VideoDecoderFactory videoDecoderFactory = new DefaultVideoDecoderFactory(eglContext);
    VideoEncoderFactory videoEncoderFactory = new DefaultVideoEncoderFactory(eglContext, true, true);
    peerConnectionFactory = PeerConnectionFactory.builder()
            .setVideoDecoderFactory(videoDecoderFactory)
            .setVideoEncoderFactory(videoEncoderFactory)
            .createPeerConnectionFactory();
}


问:
Distributing tracing and elastic stack visualisation
```<code>2019-06-03 10:45:00.051  INFO [currency-exchange,411a0496b048bcf4,8d40fcfea92613ad,true] 45648 --- [x-Controller-10] logger                                   : inside exchange
</code>```

This is the log format in my console. I am using spring cloud stream to transport my log from application to logstash.This is the format for log parsing in logstash

```<code>grok {
              match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:severity}\s+\[%{DATA:service},%{DATA:trace},%{DATA:span},%{DATA:exportable}\]\s+%{DATA:pid}\s+---\s+\[%{DATA:thread}\]\s+%{DATA:class}\s+:\s+%{GREEDYDATA:rest}" }
       }
</code>```

This is my logstash.conf

input { kafka { topics => ['zipkin'] } } filter {
         # pattern matching logback pattern
         grok {
                match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:severity}\s+\[%{DATA:service},%{DATA:trace},%{DATA:span},%{DATA:exportable}\]\s+%{DATA:pid}\s+---\s+\[%{DATA:thread}\]\s+%{DATA:class}\s+:\s+%{GREEDYDATA:rest}"
  }
         } }  output { elasticsearch {hosts => ['localhost:9200'] index => 'logging'} stdout {}  }

and this is my output in log-stash console . which is parsing exception

{
         "message" => "[{\"traceId\":\"411a0496b048bcf4\",\"parentId\":\"8d40fcfea92613ad\",\"id\":\"f14c1c332d2ef077\",\"kind\":\"CLIENT\",\"name\":\"get\",\"timestamp\":1559538900053889,\"duration\":16783,\"localEndpoint\":{\"serviceName\":\"currency-exchange\",\"ipv4\":\"10.8.0.7\"},\"tags\":{\"http.method\":\"GET\",\"http.path\":\"/convert/1/to/4\"}},{\"traceId\":\"411a0496b048bcf4\",\"parentId\":\"411a0496b048bcf4\",\"id\":\"8d40fcfea92613ad\",\"name\":\"hystrix\",\"timestamp\":1559538900050039,\"duration\":34500,\"localEndpoint\":{\"serviceName\":\"currency-exchange\",\"ipv4\":\"10.8.0.7\"}},{\"traceId\":\"411a0496b048bcf4\",\"id\":\"411a0496b048bcf4\",\"kind\":\"SERVER\",\"name\":\"get
  /convert\",\"timestamp\":1559538900041446,\"duration\":44670,\"localEndpoint\":{\"serviceName\":\"currency-exchange\",\"ipv4\":\"10.8.0.7\"},\"remoteEndpoint\":{\"ipv6\":\"::1\",\"port\":62200},\"tags\":{\"http.method\":\"GET\",\"http.path\":\"/convert\",\"mvc.controller.class\":\"Controller\",\"mvc.controller.method\":\"convert\"}}]",
      "@timestamp" => 2019-06-03T05:15:00.296Z,
        "@version" => "1",
            "tags" => [
          [0] "_grokparsefailure"
      ] }

答:
When I use the Grok Debugger that is built into Kibana (under Dev Tools) I get the following result from your sample log and grok pattern:

```<code>{
  "severity": "DEBUG",
  "rest": "GET \"/convert/4/to/5\", parameters={}",
  "pid": "35973",
  "thread": "nio-9090-exec-1",
  "trace": "62132b44a444425e",
  "exportable": "true",
  "service": "currency-conversion",
  "class": "o.s.web.servlet.DispatcherServlet",
  "timestamp": "2019-05-31 05:31:42.667",
  "span": "62132b44a444425e"
}
</code>```

That looks correct to me. So what is the missing part?

Also the logging output you are showing contains "ipv4":"192.168.xx.xxx"},"remoteEndpoint": {"ipv6":"::1","port":55394},"tags": ..., which is not in the sample log. Where is that coming from?

Body:
2019-06-03 10:45:00.051  INFO [currency-exchange,411a0496b048bcf4,8d40fcfea92613ad,true] 45648 --- [x-Controller-10] logger                                   : inside exchange

This is the log format in my console. I am using spring cloud stream to transport my log from application to logstash.This is the format for log parsing in logstash

grok {
              match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:severity}\s+\[%{DATA:service},%{DATA:trace},%{DATA:span},%{DATA:exportable}\]\s+%{DATA:pid}\s+---\s+\[%{DATA:thread}\]\s+%{DATA:class}\s+:\s+%{GREEDYDATA:rest}" }
       }

This is my logstash.conf

input { kafka { topics => ['zipkin'] } } filter {
         # pattern matching logback pattern
         grok {
                match => { "message" => "%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:severity}\s+\[%{DATA:service},%{DATA:trace},%{DATA:span},%{DATA:exportable}\]\s+%{DATA:pid}\s+---\s+\[%{DATA:thread}\]\s+%{DATA:class}\s+:\s+%{GREEDYDATA:rest}"
  }
         } }  output { elasticsearch {hosts => ['localhost:9200'] index => 'logging'} stdout {}  }

and this is my output in log-stash console . which is parsing exception

{
         "message" => "[{\"traceId\":\"411a0496b048bcf4\",\"parentId\":\"8d40fcfea92613ad\",\"id\":\"f14c1c332d2ef077\",\"kind\":\"CLIENT\",\"name\":\"get\",\"timestamp\":1559538900053889,\"duration\":16783,\"localEndpoint\":{\"serviceName\":\"currency-exchange\",\"ipv4\":\"10.8.0.7\"},\"tags\":{\"http.method\":\"GET\",\"http.path\":\"/convert/1/to/4\"}},{\"traceId\":\"411a0496b048bcf4\",\"parentId\":\"411a0496b048bcf4\",\"id\":\"8d40fcfea92613ad\",\"name\":\"hystrix\",\"timestamp\":1559538900050039,\"duration\":34500,\"localEndpoint\":{\"serviceName\":\"currency-exchange\",\"ipv4\":\"10.8.0.7\"}},{\"traceId\":\"411a0496b048bcf4\",\"id\":\"411a0496b048bcf4\",\"kind\":\"SERVER\",\"name\":\"get
  /convert\",\"timestamp\":1559538900041446,\"duration\":44670,\"localEndpoint\":{\"serviceName\":\"currency-exchange\",\"ipv4\":\"10.8.0.7\"},\"remoteEndpoint\":{\"ipv6\":\"::1\",\"port\":62200},\"tags\":{\"http.method\":\"GET\",\"http.path\":\"/convert\",\"mvc.controller.class\":\"Controller\",\"mvc.controller.method\":\"convert\"}}]",
      "@timestamp" => 2019-06-03T05:15:00.296Z,
        "@version" => "1",
            "tags" => [
          [0] "_grokparsefailure"
      ] }

Body:
When I use the Grok Debugger that is built into Kibana (under Dev Tools) I get the following result from your sample log and grok pattern:

{
  "severity": "DEBUG",
  "rest": "GET \"/convert/4/to/5\", parameters={}",
  "pid": "35973",
  "thread": "nio-9090-exec-1",
  "trace": "62132b44a444425e",
  "exportable": "true",
  "service": "currency-conversion",
  "class": "o.s.web.servlet.DispatcherServlet",
  "timestamp": "2019-05-31 05:31:42.667",
  "span": "62132b44a444425e"
}

That looks correct to me. So what is the missing part?

Also the logging output you are showing contains "ipv4":"192.168.xx.xxx"},"remoteEndpoint": {"ipv6":"::1","port":55394},"tags": ..., which is not in the sample log. Where is that coming from?


问:
How to extract specific String from pandas dataframe rows?
This my dataframe df:

```<code>Pull Up Attribute   protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player
Extract Method  private getBestMove(moves ArrayList<Move>) : Move extracted from public nextStep() : void in class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm
Extract Method  private getNLongMoves(n int) : ArrayList<Move> extracted from private getAllPossibleMoves() : ArrayList<Move> in class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm"
Extract Method  public getPoints() : ArrayList<Point> extracted from public equals(b Object) : boolean in class blokusgame.mi.android.hazi.blokus.GameLogic.Block
Extract Method  public getMin() : Point extracted from public getDimensions() : Point in class blokusgame.mi.android.hazi.blokus.GameLogic.Block
Extract Method  public getMax() : Point extracted from public getDimensions() : Point in class blokusgame.mi.android.hazi.blokus.GameLogic.Block
Extract Method  public normalize() : Block extracted from public equals(b Object) : boolean in class blokusgame.mi.android.hazi.blokus.GameLogic.Block"
Extract Method  package setPlayer(player Player) : void extracted from protected onCreate(savedInstanceState Bundle) : void in class blokusgame.mi.android.hazi.blokus.MainActivity
Extract Method  public isPlaceable(block Block, pt Point) : boolean extracted from public isPlaceable(block Block, corners ArrayList<Point>, pt Point) : boolean in class blokusgame.mi.android.hazi.blokus.GameLogic.Map
Extract And Move Method public placeBlock(blockIndex int, coord Point) : boolean extracted from public placeBlock(blockIndex int, coord Point) : boolean in class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerHuman & moved to class blokusgame.mi.android.hazi.blokus.GameLogic.Player
Rename Class    blokusgame.mi.android.hazi.blokus.GameLogic.PlayerColors renamed to blokusgame.mi.android.hazi.blokus.GameLogic.PlayerConstants
Move Class  blokusgame.mi.android.hazi.blokus.View.BoardView moved to View.BoardView
Move Class  GameLogic.Block moved to blokusgame.mi.android.hazi.blokus.GameLogic.Block
Move Class  GameLogic.BlockFactory moved to blokusgame.mi.android.hazi.blokus.GameLogic.BlockFactory
Move Class  GameLogic.Map moved to blokusgame.mi.android.hazi.blokus.GameLogic.Map
Move Class  GameLogic.Player moved to blokusgame.mi.android.hazi.blokus.GameLogic.Player
Move Class  GameLogic.PlayerHuman moved to blokusgame.mi.android.hazi.blokus.GameLogic.PlayerHuman
Move Class  GameLogic.Point moved to blokusgame.mi.android.hazi.blokus.GameLogic.Point
Move Class  View.BoardView moved to blokusgame.mi.android.hazi.blokus.View.BoardView"
Rename Method   package Point(idx int) renamed to public getPoint(idx int) : Point in class GameLogic.Block
</code>```

I need to extract the nameOfClasses whitch start after the first String class in each row.

This is my code:

```<code>import pandas as pd
df = pd.read_csv('result_refactorings.csv', sep=';')
refactoring_details = df['RefactoringDetail']
print(refactoring_details)
a=refactoring_details.to_frame(name=refactoring_details)
a.RefactoringDetail.str.extract(r'class ([^ ]*)')
</code>```

The problem when i try t print the result I found that it did not return all the classes,there are rows that contain NaN .

this is the result:

```<code>0   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
1   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
2   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
3   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
4   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
5   blokusgame.mi.android.hazi.blokus.GameLogic.Block
6   blokusgame.mi.android.hazi.blokus.GameLogic.Block
7   blokusgame.mi.android.hazi.blokus.GameLogic.Block
8   blokusgame.mi.android.hazi.blokus.GameLogic.Block
9   blokusgame.mi.android.hazi.blokus.MainActivity
10  blokusgame.mi.android.hazi.blokus.GameLogic.Map
11  blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
12  NaN
13  NaN
14  NaN
15  NaN
16  NaN
17  NaN
18  NaN
19  NaN
20  NaN
21  GameLogic.Block
</code>```

Any help please!

答: Your regex r'class ([^ ]*)' should be r'[C|c]lass\s*([^ ]*)'.

Body:
This my dataframe df:

Pull Up Attribute   protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player
Extract Method  private getBestMove(moves ArrayList<Move>) : Move extracted from public nextStep() : void in class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm
Extract Method  private getNLongMoves(n int) : ArrayList<Move> extracted from private getAllPossibleMoves() : ArrayList<Move> in class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm"
Extract Method  public getPoints() : ArrayList<Point> extracted from public equals(b Object) : boolean in class blokusgame.mi.android.hazi.blokus.GameLogic.Block
Extract Method  public getMin() : Point extracted from public getDimensions() : Point in class blokusgame.mi.android.hazi.blokus.GameLogic.Block
Extract Method  public getMax() : Point extracted from public getDimensions() : Point in class blokusgame.mi.android.hazi.blokus.GameLogic.Block
Extract Method  public normalize() : Block extracted from public equals(b Object) : boolean in class blokusgame.mi.android.hazi.blokus.GameLogic.Block"
Extract Method  package setPlayer(player Player) : void extracted from protected onCreate(savedInstanceState Bundle) : void in class blokusgame.mi.android.hazi.blokus.MainActivity
Extract Method  public isPlaceable(block Block, pt Point) : boolean extracted from public isPlaceable(block Block, corners ArrayList<Point>, pt Point) : boolean in class blokusgame.mi.android.hazi.blokus.GameLogic.Map
Extract And Move Method public placeBlock(blockIndex int, coord Point) : boolean extracted from public placeBlock(blockIndex int, coord Point) : boolean in class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerHuman & moved to class blokusgame.mi.android.hazi.blokus.GameLogic.Player
Rename Class    blokusgame.mi.android.hazi.blokus.GameLogic.PlayerColors renamed to blokusgame.mi.android.hazi.blokus.GameLogic.PlayerConstants
Move Class  blokusgame.mi.android.hazi.blokus.View.BoardView moved to View.BoardView
Move Class  GameLogic.Block moved to blokusgame.mi.android.hazi.blokus.GameLogic.Block
Move Class  GameLogic.BlockFactory moved to blokusgame.mi.android.hazi.blokus.GameLogic.BlockFactory
Move Class  GameLogic.Map moved to blokusgame.mi.android.hazi.blokus.GameLogic.Map
Move Class  GameLogic.Player moved to blokusgame.mi.android.hazi.blokus.GameLogic.Player
Move Class  GameLogic.PlayerHuman moved to blokusgame.mi.android.hazi.blokus.GameLogic.PlayerHuman
Move Class  GameLogic.Point moved to blokusgame.mi.android.hazi.blokus.GameLogic.Point
Move Class  View.BoardView moved to blokusgame.mi.android.hazi.blokus.View.BoardView"
Rename Method   package Point(idx int) renamed to public getPoint(idx int) : Point in class GameLogic.Block

I need to extract the nameOfClasses whitch start after the first String class in each row.

This is my code:

import pandas as pd
df = pd.read_csv('result_refactorings.csv', sep=';')
refactoring_details = df['RefactoringDetail']
print(refactoring_details)
a=refactoring_details.to_frame(name=refactoring_details)
a.RefactoringDetail.str.extract(r'class ([^ ]*)')

The problem when i try t print the result I found that it did not return all the classes,there are rows that contain NaN .

this is the result:

0   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
1   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
2   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
3   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
4   blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
5   blokusgame.mi.android.hazi.blokus.GameLogic.Block
6   blokusgame.mi.android.hazi.blokus.GameLogic.Block
7   blokusgame.mi.android.hazi.blokus.GameLogic.Block
8   blokusgame.mi.android.hazi.blokus.GameLogic.Block
9   blokusgame.mi.android.hazi.blokus.MainActivity
10  blokusgame.mi.android.hazi.blokus.GameLogic.Map
11  blokusgame.mi.android.hazi.blokus.GameLogic.Pl...
12  NaN
13  NaN
14  NaN
15  NaN
16  NaN
17  NaN
18  NaN
19  NaN
20  NaN
21  GameLogic.Block

Any help please!


问:
How to update pub package webdev for flutter web
when I try to "serve" my flutter web app
I'm getting this error:

This version of webdev does not support the build_daemon protocol
  used by your version of build_runner. A newer version of webdev is
  available which supports your version of the build_daemon. Please
  update.

how do I update webdev ?
"pub global" seems to offer only "activate"/ "deactivate"
and "pub upgrade" is only looking into the pubspec.yaml file

any idea?

答:
I had to use the following command to update webdev

flutter pub global run webdev deactivate
```
<p>and then</p>
<pre class="lang-bash prettyprint-override"><code>flutter pub global run webdev activate
</code>```

Body:
I had to use the following command to update webdev

flutter pub global run webdev deactivate

and then

flutter pub global run webdev activate


问:
Is there a better way to do booleans?
```<code>if "a_string" in random_word or "b_string" in random_word:
    ...
</code>```

Is there a cleaner, less dense way to write this boolean?

答:
In case of if, you could use any to check for the occurrence of either of the two strings

```<code>if any(i in random_word for i in ["a_string", "b_string"]):
</code>```

Title: Is there a better way to do booleans?

Body:
if "a_string" in random_word or "b_string" in random_word:
    ...

Is there a cleaner, less dense way to write this boolean?

Body:
In case of if, you could use any to check for the occurrence of either of the two strings

if any(i in random_word for i in ["a_string", "b_string"]):


答:
You can use a regular expression.</p>

```<code>import re
if re.search(r'a_string|b_string', random_word):
    ...
</code>```

Title: Is there a better way to do booleans?

Body:
You can use a regular expression.

import re
if re.search(r'a_string|b_string', random_word):
    ...


问:
Are there built-in extension methods in the .NET framework that don't apply to LINQ?
For the purpose of a course I am developing, I am looking for some examples of where Microsoft has already implemented extension methods themselves. But since the students are not yet acquainted to LINQ, I would like to find some other example.

So, are there any methods defined in the .NET framework that are defined as an extension method, but do not refer to the LINQ framework or IEnumerable?

答: Because you are doing coursework, perhaps the ZipFileExtensions are a good API. People tend to be able to wrap their heads around .zip files, and these APIs are generally pretty easy to use. </p>


问:
appendChild() and createElement() Javascript question
When I use appendChild() and createElement() in my code, the subsequent styles for the defined CSS IDs are not applied. Can someone tell me why? Here's my code:

```<code>function searchDone(results) {
    var result = null;
    var parent = document.getElementById('postWrap');
    var child = null;
    parent.innerHTML = '';
    var insertHTML =" ";

    //Paginating Results Links
    resultNum = results.SearchResponse.Web.Total;
    resultNum = resultNum/10;
    child = document.createElement('div');
    child.id = "paging";
    if(results.SearchResponse.Web.Offset != 0){
        insertHTML ='<span><a class="jsonp b" href="#" rev="'+(results.SearchResponse.Web.Offset-10)+'"><</a></span>';
    }
    if(results.SearchResponse.Web.Offset == 0){
        insertHTML += '<span>1</span>';
    }else{
        insertHTML +='<span><a class="jsonp" href="#" rev="0">1</a></span>';
    }
    for(var i = 1; i <= resultNum; i++){
        if((results.SearchResponse.Web.Offset/10) == i){
            insertHTML += '<span>'+(i+1)+'</span>';
        }else{
            insertHTML += '<span><a class="jsonp b" href="#" rev="'+i*10+'">'+(i+1)+'</a></span>';
        }
    }
    if(results.SearchResponse.Web.Total - results.SearchResponse.Web.Offset > 10){
        insertHTML += '<span><a class="jsonp b" href="#" rev="'+(results.SearchResponse.Web.Offset+10)+'">></a></span>';
    }
    child.innerHTML = insertHTML;
    parent.appendChild(child);
</code>```

I then have some other code which processes my search query via API to Bing (only because Google now charges... )

Next, I use the same methods to insert another div:

```<code>//Insert Paginating results again
    child = null;
    child = document.createElement('div');
    child.innerHTML = insertHTML;
    child.id = "searchResultsPages";
    parent.appendChild(child);
</code>```

Now I'd like to apply some styles to these numbers. However, when I apply a style to searchResultsPage, like

```<code>#searchResultsPages{
 float: right;
}
</code>```

I don't get the style being passed on. The curious thing is that if I only insert one of these two elements, everything goes as planned and the style shows up fine. The problem is that I'd like pages displayed at the top and bottom of the search.

Any ideas why this is happening? I think it might have something to do with an element being used twice, but I don't know why this would effect anything if the objects are different.

Thanks.

答:
```<code>child.id = "searchResultsPages";

#searchResultsPage{
</code>```

See anything wrong there?  :)

Like an s

Body:
When I use appendChild() and createElement() in my code, the subsequent styles for the defined CSS IDs are not applied. Can someone tell me why? Here's my code:

function searchDone(results) {
    var result = null;
    var parent = document.getElementById('postWrap');
    var child = null;
    parent.innerHTML = '';
    var insertHTML =" ";

    //Paginating Results Links
    resultNum = results.SearchResponse.Web.Total;
    resultNum = resultNum/10;
    child = document.createElement('div');
    child.id = "paging";
    if(results.SearchResponse.Web.Offset != 0){
        insertHTML ='<';
    }
    if(results.SearchResponse.Web.Offset == 0){
        insertHTML += '1';
    }else{
        insertHTML +='1';
    }
    for(var i = 1; i <= resultNum; i++){
        if((results.SearchResponse.Web.Offset/10) == i){
            insertHTML += ''+(i+1)+'';
        }else{
            insertHTML += ''+(i+1)+'';
        }
    }
    if(results.SearchResponse.Web.Total - results.SearchResponse.Web.Offset > 10){
        insertHTML += '>';
    }
    child.innerHTML = insertHTML;
    parent.appendChild(child);

I then have some other code which processes my search query via API to Bing (only because Google now charges... )

Next, I use the same methods to insert another div:

//Insert Paginating results again
    child = null;
    child = document.createElement('div');
    child.innerHTML = insertHTML;
    child.id = "searchResultsPages";
    parent.appendChild(child);

Now I'd like to apply some styles to these numbers. However, when I apply a style to searchResultsPage, like

#searchResultsPages{
 float: right;
}

I don't get the style being passed on. The curious thing is that if I only insert one of these two elements, everything goes as planned and the style shows up fine. The problem is that I'd like pages displayed at the top and bottom of the search.

Any ideas why this is happening? I think it might have something to do with an element being used twice, but I don't know why this would effect anything if the objects are different.

Thanks.

Body:
child.id = "searchResultsPages";

#searchResultsPage{

See anything wrong there?  :)

Like an s


问:
How to resolve Google Service Account Team Drive creation error of insufficientFilePermissions?
I am attempting to create a Google Team Drive using my Service Account but am receiving a insufficientFilePermissions error.  Does anyone know how to create a Google Team Drive using a Service Account or can identify what I am doing wrong here?

For ease of use, I've created a github project which contains the files presented here.  https://gitlab.com/eghm-lab/stackoverflow-google-service-account-test-drive-creation

I've provided the error, Java code for SOTeamDriveCreate, and a pom.xml below.  After placing SOTeamDriveCreate.java into src/main/java.  One should copy their Service Account credential client_secrets.json file to  the same directory as the pom file.  Then execute:

```<code>mvn clean compile ; mvn exec:java -Dexec.mainClass=SOTeamDriveCreate
</code>```

The insufficientFilePermissions error:

```<code>java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
    "code" : 403,
    "errors" : [ {
        "domain" : "global",
        "message" : "The user does not have sufficient permissions for this file.",
        "reason" : "insufficientFilePermissions"
    } ],
    "message" : "The user does not have sufficient permissions for this file."
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at SOTeamDriveCreate.createTeamDrive(SOTeamDriveCreate.java:110)
    at SOTeamDriveCreate.main(SOTeamDriveCreate.java:103)
    ... 6 more
</code>```

SOTeamDriveCreate.java:

```<code>import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.TeamDrive;

public class SOTeamDriveCreate {

    /** Application name. */
    private static final String APPLICATION_NAME =
            "Drive API Java Quickstart";

    /** Directory to store user credentials for this application. */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(
            System.getProperty("user.home"), ".credentials/drive-java-quickstart");

    /** Global instance of the {@link FileDataStoreFactory}. */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY =
            JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport HTTP_TRANSPORT;

    private static Drive service = null;

    protected static String FILE_FIELDS = "id, name, createdTime, mimeType, trashed, permissions, parents, teamDrive";

    /**
     * Global instance of the scopes.
     *
     * If modifying these scopes, delete your previously saved credentials
     * at ~/.credentials/drive-java-quickstart
     */
    private static final List<String> SCOPES =
            Arrays.asList(DriveScopes.DRIVE);

    private String authFile;

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    public SOTeamDriveCreate(String authFile) {
        this.authFile = authFile;
    }

    /**
     * Creates an authorized Credential object.
     *
     * @return an authorized Credential object.
     * @throws IOException
     */
    public Credential authorize() throws IOException {
        GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream(authFile))
                .createScoped(Arrays.asList(DriveScopes.DRIVE));
        return credential;
    }

    /**
     * Build and return an authorized Drive client service.
     *
     * @return an authorized Drive client service
     * @throws IOException
     */
    public Drive getDriveService() throws IOException {
        if (service == null) {
            Credential credential = authorize();
            service = new Drive.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, credential)
                            .setApplicationName(APPLICATION_NAME)
                            .build();
        }
        return service;
    }

    public static void main(String[] args) throws Exception {
        SOTeamDriveCreate createTeamDrive = new SOTeamDriveCreate("client_secrets.json");
        createTeamDrive.createTeamDrive();
    }

    public void createTeamDrive() throws Exception {
        TeamDrive teamDriveMetadata = new TeamDrive();
        teamDriveMetadata.setName("Team Drive created with Service Account");
        String requestId = UUID.randomUUID().toString();
        TeamDrive teamDrive = getDriveService().teamdrives().create(requestId, teamDriveMetadata).setFields(FILE_FIELDS).execute();
    }

}
</code>```

pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>so-team-drive-create</artifactId>
    <packaging>war</packaging>
    <name>SOTeamDriveCreate</name>
    <description>Google Service Account Team Drive creation</description>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <prerequisites>
        <maven>3.2.1</maven>
    </prerequisites>
    <properties>
        <maven-war-plugin.version>2.4</maven-war-plugin.version>
        <java.version>1.8</java.version>

        <google.http-client.version>1.23.0</google.http-client.version>
        <google.oauth-client.version>1.23.0</google.oauth-client.version>
        <google.api-client.version>1.23.0</google.api-client.version>
        <google-api-services.version>v3-rev119-1.23.0</google-api-services.version>
        <google-api-services-storage.version>v1-rev132-1.23.0</google-api-services-storage.version>

    </properties>

    <dependencies>
        <!-- Google Drive API. -->
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>${google.api-client.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.oauth-client</groupId>
            <artifactId>google-oauth-client-jetty</artifactId>
            <version>${google.oauth-client.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-storage</artifactId>
            <version>${google-api-services-storage.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.http-client</groupId>
            <artifactId>google-http-client-jackson2</artifactId>
            <version>${google.http-client.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-drive</artifactId>
            <version>${google-api-services.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client-assembly</artifactId>
            <version>${google.api-client.version}</version>
            <type>pom</type>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>${maven-war-plugin.version}</version>
                <configuration>
                    <warName>${project.name}</warName>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>clean</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
                                <echo>Here are some common goals for this project:</echo>
                                <echo>$ mvn clean compile</echo>
                                <echo>$ mvn exec:java -Dexec.mainClass=SOTeamDriveCreate</echo>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <goals><goal>java</goal></goals>
                    </execution>
                </executions>
                <configuration>
                    <executable>java</executable>
                    <classpathScope>compile</classpathScope>
                    <mainClass>${exec.mainClass}</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
A teammate has solved our problem.

First, on the Enterprise Admin console we needed to setup our client has having domain wide access.

Then we used the createCredentialForServiceAccountImpersonateUser from https://googleapis.dev/java/google-api-client/latest/com/google/api/client/googleapis/auth/oauth2/GoogleCredential.html, which uses the P12File to create the GoogleCredential.  Initially we attempted to use the json file, which worked for everything, EXCEPT creating a new Team Drive, only the P12File version allows for us to create a new Team Drive.

Body:
I am attempting to create a Google Team Drive using my Service Account but am receiving a insufficientFilePermissions error.  Does anyone know how to create a Google Team Drive using a Service Account or can identify what I am doing wrong here?

For ease of use, I've created a github project which contains the files presented here.  https://gitlab.com/eghm-lab/stackoverflow-google-service-account-test-drive-creation

I've provided the error, Java code for SOTeamDriveCreate, and a pom.xml below.  After placing SOTeamDriveCreate.java into src/main/java.  One should copy their Service Account credential client_secrets.json file to  the same directory as the pom file.  Then execute:

mvn clean compile ; mvn exec:java -Dexec.mainClass=SOTeamDriveCreate

The insufficientFilePermissions error:

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
    "code" : 403,
    "errors" : [ {
        "domain" : "global",
        "message" : "The user does not have sufficient permissions for this file.",
        "reason" : "insufficientFilePermissions"
    } ],
    "message" : "The user does not have sufficient permissions for this file."
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at SOTeamDriveCreate.createTeamDrive(SOTeamDriveCreate.java:110)
    at SOTeamDriveCreate.main(SOTeamDriveCreate.java:103)
    ... 6 more

SOTeamDriveCreate.java:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.TeamDrive;

public class SOTeamDriveCreate {

    /** Application name. */
    private static final String APPLICATION_NAME =
            "Drive API Java Quickstart";

    /** Directory to store user credentials for this application. */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(
            System.getProperty("user.home"), ".credentials/drive-java-quickstart");

    /** Global instance of the {@link FileDataStoreFactory}. */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY =
            JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport HTTP_TRANSPORT;

    private static Drive service = null;

    protected static String FILE_FIELDS = "id, name, createdTime, mimeType, trashed, permissions, parents, teamDrive";

    /**
     * Global instance of the scopes.
     *
     * If modifying these scopes, delete your previously saved credentials
     * at ~/.credentials/drive-java-quickstart
     */
    private static final List<String> SCOPES =
            Arrays.asList(DriveScopes.DRIVE);

    private String authFile;

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    public SOTeamDriveCreate(String authFile) {
        this.authFile = authFile;
    }

    /**
     * Creates an authorized Credential object.
     *
     * @return an authorized Credential object.
     * @throws IOException
     */
    public Credential authorize() throws IOException {
        GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream(authFile))
                .createScoped(Arrays.asList(DriveScopes.DRIVE));
        return credential;
    }

    /**
     * Build and return an authorized Drive client service.
     *
     * @return an authorized Drive client service
     * @throws IOException
     */
    public Drive getDriveService() throws IOException {
        if (service == null) {
            Credential credential = authorize();
            service = new Drive.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, credential)
                            .setApplicationName(APPLICATION_NAME)
                            .build();
        }
        return service;
    }

    public static void main(String[] args) throws Exception {
        SOTeamDriveCreate createTeamDrive = new SOTeamDriveCreate("client_secrets.json");
        createTeamDrive.createTeamDrive();
    }

    public void createTeamDrive() throws Exception {
        TeamDrive teamDriveMetadata = new TeamDrive();
        teamDriveMetadata.setName("Team Drive created with Service Account");
        String requestId = UUID.randomUUID().toString();
        TeamDrive teamDrive = getDriveService().teamdrives().create(requestId, teamDriveMetadata).setFields(FILE_FIELDS).execute();
    }

}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>so-team-drive-create</artifactId>
    <packaging>war</packaging>
    <name>SOTeamDriveCreate</name>
    <description>Google Service Account Team Drive creation</description>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/>
    </parent>

    <prerequisites>
        <maven>3.2.1</maven>
    </prerequisites>
    <properties>
        <maven-war-plugin.version>2.4</maven-war-plugin.version>
        <java.version>1.8</java.version>

        <google.http-client.version>1.23.0</google.http-client.version>
        <google.oauth-client.version>1.23.0</google.oauth-client.version>
        <google.api-client.version>1.23.0</google.api-client.version>
        <google-api-services.version>v3-rev119-1.23.0</google-api-services.version>
        <google-api-services-storage.version>v1-rev132-1.23.0</google-api-services-storage.version>

    </properties>

    <dependencies>

        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>${google.api-client.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.oauth-client</groupId>
            <artifactId>google-oauth-client-jetty</artifactId>
            <version>${google.oauth-client.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-storage</artifactId>
            <version>${google-api-services-storage.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.http-client</groupId>
            <artifactId>google-http-client-jackson2</artifactId>
            <version>${google.http-client.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-drive</artifactId>
            <version>${google-api-services.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client-assembly</artifactId>
            <version>${google.api-client.version}</version>
            <type>pom</type>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>${maven-war-plugin.version}</version>
                <configuration>
                    <warName>${project.name}</warName>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>clean</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
                                <echo>Here are some common goals for this project:</echo>
                                <echo>$ mvn clean compile</echo>
                                <echo>$ mvn exec:java -Dexec.mainClass=SOTeamDriveCreate</echo>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <goals><goal>java</goal></goals>
                    </execution>
                </executions>
                <configuration>
                    <executable>java</executable>
                    <classpathScope>compile</classpathScope>
                    <mainClass>${exec.mainClass}</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


问:
SimplePostTool: WARNING: IOException while reading response: java.io.IOException: Server returned HTTP response code: 400
I'm trying to post some document(json format) into solr using the below commands in command prompt, but always I'm getting 400 Bad Request error.
Java_Version:1.8.0; Solr_Version:7.2

CMD:

```<code>C:\..\..\solr-7.2.1\example\exampledocs>java -Dtype=text/json -Durl=http://localhost:8983/solr/mycore/update -jar post.jar books.json
</code>```

Error:

```<code>SimplePostTool: WARNING: Solr returned an error #400 (Bad Request) for url: http://localhost:8983/solr/mycore/update
SimplePostTool: WARNING: Response: {
  "responseHeader":{
    "status":400,
    "QTime":1},
  "error":{
    "metadata":[
      "error-class","org.apache.solr.common.SolrException",
      "root-error-class","org.apache.solr.common.SolrException"],
    "msg":"This IndexSchema is not mutable.",
    "code":400}}
SimplePostTool: WARNING: IOException while reading response: java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8983/solr/mycore/update
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/mycore/update...
Time spent: 0:00:00.062
</code>```

I've added the request handler in solrconfig.xml

```<code><requestHandler name="/update" class="solr.UpdateRequestHandler" />
</code>```

and  <schemaFactory class="ClassicIndexSchemaFactory"/> -> for referring to schema.xml file

Schema.xml: (new fields added for my indexing)

```<code><field name="id" type="string" indexed="true" stored="true" required="true"  multiValued="false" />
<field name="_version_" type="plong" indexed="false" stored="false"/>
<field name="_root_" type="string" indexed="true" stored="false" docValues="false" />
<field name="_text_" type="text_general" indexed="true" stored="false" multiValued="true"/>

<!-- new fields -starts -->
<field name="cat" type="text_general" indexed="true" stored="true"/>
<field name="name" type="text_general" indexed="true" stored="true"/>
<field name="price" type="pdouble" indexed="true" stored="true"/>
<field name="inStock" type="boolean" indexed="true" stored="true"/>
<field name="author" type="text_general" indexed="true" stored="true"/>
<!-- new fields -ends -->
</code>```

My Unique key is 'ID'.

答:
use java -Dc=core_name -Dauto=yes -Dtype=application/json -jar post.jar *.json

i dont know why it worked.

Body:
I'm trying to post some document(json format) into solr using the below commands in command prompt, but always I'm getting 400 Bad Request error.
Java_Version:1.8.0; Solr_Version:7.2

CMD:

C:\..\..\solr-7.2.1\example\exampledocs>java -Dtype=text/json -Durl=http://localhost:8983/solr/mycore/update -jar post.jar books.json

Error:

SimplePostTool: WARNING: Solr returned an error #400 (Bad Request) for url: http://localhost:8983/solr/mycore/update
SimplePostTool: WARNING: Response: {
  "responseHeader":{
    "status":400,
    "QTime":1},
  "error":{
    "metadata":[
      "error-class","org.apache.solr.common.SolrException",
      "root-error-class","org.apache.solr.common.SolrException"],
    "msg":"This IndexSchema is not mutable.",
    "code":400}}
SimplePostTool: WARNING: IOException while reading response: java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8983/solr/mycore/update
1 files indexed.
COMMITting Solr index changes to http://localhost:8983/solr/mycore/update...
Time spent: 0:00:00.062

I've added the request handler in solrconfig.xml

<requestHandler name="/update" class="solr.UpdateRequestHandler" />

and  <schemaFactory class="ClassicIndexSchemaFactory"/> -> for referring to schema.xml file

Schema.xml: (new fields added for my indexing)

<field name="id" type="string" indexed="true" stored="true" required="true"  multiValued="false" />
<field name="_version_" type="plong" indexed="false" stored="false"/>
<field name="_root_" type="string" indexed="true" stored="false" docValues="false" />
<field name="_text_" type="text_general" indexed="true" stored="false" multiValued="true"/>

<field name="cat" type="text_general" indexed="true" stored="true"/>
<field name="name" type="text_general" indexed="true" stored="true"/>
<field name="price" type="pdouble" indexed="true" stored="true"/>
<field name="inStock" type="boolean" indexed="true" stored="true"/>
<field name="author" type="text_general" indexed="true" stored="true"/>

My Unique key is 'ID'.


问:
Which Lisp should I learn?

Which Lisp (dialect) should I learn, and why?

The fragmentation between CL and Scheme slows uptake (at least for me!).

So, give me the "true answer", please!

I have tried to read feature comparisons, and they seem to get bogged down in esoterica (that I don't fully understand) like whether the dialect is fully tail-recursive, and the like.  I'm hoping you all (collectively) can make the opaque differences clear.

Things I like

Good library support, good environments, and Unicode support.

Things I dislike

Flamewars. Features that are useful at the beginning, but interfere with long-term learning.

Updates

I've been mostly using MzScheme, which I'm enjoying just fine, once I got readline support going.  I don't run a GUI on Unix, so it seemed to be a fine environment option for me.

I'm also very happy that Clojure has an easy to install .deb package on debian, so it's much easier to play with.  This is a big win.  Despite the hostility of some rather easy-to-anger below, low barrier to entry is a win.  I like being spoonfed.

After reading a lot more of SICP, I do understand the issues around tail recursion much better.

答:
If you want avoid flamewars and you enjoy libraries go with Clojure.  It's small, it's fast, and the community is helpful and non-dogmatic.  It's Lisp minus the absurd cruft of the 1980s . It has a BDFL and if you have a good idea there's a damn good chance it will get implemented into the language.

I have toyed around with Common Lisp, it's a beautiful thing.  I've completed the first 3 chapters and the Metacircular Evaluator in SICP in DrScheme, and that is beautiful thing as well.  Of course, you will benefit greatly from learning these.

But, over time I have come to hold small languages dear to my heart.  I won't lie, I love Javascript and I love C (and goddammit if every language doesn't have a C core at it's heart) because they are small.

Clojure is small. It is elegant. It is a language for our times.

OwnerDisplayName: Gregg Lind

Title: Which Lisp should I learn?

LastEditorDisplayName: Gregg Lind

OwnerDisplayName: dnolen

ContentLicense: CC BY-SA 2.5


问:
Is it possible to include a C# variable in a string variable without using a concatenator?
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

```<code>DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);
</code>```

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

```<code>string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>
    <html>
    <head>
        <title>$title</title>
    </head>
    <body>
    <div>Hello StackO</div>
    <div>The date is $date</div>
    </body>
    </html>
    ";

}
</code>```

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

答:
No, But you can create an extension method on the string instance to make the typing shorter.</p>

```<code>string s = "The date is {0}".Format(d);
</code>```

Body:
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>

        <title>$title</title>

Hello StackO

The date is $date

    ";

}

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

Body:
No, But you can create an extension method on the string instance to make the typing shorter.

string s = "The date is {0}".Format(d);


问:
How to write sql query for this task
I have tables: user (one to many reviews/tours), tour (one to many reviews), review (many to one tour| many to one user), usertour (with columns user_id, tour_id). So. I want to get all tours for user with review for tour and if review for tour does not exist tour should present anyway. Help me pls to write sql query for this.

I wrote this but it returns wrong result:

```<code>select *
from tour tr
     join usertour ut on tr.id = ut.tour_id
     left join review r on tr.id = r.tour_id
where ut.user_id = 80
</code>```

答:
I did it myself.</p>

```<code>select * from tour tr join usertour ut on tr.id = ut.tour_id
left join review r on tr.id = r.tour_id
where ut.user_id = 100 and (r.user_id = 100 or r.user_id is null)
</code>```

Title: How to write sql query for this task

Body:
I have tables: user (one to many reviews/tours), tour (one to many reviews), review (many to one tour| many to one user), usertour (with columns user_id, tour_id). So. I want to get all tours for user with review for tour and if review for tour does not exist tour should present anyway. Help me pls to write sql query for this.

I wrote this but it returns wrong result:

select *
from tour tr
     join usertour ut on tr.id = ut.tour_id
     left join review r on tr.id = r.tour_id
where ut.user_id = 80

Body:
I did it myself.

select * from tour tr join usertour ut on tr.id = ut.tour_id
left join review r on tr.id = r.tour_id
where ut.user_id = 100 and (r.user_id = 100 or r.user_id is null)