问:
GRAPH: Generate sum of squares between 1 and 10 for polynomial graph
In an attempt to write a query in Python that will generate the first one hundred sums of squares between one and ten, the following attempt is made:

```<code>for a in range(1, 10):
    for b in range(1,10):
        print(a**2+b**2)
</code>```

Format should look like this:

```<code>1   1   4   9   16  25  36  49  64  81  100
4   5   8   13  20  29  40  53  68  85  104
9   10  13  18  25  34  45  58  73  90  109
16  17  20  25  32  41  52  65  80  97  116
25  26  38  34  41  50  61  74  89  106 125
36  37  40  45  52  61  72  85  100 117 136
49  75  53  58  65  74  85  98  113 130 149
64  65  68  73  80  89  100 113 128 145 164
81  82  85  90  97  106 117 130 145 162 181
100 101 104 109 116 125 136 149 164 181 200
</code>```

After reading that the sum of two squares in a polynomial will always be positive, it occurred to me that it would make a good dataset to have all the numbers that could be generated by the sum of two squares.   Polynomial like (a+b)*(a-b)...

Seems to me there should be an answer that creates a couple of matrices multiplied together.

So tried this but format is wrong (Thank UnsignedFoo for the help)

```<code>df=pd.Dataframe=([])
for a in range(1, 10):
    val_row = " ".join([str(a**2+b**2) for b in range(1,10)])
    print("{}\n".format("["+val_row+"]"))
    df.append("{}\n".format("["+val_row+"]"))
</code>```

It can be hard coded a line a time:

```<code>df1 = pd.DataFrame([[1, 2,3,4,5,6,7,8,9,10], [2,5,10,17,26,37,50,65,82,101]], columns=list('ABCDEFGHIJ'))
df2 = pd.DataFrame([[5,8,13,20,29,40,53,68,85,104], [10,13,18,25,34,45,58,73,90,109]], columns=list('ABCDEFGHIJ'))
df3 = pd.DataFrame([[17,20,25,32,41,52,65,80,97,116], [26,38,34,41,50,61,74,89,106,125]], columns=list('ABCDEFGHIJ'))
df4 = pd.DataFrame([[37,40,45,52,61,72,85,100,117,136], [75,53,58,65,74,85,98,113,130,149]], columns=list('ABCDEFGHIJ'))
df5 = pd.DataFrame([[65,68,73,80,89,100,113,128,145,164], [82,85,90,97,106,117,130,145,162,181]], columns=list('ABCDEFGHIJ'))
df6 = pd.DataFrame([[101,104,109,116,125,136,149,164,181,200], [126,125,130,137,146,157,170,185,202,221]], columns=list('ABCDEFGHIJ'))
df1.append(df2)
df1.append(df3)
df1.append(df4)
df1.append(df5)
df1.append(df6)
</code>```

And at that point can be graphed and it would be great if the matrice could be built with less work - up to this point, Excel does everything but the Excel doesn't have the advanced matplot libraries:

```<code>import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
%config InlineBackend.figure_format='retina'
from mpl_toolkits import mplot3d
fig=plt.figure(figsize=(8,6))
xs=df1['A']
ys=df1['B']
zs=df1['C']
ax=fig.add_subplot(111,projection='3d')
ax.scatter(xs,ys,zs,s=50,alpha=0.6,edgecolors='w')
ax.set_xlabel('A')
ax.set_ylabel('B')
ax.set_zlabel('C')
plt.show()
</code>```

A better example that is closer to where this should go is:

```<code>X = np.arange(1, 10, 1)
Y = np.arange(1, 10, 1)
X, Y = np.meshgrid(X, Y)
R = (X**2 + Y**2)# R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis)

plt.show()
</code>```

Still hoping someone can answer this question.  I'd like to delete and start again: the "answers" don't address the issue of graphing.

Body:
In an attempt to write a query in Python that will generate the first one hundred sums of squares between one and ten, the following attempt is made:

for a in range(1, 10):
    for b in range(1,10):
        print(a**2+b**2)

Format should look like this:

1   1   4   9   16  25  36  49  64  81  100
4   5   8   13  20  29  40  53  68  85  104
9   10  13  18  25  34  45  58  73  90  109
16  17  20  25  32  41  52  65  80  97  116
25  26  38  34  41  50  61  74  89  106 125
36  37  40  45  52  61  72  85  100 117 136
49  75  53  58  65  74  85  98  113 130 149
64  65  68  73  80  89  100 113 128 145 164
81  82  85  90  97  106 117 130 145 162 181
100 101 104 109 116 125 136 149 164 181 200

After reading that the sum of two squares in a polynomial will always be positive, it occurred to me that it would make a good dataset to have all the numbers that could be generated by the sum of two squares.   Polynomial like (a+b)*(a-b)...

Seems to me there should be an answer that creates a couple of matrices multiplied together.

So tried this but format is wrong (Thank UnsignedFoo for the help)

df=pd.Dataframe=([])
for a in range(1, 10):
    val_row = " ".join([str(a**2+b**2) for b in range(1,10)])
    print("{}\n".format("["+val_row+"]"))
    df.append("{}\n".format("["+val_row+"]"))

It can be hard coded a line a time:

df1 = pd.DataFrame([[1, 2,3,4,5,6,7,8,9,10], [2,5,10,17,26,37,50,65,82,101]], columns=list('ABCDEFGHIJ'))
df2 = pd.DataFrame([[5,8,13,20,29,40,53,68,85,104], [10,13,18,25,34,45,58,73,90,109]], columns=list('ABCDEFGHIJ'))
df3 = pd.DataFrame([[17,20,25,32,41,52,65,80,97,116], [26,38,34,41,50,61,74,89,106,125]], columns=list('ABCDEFGHIJ'))
df4 = pd.DataFrame([[37,40,45,52,61,72,85,100,117,136], [75,53,58,65,74,85,98,113,130,149]], columns=list('ABCDEFGHIJ'))
df5 = pd.DataFrame([[65,68,73,80,89,100,113,128,145,164], [82,85,90,97,106,117,130,145,162,181]], columns=list('ABCDEFGHIJ'))
df6 = pd.DataFrame([[101,104,109,116,125,136,149,164,181,200], [126,125,130,137,146,157,170,185,202,221]], columns=list('ABCDEFGHIJ'))
df1.append(df2)
df1.append(df3)
df1.append(df4)
df1.append(df5)
df1.append(df6)

And at that point can be graphed and it would be great if the matrice could be built with less work - up to this point, Excel does everything but the Excel doesn't have the advanced matplot libraries:

import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
%config InlineBackend.figure_format='retina'
from mpl_toolkits import mplot3d
fig=plt.figure(figsize=(8,6))
xs=df1['A']
ys=df1['B']
zs=df1['C']
ax=fig.add_subplot(111,projection='3d')
ax.scatter(xs,ys,zs,s=50,alpha=0.6,edgecolors='w')
ax.set_xlabel('A')
ax.set_ylabel('B')
ax.set_zlabel('C')
plt.show()

A better example that is closer to where this should go is:

X = np.arange(1, 10, 1)
Y = np.arange(1, 10, 1)
X, Y = np.meshgrid(X, Y)
R = (X**2 + Y**2)# R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis)

plt.show()

Still hoping someone can answer this question.  I'd like to delete and start again: the "answers" don't address the issue of graphing.

Body:
for a in range(1, 11):
   val_row = " ".join([str(a**2 + b**2 -1) for b in range(1,11)])
   print("{}\n".format(val_row))

Output:

1   4   9   16  25  36  49  64  81  100

4   7   12  19  28  39  52  67  84  103

9   12  17  24  33  44  57  72  89  108

16  19  24  31  40  51  64  79  96  115

25  28  33  40  49  60  73  88  105 124

36  39  44  51  60  71  84  99  116 135

49  52  57  64  73  84  97  112 129 148

64  67  72  79  88  99  112 127 144 163

81  84  89  96  105 116 129 144 161 180

100 103 108 115 124 135 148 163 180 199


来源: stackexchange

问:
NotificationServiceExtension with multiple targets in iOS Application
I have 3 targets in my iOS application namely Stage, Preprod and Prod. I added NotificationServiceExtension for the Stage target for the development purpose. Since the added NotificationServiceExtension is not available in other targets i.e pre-prod and prod, hence am not able to use the NotificationServiceExtension. Do i have to added 2 more NotificationServiceExtension for Preprod and prod targets? Or there is some different solution?
Thank you.</p>

答:
I'd recommend you to avoid using different targets for different environments. The better way is to use different build configurations, because:

.xcodeproj file will be much smaller

You will need single app extension

You will not need to add each new file to every target

You will not need to recompile the whole app for different environment

So in your case I'd create the following configs:

StageDebug

StageRelease

PreprodDebug

PreprodRelease

ProdDebug

ProdRelease

Here is a nice article about creating build configurations, have a look.

ContentLicense: CC BY-SA 4.0


问:
Why am I getting an unexpected Error in Snowflake PUT load?
I am trying to load a local csv file to my staging area in Snowflake, and am using:

```<code>PUT file:'//Users/mark 1/Downloads/pp-complete.csv' @~ auto_compress=true;
</code>```

But I keep getting the error:

SQL compilation error: parse error line 1 at position 9 near '39'.
  syntax error line 1 at position 74 unexpected '

As far as I can tell, there's nothing 'wrong' with the SCV file. It opens fine in SublimeEdit and Excel, and I can't see anything 'funny' in there to account for this.

Am stuck now.

Thanks,
Mark

答:
Could you try this?</p>

```<code>PUT 'file:///Users/mark 1/Downloads/pp-complete.csv' @~ auto_compress=true;
</code>```

Body:
I am trying to load a local csv file to my staging area in Snowflake, and am using:

PUT file:'//Users/mark 1/Downloads/pp-complete.csv' @~ auto_compress=true;

But I keep getting the error:

SQL compilation error: parse error line 1 at position 9 near '39'.
  syntax error line 1 at position 74 unexpected '

As far as I can tell, there's nothing 'wrong' with the SCV file. It opens fine in SublimeEdit and Excel, and I can't see anything 'funny' in there to account for this.

Am stuck now.

Thanks,
Mark

Body:
Could you try this?

PUT 'file:///Users/mark 1/Downloads/pp-complete.csv' @~ auto_compress=true;


问:
how to convert linq query into lambda expression
I have written Linq Query that i wanted to make it Lambda Expression. how to write the Lambda Expression in place of return statement
Linq Query. entities tables are entities.Users,entities.Users,entities.ponds

Query Expression :

```<code>from pond in Ponds
join customerdevice in CustomerDevices on pond.Imei equals customerdevice.Imei
join user in Users on customerdevice.CustomerId equals user.CustomerId
where user.Username=="user1"
select new { temp = pond.Temp, imei = pond.Imei,timestamp=pond.Timestatmp }
</code>```

Lambda Expression :

```<code> public async Task<IHttpActionResult> GetAllData(int deviceid)
        {
            using (smartpondEntities entities = new smartpondEntities())
            {
                try
                {
                    return Ok(await entities.ponds.Where(u=>u.deviceid==deviceid).OrderByDescending(u => u.timestatmp).ToListAsync());
                }
                catch (Exception Ex)
                {
                    return BadRequest("Sorry Error Found!!!");
                }
            }
        }
</code>```

答:
That's pretty much a 1-1 mapping.

```<code>entities.Ponds
    .Join(entities.CustomerDevices, pond => pond.Imei, device => device.Imei, new {pond,device});
    .Join(entities.Users, devicePond => devicePond.deviceCustomerId, user => user.CustomerId, new {devicePond.pond, devicePond.device, user})
    .Where( e => e.user.Username == "user1")
    .Select( e => new { temp = e.pond.Temp, imei = e.pond.Imei,timestamp=e.pond.Timestatmp })
    .ToListAsync();
</code>```

However, I'd suggest you add some navigational properties on your entities to shorten the Linq queries and have EF generate the joins for you.

```<code>public class Ponds {
    public string Imei {get;set}
    [ForeignKey(nameof(Imei))]
    public virtual CustomerDevice Device {get;set;}
}

public class CustomerDevices {
    [Key]
    public string Imei {get;set}
    public int CustomerId {get;set;}
    public int DeviceId {get;set;}
    [ForeignKey(nameof(CustomerId))]
    public virtual User Customer {get;set;}
}

public class Users {
    [Key]
    public int CustomerId {get;set;}
}
</code>```

Shorting the query to:

```<code>this.entites.Ponds.Where (
   e => e.Device.Customer.Username == "user1" ||
        e.Device.DeviceId == 1
)
.Select( e => new { temp = e.Temp, imei = e.Imei,timestamp=e.Timestatmp })
.FirstOrDefaultAsync();
</code>```

You should then consider using something like SQLProfiler if you're using a MS DB to view, and then optimize the EF-SQL query.

Body:
I have written Linq Query that i wanted to make it Lambda Expression. how to write the Lambda Expression in place of return statement
Linq Query. entities tables are entities.Users,entities.Users,entities.ponds

Query Expression :

from pond in Ponds
join customerdevice in CustomerDevices on pond.Imei equals customerdevice.Imei
join user in Users on customerdevice.CustomerId equals user.CustomerId
where user.Username=="user1"
select new { temp = pond.Temp, imei = pond.Imei,timestamp=pond.Timestatmp }

Lambda Expression :

 public async Task<IHttpActionResult> GetAllData(int deviceid)
        {
            using (smartpondEntities entities = new smartpondEntities())
            {
                try
                {
                    return Ok(await entities.ponds.Where(u=>u.deviceid==deviceid).OrderByDescending(u => u.timestatmp).ToListAsync());
                }
                catch (Exception Ex)
                {
                    return BadRequest("Sorry Error Found!!!");
                }
            }
        }

Body:
That's pretty much a 1-1 mapping.

entities.Ponds
    .Join(entities.CustomerDevices, pond => pond.Imei, device => device.Imei, new {pond,device});
    .Join(entities.Users, devicePond => devicePond.deviceCustomerId, user => user.CustomerId, new {devicePond.pond, devicePond.device, user})
    .Where( e => e.user.Username == "user1")
    .Select( e => new { temp = e.pond.Temp, imei = e.pond.Imei,timestamp=e.pond.Timestatmp })
    .ToListAsync();

However, I'd suggest you add some navigational properties on your entities to shorten the Linq queries and have EF generate the joins for you.

public class Ponds {
    public string Imei {get;set}
    [ForeignKey(nameof(Imei))]
    public virtual CustomerDevice Device {get;set;}
}

public class CustomerDevices {
    [Key]
    public string Imei {get;set}
    public int CustomerId {get;set;}
    public int DeviceId {get;set;}
    [ForeignKey(nameof(CustomerId))]
    public virtual User Customer {get;set;}
}

public class Users {
    [Key]
    public int CustomerId {get;set;}
}

Shorting the query to:

this.entites.Ponds.Where (
   e => e.Device.Customer.Username == "user1" ||
        e.Device.DeviceId == 1
)
.Select( e => new { temp = e.Temp, imei = e.Imei,timestamp=e.Timestatmp })
.FirstOrDefaultAsync();

You should then consider using something like SQLProfiler if you're using a MS DB to view, and then optimize the EF-SQL query.


问:
React + Firebase + Python
I have one project that I want to write in React frontend and Firebase as a database. But I need to write some functions with Python, I have some operations with ssh, valve, and FTP. Should I use Django? How to grab data that comes from Python libraries live like from base? What do you recommend?

Btw, I never user Python with Firebase and I have struggles.

答:
First, your question is not so clear down to the specifics. But on a higher level, whatever you want to do should be doable in firebase using Javascript. Firebase comes with cloud functions. This allows you to write actual backend code which can be executed either by a trigger or by an http request. So find out if you can find equivalent libraries in npm. Then implement the functionality you want in js. Then plug them into your cloud functions. Voila!!

If you can provide clearer details I might be able to give you more details support.

Title: React + Firebase + Python


问:
Prevent double active function on live table upload
I have a table with contenteditable value, when i change value an ajax action will update value for DB.
the problem is when clicking on a box and then on another immediately after the alert continues to appear without being able to do anything else.
Is there a way to prevent the other clicks function once started?

Code JS:

```<code>function showEdit(editableObj) {
  $(editableObj).css("background", "#FFF");
}

function saveToDatabase(editableObj, column, id) {
  var isGood = confirm('Are you sure?');
  if (isGood) {

    $(editableObj).css("background", "#FFF url(./img/loaderIcon.gif) no-repeat right");
    $.ajax({
      url: "saveedit.php",
      type: "POST",
      data: 'column=' + column + '&editval=' + editableObj.innerHTML + '&id=' + id,
      success: function(data) {
        $(editableObj).css("background", "#FDFDFD");
      }
    });
    //  }
  } else {
    alert('Abort');
  }
}
</code>```

Php table:

```<code>echo '<td contenteditable="true" onBlur="saveToDatabase(this, \'nameDB\', \''.$res2['valuefromDB'].'\')" onClick="showEdit(this);">' .$res2['valuefromDB'] .'</td>';
</code>```

答:
You can use a flag to prevent activation:</p>

```<code>var saveEnabled = true; // Only let you save when this is true
function saveToDatabase(editableObj, column, id) {
  if (!saveEnabled) return; // If saveEnabled is false do not continue
  saveEnabled = false;
  var isGood = confirm('Are you sure?');
  if (isGood) {
    $(editableObj).css("background", "#FFF url(./img/loaderIcon.gif) no-repeat right");
    $.ajax({
      url: "saveedit.php",
      type: "POST",
      data: 'column=' + column + '&editval=' + editableObj.innerHTML + '&id=' + id,
      complete: function(data) { // Errors should be handled before this
        $(editableObj).css("background", "#FDFDFD");
        saveEnabled = true;
      }
    });
    //  }
  } else {
    alert('Abort');
    saveEnabled = true;
  }
}
</code>```

Body:
I have a table with contenteditable value, when i change value an ajax action will update value for DB.
the problem is when clicking on a box and then on another immediately after the alert continues to appear without being able to do anything else.
Is there a way to prevent the other clicks function once started?

Code JS:

function showEdit(editableObj) {
  $(editableObj).css("background", "#FFF");
}

function saveToDatabase(editableObj, column, id) {
  var isGood = confirm('Are you sure?');
  if (isGood) {

    $(editableObj).css("background", "#FFF url(./img/loaderIcon.gif) no-repeat right");
    $.ajax({
      url: "saveedit.php",
      type: "POST",
      data: 'column=' + column + '&editval=' + editableObj.innerHTML + '&id=' + id,
      success: function(data) {
        $(editableObj).css("background", "#FDFDFD");
      }
    });
    //  }
  } else {
    alert('Abort');
  }
}

Php table:

echo '' .$res2['valuefromDB'] .'	';

Body:
You can use a flag to prevent activation:

var saveEnabled = true; // Only let you save when this is true
function saveToDatabase(editableObj, column, id) {
  if (!saveEnabled) return; // If saveEnabled is false do not continue
  saveEnabled = false;
  var isGood = confirm('Are you sure?');
  if (isGood) {
    $(editableObj).css("background", "#FFF url(./img/loaderIcon.gif) no-repeat right");
    $.ajax({
      url: "saveedit.php",
      type: "POST",
      data: 'column=' + column + '&editval=' + editableObj.innerHTML + '&id=' + id,
      complete: function(data) { // Errors should be handled before this
        $(editableObj).css("background", "#FDFDFD");
        saveEnabled = true;
      }
    });
    //  }
  } else {
    alert('Abort');
    saveEnabled = true;
  }
}


问:
How to connect to class component without passing props typescript
I started learning React with TypeScript and today I encountered a problem - I can't connect to component without passing data.

For example

```<code>import React from 'react';
import './App.css';
import Header from './components/Header';
import { PostInterface } from './pages/Posts';
import { Route, Switch } from 'react-router-dom';
import FullPost from './pages/FullPost';
import { BrowserRouter } from 'react-router-dom';
import PostsContainer from './pages/PostsContainer';

const App: React.FC = () => {
  return (
    <div className="App">
      <BrowserRouter>
        <Switch>
          <Route exact path="/">
            <Header image="https://www.linagro.tn/images/slider/slides/1920x400/southern-alps-1920x400.png" text="posts" />
            <PostsContainer />
          </Route>
          <Route path="/posts/:id">
            <Header image="https://www.linagro.tn/images/slider/slides/1920x400/southern-alps-1920x400.png" text="post" />
            <FullPost text="Post" title="It's my post" createdAt={Date.now} author="noname" />
          </Route>
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;
</code>```

I wanna render PostsContainer without passing there any props because the component will get the props using connect with react redux

```<code>import React, { Component } from 'react'
import { connect } from 'react-redux'
import Posts from './Posts';

class PostsContainer extends Component {
    render() {
        return (
            <Posts posts={this.props.posts} />
        )
    }
}

const mapStateToProps = (state: any) => {
    return {
        posts: state.posts
    }
}

export default connect(mapStateToProps, null)(PostsContainer);
</code>```

I get two errors:

Property 'posts' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
Object is possibly 'undefined'.

How can I render PostsContainer without passing data?

答:
The issue is that you havn't specified what kind of props PostsContainer takes, so by default it's assumed it doesn't take any props. Then when you try to use mapStateToProps to pass it a posts prop, typescript complains.

The fix is to update the types to include a posts prop:

```<code>interface PostsContainerProps {
  // not sure exactly what the type on the posts prop is, but assuming
  // you have a Post type defined somewhere, maybe something like:
  posts: Post[],
}

class PostsContainer extends Component<PostsContainerProps> {
  // rest is unchanged
</code>```

Body:
I started learning React with TypeScript and today I encountered a problem - I can't connect to component without passing data.

For example

import React from 'react';
import './App.css';
import Header from './components/Header';
import { PostInterface } from './pages/Posts';
import { Route, Switch } from 'react-router-dom';
import FullPost from './pages/FullPost';
import { BrowserRouter } from 'react-router-dom';
import PostsContainer from './pages/PostsContainer';

const App: React.FC = () => {
  return (

      <BrowserRouter>
        <Switch>
          <Route exact path="/">

            <PostsContainer />
          </Route>
          <Route path="/posts/:id">

            <FullPost text="Post" title="It's my post" createdAt={Date.now} author="noname" />
          </Route>
        </Switch>
      </BrowserRouter>

  );
}

export default App;

I wanna render PostsContainer without passing there any props because the component will get the props using connect with react redux

import React, { Component } from 'react'
import { connect } from 'react-redux'
import Posts from './Posts';

class PostsContainer extends Component {
    render() {
        return (
            <Posts posts={this.props.posts} />
        )
    }
}

const mapStateToProps = (state: any) => {
    return {
        posts: state.posts
    }
}

export default connect(mapStateToProps, null)(PostsContainer);

I get two errors:

Property 'posts' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
Object is possibly 'undefined'.

How can I render PostsContainer without passing data?

Body:
The issue is that you havn't specified what kind of props PostsContainer takes, so by default it's assumed it doesn't take any props. Then when you try to use mapStateToProps to pass it a posts prop, typescript complains.

The fix is to update the types to include a posts prop:

interface PostsContainerProps {
  // not sure exactly what the type on the posts prop is, but assuming
  // you have a Post type defined somewhere, maybe something like:
  posts: Post[],
}

class PostsContainer extends Component<PostsContainerProps> {
  // rest is unchanged


问:
Email message with no body part when attaching a file and sending via SMTP in Golang
I am trying to send an email message with both an email body and a file attachment (a CSV file) in Go (Golang).

I am following the mime standard of a multi-part message, however I am not  very familiar with the structure of the messages following that standard. I am vaguely following a Python code snippet from a colleague as a guide which is using the Python library email (I think this is from the standard library) e.g. MIMEText and MIMEMultipart.

The email message body is not showing up when executing the following Go code:

What is wrong with it?

How can I send an email message with both that file attachment and an email message body?

This function should return a byte slice to be used as a parameter for the call to smtp.SendMail from the Go standard library. See the comments below explaining what's happening to the received email message (the THIS DOES NOT SHOW UP [...] and the THIS ALSO DOES NOT SHOW UP [...]).

```<code>func msgWithAttachment(subject, filePath string) ([]byte, error) {
    // this is the separator used for the various parts of the MIME message structure
    // identified as "boundary"
    bPlaceholder := "our-custom-separator"

    // the message setup of the common/standard initial part
    mime := bytes.NewBuffer(nil)
    mime.WriteString(fmt.Sprintf("Subject: %s\r\nMIME-Version: 1.0\r\n", subject))
    mime.WriteString(fmt.Sprintf("Content-Type: multipart/mixed; boundary=%s\r\n", bPlaceholder))

    // THIS DOES NOT SHOW UP AS THE BODY OF THE EMAIL...
    // mime.WriteString("\r\n")
    // mime.WriteString(fmt.Sprintf("--%s\r\n", bPlaceholder))
    // mime.WriteString("This should be the email message body (v1)...")
    // mime.WriteString("\r\n")

    // THIS ALSO DOES NOT SHOW UP AS THE BODY OF THE EMAIL...
    // BUT IS NEEDED OTHERWISE THE EMAIL MESSAGE SEEMS TO CONTAIN AS ATTACHMENT THE EMAIL MESSAGE ITSELF
    // (CONTAINING ITSELF THE REAL ATTACHMENT)
    mime.WriteString(fmt.Sprintf("--%s\r\n", bPlaceholder))
    mime.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
    mime.WriteString("This should be the email message body (v2)...")

    // attach a file from the filesystem
    _, msgFilename := filepath.Split(filePath)
    mime.WriteString(fmt.Sprintf("\n--%s\r\n", bPlaceholder))
    mime.WriteString("Content-Type: application/octet-stream\r\n")
    mime.WriteString("Content-Description: " + msgFilename + "\r\n")
    mime.WriteString("Content-Transfer-Encoding: base64\r\n")
    mime.WriteString("Content-Disposition: attachment; filename=\"" + msgFilename + "\"\r\n\r\n")
    fileContent, err := ioutil.ReadFile(filePath) // read and encode the content of the file
    if err != nil {
        return nil, err
    }
    b := make([]byte, base64.StdEncoding.EncodedLen(len(fileContent)))
    base64.StdEncoding.Encode(b, fileContent)
    mime.Write(b)

    // footer of the email message
    mime.WriteString("\r\n--" + bPlaceholder + "--\r\n\r\n")

    return mime.Bytes(), nil
}
</code>```

答:
Coincidentally I had a similar issue the other day. I needed a blank line between the body content type and the beginning of the body itself. Below is the updated lines for this section of your code:

```<code>    mime.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
    mime.WriteString("\r\nThis should be the email message body (v2)...")
</code>```

For clarity, this newline (\r\n) doesn't have to be exactly here, it can be appended to the content-type line above. It just needs to see a blank line between the content-type and the beginning of the body.

I'm assuming the attachment is being attached without problems, correct? My assumption is this is because you have the double new-line at the end of the content-disposition line before the attachment data is added.

Body:
I am trying to send an email message with both an email body and a file attachment (a CSV file) in Go (Golang).

I am following the mime standard of a multi-part message, however I am not  very familiar with the structure of the messages following that standard. I am vaguely following a Python code snippet from a colleague as a guide which is using the Python library email (I think this is from the standard library) e.g. MIMEText and MIMEMultipart.

The email message body is not showing up when executing the following Go code:

What is wrong with it?

How can I send an email message with both that file attachment and an email message body?

This function should return a byte slice to be used as a parameter for the call to smtp.SendMail from the Go standard library. See the comments below explaining what's happening to the received email message (the THIS DOES NOT SHOW UP [...] and the THIS ALSO DOES NOT SHOW UP [...]).

func msgWithAttachment(subject, filePath string) ([]byte, error) {
    // this is the separator used for the various parts of the MIME message structure
    // identified as "boundary"
    bPlaceholder := "our-custom-separator"

    // the message setup of the common/standard initial part
    mime := bytes.NewBuffer(nil)
    mime.WriteString(fmt.Sprintf("Subject: %s\r\nMIME-Version: 1.0\r\n", subject))
    mime.WriteString(fmt.Sprintf("Content-Type: multipart/mixed; boundary=%s\r\n", bPlaceholder))

    // THIS DOES NOT SHOW UP AS THE BODY OF THE EMAIL...
    // mime.WriteString("\r\n")
    // mime.WriteString(fmt.Sprintf("--%s\r\n", bPlaceholder))
    // mime.WriteString("This should be the email message body (v1)...")
    // mime.WriteString("\r\n")

    // THIS ALSO DOES NOT SHOW UP AS THE BODY OF THE EMAIL...
    // BUT IS NEEDED OTHERWISE THE EMAIL MESSAGE SEEMS TO CONTAIN AS ATTACHMENT THE EMAIL MESSAGE ITSELF
    // (CONTAINING ITSELF THE REAL ATTACHMENT)
    mime.WriteString(fmt.Sprintf("--%s\r\n", bPlaceholder))
    mime.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
    mime.WriteString("This should be the email message body (v2)...")

    // attach a file from the filesystem
    _, msgFilename := filepath.Split(filePath)
    mime.WriteString(fmt.Sprintf("\n--%s\r\n", bPlaceholder))
    mime.WriteString("Content-Type: application/octet-stream\r\n")
    mime.WriteString("Content-Description: " + msgFilename + "\r\n")
    mime.WriteString("Content-Transfer-Encoding: base64\r\n")
    mime.WriteString("Content-Disposition: attachment; filename=\"" + msgFilename + "\"\r\n\r\n")
    fileContent, err := ioutil.ReadFile(filePath) // read and encode the content of the file
    if err != nil {
        return nil, err
    }
    b := make([]byte, base64.StdEncoding.EncodedLen(len(fileContent)))
    base64.StdEncoding.Encode(b, fileContent)
    mime.Write(b)

    // footer of the email message
    mime.WriteString("\r\n--" + bPlaceholder + "--\r\n\r\n")

    return mime.Bytes(), nil
}

Body:
Coincidentally I had a similar issue the other day. I needed a blank line between the body content type and the beginning of the body itself. Below is the updated lines for this section of your code:

    mime.WriteString("Content-Type: text/plain; charset=utf-8\r\n")
    mime.WriteString("\r\nThis should be the email message body (v2)...")

For clarity, this newline (\r\n) doesn't have to be exactly here, it can be appended to the content-type line above. It just needs to see a blank line between the content-type and the beginning of the body.

I'm assuming the attachment is being attached without problems, correct? My assumption is this is because you have the double new-line at the end of the content-disposition line before the attachment data is added.


问:
Flutter: Cannot build android apk
I have been getting errors building apk for flutter. But the app works well while I run it.

I have tried so many fixes like migrating to androidX and upgrading my dependencies but none worked. I recently started getting this error after upgrading flutter. What could be the solution to this?

Error

```<code>FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':shared_preferences:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     /Users/apple/.gradle/caches/transforms-2/files-2.1/d45c258d5b0086b06365ac1a25df0442/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     /Users/apple/.gradle/caches/transforms-2/files-2.1/d45c258d5b0086b06365ac1a25df0442/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':path_provider:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     /Users/apple/.gradle/caches/transforms-2/files-2.1/d45c258d5b0086b06365ac1a25df0442/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     /Users/apple/.gradle/caches/transforms-2/files-2.1/d45c258d5b0086b06365ac1a25df0442/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code>```

build.gradle

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 29

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.miraclecentre.bnotion.ben.maf_mentor"
        minSdkVersion 16
        targetSdkVersion 29
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:multidex:1.0.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

答:
Try changing your targetSdkVersion to 28.

That's the only fix I've run across.  But when I figure out why that is, I'll come back and update.

EDIT:

update your shared_pref version reference to the most recent one.
After that's done run

```<code>flutter pub cache repair
</code>```

Title: Flutter: Cannot build android apk

Body:
I have been getting errors building apk for flutter. But the app works well while I run it.

I have tried so many fixes like migrating to androidX and upgrading my dependencies but none worked. I recently started getting this error after upgrading flutter. What could be the solution to this?

Error

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':shared_preferences:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     /Users/apple/.gradle/caches/transforms-2/files-2.1/d45c258d5b0086b06365ac1a25df0442/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     /Users/apple/.gradle/caches/transforms-2/files-2.1/d45c258d5b0086b06365ac1a25df0442/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':path_provider:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     /Users/apple/.gradle/caches/transforms-2/files-2.1/d45c258d5b0086b06365ac1a25df0442/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     /Users/apple/.gradle/caches/transforms-2/files-2.1/d45c258d5b0086b06365ac1a25df0442/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 29

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.miraclecentre.bnotion.ben.maf_mentor"
        minSdkVersion 16
        targetSdkVersion 29
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:multidex:1.0.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Body:
Try changing your targetSdkVersion to 28.

That's the only fix I've run across.  But when I figure out why that is, I'll come back and update.

EDIT:

update your shared_pref version reference to the most recent one.
After that's done run

flutter pub cache repair


问:
Does one have to know Razor Pages to use scaffolded identity?
I'm developing an ASP.NET Core MVC application. I am using Razor Views and MVC as my preferred approach. I am also using individual user accounts. I have run scaffolding to create code connected with Identity management (Login, Register pages, etc.). That scaffolding results with creating Razor Pages, which seems to be a MVVM approach. Is there a way I could scaffold those features using Razor Views, what in turn would support MVC pattern?
I feel like I am mixing approaches due to that scaffolding. Now, when I want to add some feature connected with user profile, I have to write MVVM code, and I would like to use one approach instead.</p>

答: Yes indeed, Microsoft changed the Identity stuff when creating a new project a while ago, from classic Razor views to new Razor Pages. But luckily, you can grab all this old stuff from Github, for example here.</p>


问:
How to load a file to a specific path in a Container with ConfigMap?
I'm using the Helm chart to deploy Spark to Kubernetes in GCE. I want to provide a custom spark-defaults.conf file in a ConfigMap to be deployed to spark-master path /opt/bitnami/spark/conf.

But I don't understand how can I make another file custom-keys.yaml to be deployed to the same path that is referenced from the spark-defaults.conf?
The documentation only describes how to override default spark configuration. What is the correct way to load extra files and jars in this case?

I've specified a ConfigMap for spark-master in the values.yaml:

```<code>master:
  ## Set a custom configuration by using an existing configMap with the configuration file.
  ##
   configurationConfigMap: master-config
</code>```

master-config.yaml

```<code>kind: ConfigMap
metadata:
  name: master-config
data:
  {{ (.Files.Glob "files/spark-defaults.conf").AsConfig | indent 2 }}
</code>```

答:
The ConfigMap name can be provided on deployment time.</p>

```<code>helm install <Name> bitnami/spark --set master.configurationConfigMap=master-config
</code>```

Body:
I'm using the Helm chart to deploy Spark to Kubernetes in GCE. I want to provide a custom spark-defaults.conf file in a ConfigMap to be deployed to spark-master path /opt/bitnami/spark/conf.

But I don't understand how can I make another file custom-keys.yaml to be deployed to the same path that is referenced from the spark-defaults.conf?
The documentation only describes how to override default spark configuration. What is the correct way to load extra files and jars in this case?

I've specified a ConfigMap for spark-master in the values.yaml:

master:
  ## Set a custom configuration by using an existing configMap with the configuration file.
  ##
   configurationConfigMap: master-config

master-config.yaml

kind: ConfigMap
metadata:
  name: master-config
data:
  {{ (.Files.Glob "files/spark-defaults.conf").AsConfig | indent 2 }}

Body:
The ConfigMap name can be provided on deployment time.

helm install <Name> bitnami/spark --set master.configurationConfigMap=master-config


问:
No bean named 'loggingFilter' available error when deploying Spring Boot application in Tomcat
I have a Spring Boot application with Spring Security enabled. When I run it on IntelliJ it works fine and I am able to log in and use the application as expected. But when I try to deploy it on tomcat 8.5.x and 9.x I get the error No bean named 'loggingFilter' available error when deploying the application in Tomcat. Here is the complete log

```<code>08-Feb-2020 00:59:35.839 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log 3 Spring WebApplicationInitializers detected on classpath
08-Feb-2020 00:59:39.959 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring embedded WebApplicationContext
08-Feb-2020 00:59:57.047 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.filterStart Exception starting filter [delegatingFilterProxy]
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'loggingFilter' available
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:805)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1278)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:297)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1114)
        at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:338)
        at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:243)
        at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:239)
        at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:283)
        at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:112)
        at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4546)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5191)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:743)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:719)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:705)
        at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1720)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:287)
        at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:809)
        at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
        at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:479)
        at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:428)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:287)
        at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:809)
        at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
        at java.management/com.sun.jmx.remote.security.MBeanServerAccessController.invoke(MBeanServerAccessController.java:468)
        at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
        at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1406)
        at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:827)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:834)
08-Feb-2020 00:59:57.052 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext
</code>```

If it helps, I use logback.xml file to show INFO logs

```<code><configuration debug="true" scan="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

</code>```

pom.xml

```<code><properties>
    <java.version>11</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
    <javax.servlet-api.version>3.0.1</javax.servlet-api.version>
    <jsp-api.version>2.2</jsp-api.version>
    <tiles-jsp.version>3.0.8</tiles-jsp.version>
    <json-simple.version>1.1</json-simple.version>
    <commons-fileupload.version>1.3.1</commons-fileupload.version>
    <joda-time.version>2.10.4</joda-time.version>
    <modelmapper.version>2.3.0</modelmapper.version>
    <lombok.version>1.18.10</lombok.version>
    <jackson.version>2.9.3</jackson.version>
    <junit.version>4.12</junit.version>
    <spring-boot.version>2.2.2.RELEASE</spring-boot.version>
    <json.version>20190722</json.version>
    <validation-api.version>2.0.1.Final</validation-api.version>
    <hibernate.version>5.4.10.Final</hibernate.version>
    <mssql-jdbc.version>7.4.1.jre11</mssql-jdbc.version>
    <hazelcast.version>3.12.6</hazelcast.version>
    <jjwt.version>0.9.1</jjwt.version>
</properties>
<dependencies>
        <!-- Spring Core dependencies-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
        </dependency>
        <dependency>
            <groupId>com.unboundid</groupId>
            <artifactId>unboundid-ldapsdk</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>${spring-boot.version}</version>
            <optional>false</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!-- Other Core dependencies-->

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>${mssql-jdbc.version}</version>
        </dependency>

        <!-- Utilities-->
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast</artifactId>
            <version>${hazelcast.version}</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-spring</artifactId>
            <version>${hazelcast.version}</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-hibernate53</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-client</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>${json.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>${modelmapper.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>${validation-api.version}</version>
        </dependency>

        <!-- Test dependencies-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <version>${spring-boot.version}</version>
        </dependency>

    </dependencies>
</code>```

答:
In your question you indicate that "...When I run it on IntelliJ it works fine... But when I try to deploy it on tomcat 8.5.x and 9.x I get the error..."

Follow these steps to find the cause:

1) Do a complete Project clean: maven clean update, Tomcat clean, and regenerate the war files. This will ensure that your war is the same on both tests.

2) If the problem persists look at ItelliJ server version and make sure you are using the same Tomcat version for deployment.

3) If none of these is the cause you may be trying to fetch the required files from a remote location. Do you have aditional war files in the Tomcat server? are they using the same version? are you able to manually deploy in a fresh Tomcat on your machine without the help of IntellJ?

4) If the Tomcat is exactly the same, the wars are exactly the same and the Host is exactly the same. the results should be exactly the same*. If this is not the case, one of the previous statements is false so double check.

*Java version, memory allocation, and Server options can also Affect the result, but most likely it's not the case here.

After you find the cause you can apply the following to solve it:

If your cause is the War, compare it with the previous working version, and you will probably find to have added a Custom Filter while adding Spring Security.

If your cause is Tomcat, you may have a few extra libraries in IntelliJ's which your out of the box tomcat does not have.

And if you use aditional wars make sure to update them

For a detailed explanation of DelegatingFilterProxy and Custom Filters checkout borchvm's awnser.

Body:
I have a Spring Boot application with Spring Security enabled. When I run it on IntelliJ it works fine and I am able to log in and use the application as expected. But when I try to deploy it on tomcat 8.5.x and 9.x I get the error No bean named 'loggingFilter' available error when deploying the application in Tomcat. Here is the complete log

08-Feb-2020 00:59:35.839 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log 3 Spring WebApplicationInitializers detected on classpath
08-Feb-2020 00:59:39.959 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring embedded WebApplicationContext
08-Feb-2020 00:59:57.047 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.filterStart Exception starting filter [delegatingFilterProxy]
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'loggingFilter' available
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:805)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1278)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:297)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1114)
        at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:338)
        at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:243)
        at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:239)
        at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:283)
        at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:112)
        at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4546)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5191)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:743)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:719)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:705)
        at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1720)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:287)
        at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:809)
        at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
        at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:479)
        at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:428)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:287)
        at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:809)
        at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
        at java.management/com.sun.jmx.remote.security.MBeanServerAccessController.invoke(MBeanServerAccessController.java:468)
        at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
        at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1406)
        at java.management.rmi/javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:827)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:834)
08-Feb-2020 00:59:57.052 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext

If it helps, I use logback.xml file to show INFO logs

<configuration debug="true" scan="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

pom.xml

<properties>
    <java.version>11</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
    <javax.servlet-api.version>3.0.1</javax.servlet-api.version>
    <jsp-api.version>2.2</jsp-api.version>
    <tiles-jsp.version>3.0.8</tiles-jsp.version>
    <json-simple.version>1.1</json-simple.version>
    <commons-fileupload.version>1.3.1</commons-fileupload.version>
    <joda-time.version>2.10.4</joda-time.version>
    <modelmapper.version>2.3.0</modelmapper.version>
    <lombok.version>1.18.10</lombok.version>
    <jackson.version>2.9.3</jackson.version>
    <junit.version>4.12</junit.version>
    <spring-boot.version>2.2.2.RELEASE</spring-boot.version>
    <json.version>20190722</json.version>
    <validation-api.version>2.0.1.Final</validation-api.version>
    <hibernate.version>5.4.10.Final</hibernate.version>
    <mssql-jdbc.version>7.4.1.jre11</mssql-jdbc.version>
    <hazelcast.version>3.12.6</hazelcast.version>
    <jjwt.version>0.9.1</jjwt.version>
</properties>
<dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
        </dependency>
        <dependency>
            <groupId>com.unboundid</groupId>
            <artifactId>unboundid-ldapsdk</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>${spring-boot.version}</version>
            <optional>false</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>${mssql-jdbc.version}</version>
        </dependency>

        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast</artifactId>
            <version>${hazelcast.version}</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-spring</artifactId>
            <version>${hazelcast.version}</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-hibernate53</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-client</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>${json.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>${modelmapper.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>${validation-api.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <version>${spring-boot.version}</version>
        </dependency>

    </dependencies>


问:
React router catching webapi routes
.NET Core 3.1 web application with react 16.12.0.

Problem

Newbie at react... when I fetch 'api/checksheet/types' it gets caught by '/checksheet/:checkSheetTypeId' and it attempts to load the component declared for that route.

How do I eliminate the conflict between front end and server side routes?

Server side, 2 endpoints

```<code>[Route("api/[controller]")]
[ApiController]
public class CheckSheetController : ControllerBase
{
    // GET: api/checksheet/types
    [HttpGet]
    public IList Types()
    {
    }

    // GET: api/checksheet/{id}
    [HttpGet("{id}")]
    public Dto Get(int id)
    {
    }
}
</code>```

App.js

```<code><Layout>
    <Switch>
        <Route exact path='/checksheet/add' component={AddChecksheet} />
        <Route path='/checksheet/:checkSheetTypeId' component={TasksPage} />
    </Switch>
</Layout>
</code>```

Component

```<code>import React, { Component } from 'react';

export class NavMenu extends Component {
    constructor(props) {
        super(props);
        this.state = { types: [], loading: true };
    }

    componentDidMount() {
        this.getTypes();
    }

    async getTypes() {
        const response = await fetch('api/checksheet/types');
        const data = await response.json();
        this.setState({ types: data, loading: false });
    }
}
</code>```

答:
Coming to think about, I can solve this by following the RESTful API naming conventions, so that CheckSheetController is pluralised, then making my endpoint calls /api/checksheets/{id}

Though there must be another solution....

Title: React router catching webapi routes

Body:
.NET Core 3.1 web application with react 16.12.0.

Problem

Newbie at react... when I fetch 'api/checksheet/types' it gets caught by '/checksheet/:checkSheetTypeId' and it attempts to load the component declared for that route.

How do I eliminate the conflict between front end and server side routes?

Server side, 2 endpoints

[Route("api/[controller]")]
[ApiController]
public class CheckSheetController : ControllerBase
{
    // GET: api/checksheet/types
    [HttpGet]
    public IList Types()
    {
    }

    // GET: api/checksheet/{id}
    [HttpGet("{id}")]
    public Dto Get(int id)
    {
    }
}

App.js

<Layout>
    <Switch>
        <Route exact path='/checksheet/add' component={AddChecksheet} />
        <Route path='/checksheet/:checkSheetTypeId' component={TasksPage} />
    </Switch>
</Layout>

Component

import React, { Component } from 'react';

export class NavMenu extends Component {
    constructor(props) {
        super(props);
        this.state = { types: [], loading: true };
    }

    componentDidMount() {
        this.getTypes();
    }

    async getTypes() {
        const response = await fetch('api/checksheet/types');
        const data = await response.json();
        this.setState({ types: data, loading: false });
    }
}


问:
Initialise first n members only of struct or array
I'm using the clang compiler (c++ 11 I think) that comes with RAD studio 10.2. By mistake I discovered today that the first n members of a struct or array can be assigned using the usual curly brackets e.g.

```<code>int a[500]={1};
struct {int a,b,c;} st={2,3};
</code>```

The above compiles and works fine but I've never come across this or seen it used before and I can find no mention of it online (maybe I'm searching using the wrong type of wording). Is this c++ documented?

答:
I've never come across this or seen it used before and I can find no mention of it online (maybe I'm searching using the wrong type of wording). Is this c++ documented?

Yes, this is documented. This syntax is called list initialisation - and more specifically since the types are aggregates: This is aggregate initialisation.

Initialise first n members only of struct or array

It is not possible to only initialise some members / elements. If you list initialise class object or array, then all of it will be initialised. The members / elements which lack an initialiser will be value initialised.

If you wanted to do that, then what you can do instead is default initialise the class object or array, and then initialise the sub objects selectively afterwards.

Body:
I'm using the clang compiler (c++ 11 I think) that comes with RAD studio 10.2. By mistake I discovered today that the first n members of a struct or array can be assigned using the usual curly brackets e.g.

int a[500]={1};
struct {int a,b,c;} st={2,3};

The above compiles and works fine but I've never come across this or seen it used before and I can find no mention of it online (maybe I'm searching using the wrong type of wording). Is this c++ documented?


问:
How to display mouse pointer in my recording
I am making a screen recorder that records the screen of the desktop. However, when I record the screen, the mouse pointer (cursor) is not visible in the recording.
Is there any way I can show the mouse pointer in my recording?
This is my current code:

import cv2
import numpy as np
import pyautogui
import datetime

date = datetime.datetime.now()

SCREEN_SIZE = (1366, 768)
framerate = 12

fourcc = cv2.VideoWriter_fourcc(*'XVID')
filename = 'E:/project/videos/rec_%s%s%s%s%s%s.avi' % (date.year, date.month, date.day, date.hour, date.minute, date.second)

out = cv2.VideoWriter(filename, fourcc,framerate, SCREEN_SIZE)

while True:
    img = pyautogui.screenshot()
    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    out.write(frame)
    cv2.imshow('screenshot', frame)
    if cv2.waitKey(1) == ord("q"):
        break

cv2.destroyAllWindows()
out.release()
```

答:
I don't think it's possible with that approach - but am always happy to be corrected and learn something new. I know of a couple of workarounds.

The first is to continue to use pyautogui and to call its mouseposition() function and paste/draw your own synthetic mouse pointer onto the grab. I did that with OpenCV's fillPoly() function:

```<code>#!/usr/bin/env python3

import cv2
import numpy as np
import pyautogui
import datetime

# X and Y coordinates of mouse pointer
Xs = [0,8,6,14,12,4,2,0]
Ys = [0,2,4,12,14,6,8,0]

while True:

    img = pyautogui.screenshot()
    mouseX,mouseY = pyautogui.position()
    mouseX *= 2
    mouseY *= 2

    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

    # Synthesize mouse pointer
    Xthis = [4*x+mouseX for x in Xs]
    Ythis = [4*y+mouseY for y in Ys]
    points = list(zip(Xthis,Ythis))
    points = np.array(points, 'int32')
    cv2.fillPoly(frame,[points],color=[255,255,255])

    # Make it a bit smaller for display
    frame = cv2.resize(frame,(960,540))

    cv2.imshow('Title', frame)
    if cv2.waitKey(1) == ord("q"):
        break

cv2.destroyAllWindows()
out.release()
</code>```

The second is to use ffmpeg which can capture the mouse - you can either run ffmpeg in place of your current app, or pipe the output from ffmpeg into your app through a pipe and continue to process it as you are now. That might look like this:

```<code>#!/usr/bin/env python3

# ffmpeg -y -pix_fmt bgr0 -f avfoundation -r 20 -t 10 -i 1 -vf scale=w=3840:h=2160 -f rawvideo /dev/null

import sys
import cv2
import time
import subprocess
import numpy as np

w,h = 3840, 2160

def ffmpegGrab():
    """Generator to read frames from ffmpeg subprocess"""
    cmd = [
        'ffmpeg',
        '-pix_fmt', 'bgr0',
        '-f', 'avfoundation',
        '-capture_cursor', '1',
        '-capture_mouse_clicks', '1',
        '-r', '20',
        '-i', '1',
        '-vf','scale=w=3840:h=2160',
        '-f', 'rawvideo',
        'pipe:1'
    ]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while True:
        frame = proc.stdout.read(w*h*4)
        yield np.frombuffer(frame, dtype=np.uint8).reshape((h,w,4))

# Get frame generator
gen = ffmpegGrab()

# Get start time
start = time.time()

# Read video frames from ffmpeg in loop
nFrames = 0
while True:
    # Read next frame from ffmpeg
    frame = next(gen)
    nFrames += 1
    frame = cv2.resize(frame,(960,540))

    cv2.imshow('screenshot', frame)

    if cv2.waitKey(1) == ord("q"):
        break

    fps = nFrames/(time.time()-start)
    print(f'FPS: {fps}')

cv2.destroyAllWindows()
out.release()
</code>```

Note that pyautogui takes around 600ms to capture one frame on my Mac, whereas the ffmpeg above achieves around 20fps, or 50ms per frame.

Keywords: Python. image processing, ffmpeg, pyautogui, screen-grab, screen-capture, screengrab, screencapture, fps. speed, prime.

Body:
I don't think it's possible with that approach - but am always happy to be corrected and learn something new. I know of a couple of workarounds.

The first is to continue to use pyautogui and to call its mouseposition() function and paste/draw your own synthetic mouse pointer onto the grab. I did that with OpenCV's fillPoly() function:

#!/usr/bin/env python3

import cv2
import numpy as np
import pyautogui
import datetime

# X and Y coordinates of mouse pointer
Xs = [0,8,6,14,12,4,2,0]
Ys = [0,2,4,12,14,6,8,0]

while True:

    img = pyautogui.screenshot()
    mouseX,mouseY = pyautogui.position()
    mouseX *= 2
    mouseY *= 2

    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

    # Synthesize mouse pointer
    Xthis = [4*x+mouseX for x in Xs]
    Ythis = [4*y+mouseY for y in Ys]
    points = list(zip(Xthis,Ythis))
    points = np.array(points, 'int32')
    cv2.fillPoly(frame,[points],color=[255,255,255])

    # Make it a bit smaller for display
    frame = cv2.resize(frame,(960,540))

    cv2.imshow('Title', frame)
    if cv2.waitKey(1) == ord("q"):
        break

cv2.destroyAllWindows()
out.release()

The second is to use ffmpeg which can capture the mouse - you can either run ffmpeg in place of your current app, or pipe the output from ffmpeg into your app through a pipe and continue to process it as you are now. That might look like this:

#!/usr/bin/env python3

# ffmpeg -y -pix_fmt bgr0 -f avfoundation -r 20 -t 10 -i 1 -vf scale=w=3840:h=2160 -f rawvideo /dev/null

import sys
import cv2
import time
import subprocess
import numpy as np

w,h = 3840, 2160

def ffmpegGrab():
    """Generator to read frames from ffmpeg subprocess"""
    cmd = [
        'ffmpeg',
        '-pix_fmt', 'bgr0',
        '-f', 'avfoundation',
        '-capture_cursor', '1',
        '-capture_mouse_clicks', '1',
        '-r', '20',
        '-i', '1',
        '-vf','scale=w=3840:h=2160',
        '-f', 'rawvideo',
        'pipe:1'
    ]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while True:
        frame = proc.stdout.read(w*h*4)
        yield np.frombuffer(frame, dtype=np.uint8).reshape((h,w,4))

# Get frame generator
gen = ffmpegGrab()

# Get start time
start = time.time()

# Read video frames from ffmpeg in loop
nFrames = 0
while True:
    # Read next frame from ffmpeg
    frame = next(gen)
    nFrames += 1
    frame = cv2.resize(frame,(960,540))

    cv2.imshow('screenshot', frame)

    if cv2.waitKey(1) == ord("q"):
        break

    fps = nFrames/(time.time()-start)
    print(f'FPS: {fps}')

cv2.destroyAllWindows()
out.release()

Note that pyautogui takes around 600ms to capture one frame on my Mac, whereas the ffmpeg above achieves around 20fps, or 50ms per frame.

Keywords: Python. image processing, ffmpeg, pyautogui, screen-grab, screen-capture, screengrab, screencapture, fps. speed, prime.


问:
Dynamically assign a field
I'm trying to generate code for dynamically assigning field values to a dynamic class. Basically, what I'd ideally be able to do is something to this effect:

il.Emit(OpCodes.Ldarg_0); // Object instance
il.Emit(OpCodes.Ldc_I4_0); // Value to assign to the field
il.Emit(OpCodes.Ld???, fieldInfo); // FieldInfo to assign the value to
il.Emit(OpCodes.Stfld); // Some kind of Stfld that pops the field and the value and assigns it
```

<p>I was not able to find any instruction that would suit my needs. Another idea I had was to generate a setter method for each field and invoke that method, but I did not find a method to do that without converting it into a Delegate, which generated <em>a lot</em> of boilerplate code.</p>

<p>Does anyone have a better solution?</p>

<p>EDIT:
The issue is that the field that needs to be assigned has to be found on the stack, and somehow pop'd when the time to assign it comes. Unfortunately, none of the CIL instructions support popping a fieldInfo to assign to it, but maybe there are other solutions I had not thought about.</p>

<p>EDIT2: I'll give a bit more of the surrounding scenario, hopefully the context will make things clearer.</p>

<p>I'm trying to make a sort of "recompiler" from a stack-based vm bytecode to CIL. The bytecode in question does not access fields in a struct like the CIL does it, i.e. statically. Instead, the reference to the field to be accessed is pushed on the stack, and the <code>store</code> instruction takes care of the rest.</p>

<p>Here's a sample of what this bytecode might look like:</p>

```PushFloat 0.0
PushField [someField]
SetField
```

What I'd like to obtain would be something like the code I've written above, but the CIL only supports assigning to fields which are known at codegen time.

答:
I've solved this by using ldflda and stind:

il.Emit(OpCodes.Ldarg_0); // Object instance
il.Emit(OpCodes.Ldflda, fieldInfo); // Loads reference to field
il.Emit(OpCodes.Conv_U); // Converts to pointer
il.Emit(OpCodes.Ldc_I4_0); // Something to put in the field
il.Emit(OpCodes.Stind_I4); // Put the value in the field
```

Which appears to be doing roughly what I had initially set out to do.

Title: Dynamically assign a field

Body:
I'm trying to generate code for dynamically assigning field values to a dynamic class. Basically, what I'd ideally be able to do is something to this effect:

il.Emit(OpCodes.Ldarg_0); // Object instance
il.Emit(OpCodes.Ldc_I4_0); // Value to assign to the field
il.Emit(OpCodes.Ld???, fieldInfo); // FieldInfo to assign the value to
il.Emit(OpCodes.Stfld); // Some kind of Stfld that pops the field and the value and assigns it

I was not able to find any instruction that would suit my needs. Another idea I had was to generate a setter method for each field and invoke that method, but I did not find a method to do that without converting it into a Delegate, which generated a lot of boilerplate code.

Does anyone have a better solution?

EDIT:
The issue is that the field that needs to be assigned has to be found on the stack, and somehow pop'd when the time to assign it comes. Unfortunately, none of the CIL instructions support popping a fieldInfo to assign to it, but maybe there are other solutions I had not thought about.

EDIT2: I'll give a bit more of the surrounding scenario, hopefully the context will make things clearer.

I'm trying to make a sort of "recompiler" from a stack-based vm bytecode to CIL. The bytecode in question does not access fields in a struct like the CIL does it, i.e. statically. Instead, the reference to the field to be accessed is pushed on the stack, and the store instruction takes care of the rest.

Here's a sample of what this bytecode might look like:

PushFloat 0.0
PushField [someField]
SetField

What I'd like to obtain would be something like the code I've written above, but the CIL only supports assigning to fields which are known at codegen time.

Body:
I've solved this by using ldflda and stind:

il.Emit(OpCodes.Ldarg_0); // Object instance
il.Emit(OpCodes.Ldflda, fieldInfo); // Loads reference to field
il.Emit(OpCodes.Conv_U); // Converts to pointer
il.Emit(OpCodes.Ldc_I4_0); // Something to put in the field
il.Emit(OpCodes.Stind_I4); // Put the value in the field

Which appears to be doing roughly what I had initially set out to do.


问:
Cannot import name 'easter' from 'holidays'
I am trying to import fbprophet on Python Anaconda, however, I get this error:

```<code> ImportError: cannot import name 'easter' from 'holidays'
</code>```

Can anyone suggest what might have gone wrong?

Code:

```<code>from fbprophet import fbprophet
</code>```

答:
I'm using anaconda, and the only solution that worked for me was:

Replace line 16 in fbprophet/hdays.py (\AppData\Local\Continuum\anaconda3\Lib\site-packages\fbprophet\hdays.py):

```<code>from holidays import WEEKEND, HolidayBase, easter, rd
</code>```

to

```<code>from holidays import WEEKEND, HolidayBase
from dateutil.easter import easter
from dateutil.relativedelta import relativedelta as rd
</code>```

Body:
I am trying to import fbprophet on Python Anaconda, however, I get this error:

 ImportError: cannot import name 'easter' from 'holidays'

Can anyone suggest what might have gone wrong?

Code:

from fbprophet import fbprophet

Body:
I'm using anaconda, and the only solution that worked for me was:

Replace line 16 in fbprophet/hdays.py (\AppData\Local\Continuum\anaconda3\Lib\site-packages\fbprophet\hdays.py):

from holidays import WEEKEND, HolidayBase, easter, rd

to

from holidays import WEEKEND, HolidayBase
from dateutil.easter import easter
from dateutil.relativedelta import relativedelta as rd


问:
Azure Machine Learning - slow to start
I am working with Azure AI and initially had been using Machine Learning Studio Classic.

It was working well but was slow training my models. From looking around, it seems that if I use Azure Machine Learning Studio, I can control the hardware used to run the experiments, so this is what I am trying.

My issue is that Azure Machine Learning Studio is extremely slow in starting the experiments-it can take 10 minutes to even start.

Is this as expected or am I missing something?

Incidentally, NC24 was actually slower than NC6 - is this because of the configuration of my experiment?

GPU Training    Whole run
NC6 2m 36s  10m 48s
NC24    2m 52s  16m 48s

答:
I'm assuming that you're:

using Azure ML Studio (i.e. ml.azure.com/)'s Pipeline Designer, and

creating a new compute target before running?

If so, then 10 minutes is normal for the first run, given that a cluster of VMs has to be created and provisioned with a Docker container and Conda environment. After the run first completes the compute target is configured to stay on and available for two hours so future runs should execute without the 10 minute delay (provided you don't change the Conda dependencies or choose a new compute target).

more information about AMLCompute

Title: Azure Machine Learning - slow to start


问:
How do I create a pipeline of functions so that functions run one after another?
I want to create classes where each class is associated with some function. I want to stack these functions in series such that one function runs after another in a user defined order. I am new to C++ so correct me wherever my syntax is wrong.

```<code>#include<iostream>
using namespace std;
class Function
{
public:
    virtual void setSuccessor(Function *) = 0;
    virtual void Start(int value) = 0;
};

class Prime:public Function
{
public:
    Prime()
    {
        successor=NULL;
    }
    Function *successor;
    void setSuccessor(Function *f)
    {
//if a successor is not declared then assign successor.
//else if a successor is already defined then set the new function as the successor of the successor.
        if (successor == NULL)
            successor = f;
        else
            successor->setSuccessor(f);
    }

    void Start(int value)
    {
        //prime function
        cout<<"I am Prime Function\n";
        //if successor !=null
        //  call successor
        if(successor!=NULL)
            successor->Start(value);
    }

};
class Even:public Function
{
public:
    Even()
    {
        successor=NULL;
    }
    Function *successor;
    void setSuccessor(Function *f)
    {
        if (successor == NULL)
            successor = f;
        else
            successor->setSuccessor(f);
    }

    void Start(int value)
    {
        //prime function
        cout<<"I am Even Function\n";
        //if successor !=null
        //  call successor
        if(successor!=NULL)
            successor->Start(value);
    }

};

class Pipeline
{
    public:
    Function *function;
    void addToPipe(Function* function)
    {
        if(this->function==NULL)
            this->function=function;
        else
            function->setSuccessor(function);
    }
    void start(int value)
    {
        function->Start(value);
    }
};
int main()
{
    Pipeline pipe;
    pipe.addToPipe(new Prime());
    pipe.addToPipe(new Even());
    pipe.start(5);
}
</code>```

In this program I have stacked Prime first then Even. I want that my function prime starts then Even starts. Since no other function is added so it should stop after Even. This program has runtime errors. Please help me detect them

答:
You may use standard library templates for this and avoid writing your own classes. For example,

```<code># include <iostream>

void prime(int) { cout << "Prime" << endl; }
void even(int) { cout << "Even" << endl; }

...

#include <functional>
#include <vector>

std::vector<std::function<void(int)>> pipeline;
pipeline.push_back(prime);
pipeline.push_back(even);

...

for (const auto& f : pipeline) f();
</code>```

Note that it seems odd to have functions named "prime" and "even" that return void.

Body:
I want to create classes where each class is associated with some function. I want to stack these functions in series such that one function runs after another in a user defined order. I am new to C++ so correct me wherever my syntax is wrong.

#include<iostream>
using namespace std;
class Function
{
public:
    virtual void setSuccessor(Function *) = 0;
    virtual void Start(int value) = 0;
};

class Prime:public Function
{
public:
    Prime()
    {
        successor=NULL;
    }
    Function *successor;
    void setSuccessor(Function *f)
    {
//if a successor is not declared then assign successor.
//else if a successor is already defined then set the new function as the successor of the successor.
        if (successor == NULL)
            successor = f;
        else
            successor->setSuccessor(f);
    }

    void Start(int value)
    {
        //prime function
        cout<<"I am Prime Function\n";
        //if successor !=null
        //  call successor
        if(successor!=NULL)
            successor->Start(value);
    }

};
class Even:public Function
{
public:
    Even()
    {
        successor=NULL;
    }
    Function *successor;
    void setSuccessor(Function *f)
    {
        if (successor == NULL)
            successor = f;
        else
            successor->setSuccessor(f);
    }

    void Start(int value)
    {
        //prime function
        cout<<"I am Even Function\n";
        //if successor !=null
        //  call successor
        if(successor!=NULL)
            successor->Start(value);
    }

};

class Pipeline
{
    public:
    Function *function;
    void addToPipe(Function* function)
    {
        if(this->function==NULL)
            this->function=function;
        else
            function->setSuccessor(function);
    }
    void start(int value)
    {
        function->Start(value);
    }
};
int main()
{
    Pipeline pipe;
    pipe.addToPipe(new Prime());
    pipe.addToPipe(new Even());
    pipe.start(5);
}

In this program I have stacked Prime first then Even. I want that my function prime starts then Even starts. Since no other function is added so it should stop after Even. This program has runtime errors. Please help me detect them

Body:
You may use standard library templates for this and avoid writing your own classes. For example,

# include <iostream>

void prime(int) { cout << "Prime" << endl; }
void even(int) { cout << "Even" << endl; }

...

#include <functional>
#include <vector>

std::vector<std::function<void(int)>> pipeline;
pipeline.push_back(prime);
pipeline.push_back(even);

...

for (const auto& f : pipeline) f();

Note that it seems odd to have functions named "prime" and "even" that return void.


答:
For aggregate initialization,

(emphasis mine)

If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default member initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates).

That means, for int a[500]={1};, the 1st element is initialized to 1 and the remaining 499 elements of the array are value-initialized to 0. For struct {int a,b,c;} st={2,3};, the member a is initialized to 2 and b is initialized to 3, the last member c is value-initialized to 0 too.

Title: Initialise first n members only of struct or array


问:
Jquery Cookie plugin, check to see if cookie is unset
So Im using the jquery cookie plugin and I need to check if a cookie is unset. I set it up something like this:

```<code>if ($.cookie('language')==null) {

}
</code>```

This doesn't seem to work. Any ideas why?

答:
Use simply:</p>

```<code>if($.cookie("language")){}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So Im using the jquery cookie plugin and I need to check if a cookie is unset. I set it up something like this:

if ($.cookie('language')==null) {

}

This doesn't seem to work. Any ideas why?

Body:
Use simply:

if($.cookie("language")){}


问:
How can I check for custom ROM?
I want to check in my device whether a custom ROM is installed or not.  I don't want my app to run if there is a custom ROM on any device.  How could I know this through code?</p>

答:
Could someone ask this question as a part of "google's policy supporters"?
Personally, I think that could be happen.
As I know and I can see, there are such of "supporters"!
 - I mean google's policy to keep enforce the exposing the personal user's data and keeps control the market.

Title: How can I check for custom ROM?