问:
Firebase recycleradapter with filter using searchview
I have a project list in firebase database and it is listed in Recyclerview using firebaserecycleradapter. It works fine. I also have a searchview to filter the list based on search query. But the adapter doesn't show the filtered list. The recyclerview goes blank when I type the query in searchview. Could anyone highlight the mistake in my coding and correct me to get the desired result. I have given below the coding.</p>

```<code>public class HomeActivity extends AppCompatActivity {

    private DatabaseReference mDatabase;
    private RecyclerView PList;
    private FirebaseRecyclerAdapter<project, ProjViewHolder> FBRA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        PList = findViewById(R.id.ProjList);
        PList.setHasFixedSize(true);
        PList.setLayoutManager(new LinearLayoutManager(this));
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Projects");
    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerOptions<project> options = new FirebaseRecyclerOptions.Builder<project>()
                .setQuery(mDatabase, project.class).build();
        FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull ProjViewHolder holder, int position, @NonNull project model) {
                pbar.setVisibility(View.GONE);
                String proj_key = getRef(position).getKey();
                holder.prname.setText(model.getPname());
                holder.prlocation.setText(model.getPlocation());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent detactivity = new Intent(HomeActivity.this, InfoActivity.class);
                        detactivity.putExtra("ProjID", proj_key);
                        startActivity(detactivity);
                    }
                });
            }

            @NonNull
            @Override
            public ProjViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
                ProjViewHolder vh = new ProjViewHolder(view);
                return vh;
            }
        };
        PList.setAdapter(FBRA);
        FBRA.startListening();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        final MenuItem search = menu.findItem(R.id.search);
        final SearchView searchView = (SearchView) search.getActionView();
        searchView.setQueryHint("Search Project");
        if (searchView != null) {
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    fbsearch(query);
                    return false;
                }
                @Override
                public boolean onQueryTextChange(String newText) {
                    fbsearch(newText);
                    return false;
                }
            });
        }
        return true;
    }

    private void fbsearch (String searchText){
        String pquery = searchText.toLowerCase();
        Query sQuery = mDatabase.orderByChild("pname").equalTo(pquery);
        FirebaseRecyclerOptions<project> soptions = new FirebaseRecyclerOptions.Builder<project>()
                .setQuery(sQuery, project.class).build();
        FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(soptions) {
            @Override
            protected void onBindViewHolder(@NonNull ProjViewHolder holder, int position, @NonNull project model) {
                pbar.setVisibility(View.GONE);
                String proj_key = getRef(position).getKey();
                holder.prname.setText(model.getPname());
                holder.prlocation.setText(model.getPlocation());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent detactivity = new Intent(HomeActivity.this, InfoActivity.class);
                        detactivity.putExtra("ProjID", proj_key);
                        startActivity(detactivity);
                    }
                });
            }

            @NonNull
            @Override
            public ProjViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
                ProjViewHolder vh = new ProjViewHolder(view);
                return vh;
            }
        };

        PList.setAdapter(FBRA);
        FBRA.startListening();
    }

    public class ProjViewHolder extends RecyclerView.ViewHolder {
        TextView prname, prlocation, prservice, prvalue, practual;
        public ProjViewHolder(@NonNull View itemView) {
            super(itemView);
            prname = itemView.findViewById(R.id.FPName);
            prlocation = itemView.findViewById(R.id.FPLocation);
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        FBRA.stopListening();
    }
}
</code>```

答:
Yes, I was able to identify the problem in the code. As the query is case sensitive, the search list was not shown. I created a new field to store the project name in lower case. Then I made the query to the new field. The corrected code is given below.

```<code>  private void fbsearch (String searchText){
    String pquery = searchText.toLowerCase();
    Query sQuery = mDatabase.orderByChild("pnamelowcase").startAt(pquery).endAt(pquery + "\uf8ff");
    FirebaseRecyclerOptions<project> options = new FirebaseRecyclerOptions.Builder<project>()
            .setQuery(sQuery, project.class).setLifecycleOwner(this).build();
    FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull ProjViewHolder holder, int position, @NonNull project model) {
            String proj_key = getRef(position).getKey();

            holder.prname.setText(model.getPname());
            holder.prlocation.setText(model.getPlocation());
            holder.prservice.setText(model.getPservice());
            holder.prvalue.setText(model.getPvalue());
            holder.practual.setText(model.getPactual());

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent detactivity = new Intent(HomeActivity.this, InfoActivity.class);
                    detactivity.putExtra("ProjID", proj_key);
                    startActivity(detactivity);
                }
            });
        }

        @NonNull
        @Override
        public ProjViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
   //         ProjViewHolder vh = new ProjViewHolder(view);
            return new ProjViewHolder(view);

        }
    };
    PList.setAdapter(FBRA);
}
</code>```

What I noticed that Query only works with startAt and endAt If I change to any other queries such as equalTo, It doesn't work.

I have also noticed one more issue that normal list is not shown once the searchview is closed. If anyone find the issue in my code, please highlight it and tell me why other queries don't work and how to get back the original list once the searchview is closed.

Body:
I have a project list in firebase database and it is listed in Recyclerview using firebaserecycleradapter. It works fine. I also have a searchview to filter the list based on search query. But the adapter doesn't show the filtered list. The recyclerview goes blank when I type the query in searchview. Could anyone highlight the mistake in my coding and correct me to get the desired result. I have given below the coding.

public class HomeActivity extends AppCompatActivity {

    private DatabaseReference mDatabase;
    private RecyclerView PList;
    private FirebaseRecyclerAdapter<project, ProjViewHolder> FBRA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        PList = findViewById(R.id.ProjList);
        PList.setHasFixedSize(true);
        PList.setLayoutManager(new LinearLayoutManager(this));
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Projects");
    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerOptions<project> options = new FirebaseRecyclerOptions.Builder<project>()
                .setQuery(mDatabase, project.class).build();
        FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull ProjViewHolder holder, int position, @NonNull project model) {
                pbar.setVisibility(View.GONE);
                String proj_key = getRef(position).getKey();
                holder.prname.setText(model.getPname());
                holder.prlocation.setText(model.getPlocation());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent detactivity = new Intent(HomeActivity.this, InfoActivity.class);
                        detactivity.putExtra("ProjID", proj_key);
                        startActivity(detactivity);
                    }
                });
            }

            @NonNull
            @Override
            public ProjViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
                ProjViewHolder vh = new ProjViewHolder(view);
                return vh;
            }
        };
        PList.setAdapter(FBRA);
        FBRA.startListening();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        final MenuItem search = menu.findItem(R.id.search);
        final SearchView searchView = (SearchView) search.getActionView();
        searchView.setQueryHint("Search Project");
        if (searchView != null) {
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    fbsearch(query);
                    return false;
                }
                @Override
                public boolean onQueryTextChange(String newText) {
                    fbsearch(newText);
                    return false;
                }
            });
        }
        return true;
    }

    private void fbsearch (String searchText){
        String pquery = searchText.toLowerCase();
        Query sQuery = mDatabase.orderByChild("pname").equalTo(pquery);
        FirebaseRecyclerOptions<project> soptions = new FirebaseRecyclerOptions.Builder<project>()
                .setQuery(sQuery, project.class).build();
        FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(soptions) {
            @Override
            protected void onBindViewHolder(@NonNull ProjViewHolder holder, int position, @NonNull project model) {
                pbar.setVisibility(View.GONE);
                String proj_key = getRef(position).getKey();
                holder.prname.setText(model.getPname());
                holder.prlocation.setText(model.getPlocation());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent detactivity = new Intent(HomeActivity.this, InfoActivity.class);
                        detactivity.putExtra("ProjID", proj_key);
                        startActivity(detactivity);
                    }
                });
            }

            @NonNull
            @Override
            public ProjViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
                ProjViewHolder vh = new ProjViewHolder(view);
                return vh;
            }
        };

        PList.setAdapter(FBRA);
        FBRA.startListening();
    }

    public class ProjViewHolder extends RecyclerView.ViewHolder {
        TextView prname, prlocation, prservice, prvalue, practual;
        public ProjViewHolder(@NonNull View itemView) {
            super(itemView);
            prname = itemView.findViewById(R.id.FPName);
            prlocation = itemView.findViewById(R.id.FPLocation);
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        FBRA.stopListening();
    }
}

Body:
Yes, I was able to identify the problem in the code. As the query is case sensitive, the search list was not shown. I created a new field to store the project name in lower case. Then I made the query to the new field. The corrected code is given below.

  private void fbsearch (String searchText){
    String pquery = searchText.toLowerCase();
    Query sQuery = mDatabase.orderByChild("pnamelowcase").startAt(pquery).endAt(pquery + "\uf8ff");
    FirebaseRecyclerOptions<project> options = new FirebaseRecyclerOptions.Builder<project>()
            .setQuery(sQuery, project.class).setLifecycleOwner(this).build();
    FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull ProjViewHolder holder, int position, @NonNull project model) {
            String proj_key = getRef(position).getKey();

            holder.prname.setText(model.getPname());
            holder.prlocation.setText(model.getPlocation());
            holder.prservice.setText(model.getPservice());
            holder.prvalue.setText(model.getPvalue());
            holder.practual.setText(model.getPactual());

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent detactivity = new Intent(HomeActivity.this, InfoActivity.class);
                    detactivity.putExtra("ProjID", proj_key);
                    startActivity(detactivity);
                }
            });
        }

        @NonNull
        @Override
        public ProjViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
   //         ProjViewHolder vh = new ProjViewHolder(view);
            return new ProjViewHolder(view);

        }
    };
    PList.setAdapter(FBRA);
}

What I noticed that Query only works with startAt and endAt If I change to any other queries such as equalTo, It doesn't work.

I have also noticed one more issue that normal list is not shown once the searchview is closed. If anyone find the issue in my code, please highlight it and tell me why other queries don't work and how to get back the original list once the searchview is closed.


来源: stackexchange

问:
Python pandas if row contains string add to table
I have a spreadsheet that looks as follows:

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

HMI1 controls AZ1

HMI2 controls AZ2

HMI3 controls AZ3

HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

```<code>HMIX | AZX
</code>```

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

```<code>    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])
</code>```

答:
Given df,

```<code>df = pd.DataFrame({'hmi_number':np.arange(1,10),
                  'az1':['x']+[np.nan]*8,
                  'az2':[np.nan]+['x']+[np.nan]*7,
                  'az3':[np.nan]*2+['x']*2+[np.nan]*5,
                  'az4':[np.nan]*4+['x']*2+[np.nan]*3,
                  'az5':[np.nan]*6+['x']*2+[np.nan],
                  'az6':[np.nan]*8+['x']})
</code>```

Try this:

```<code>for hmi, az in (df.set_index('hmi_number')=='x').dot(df.columns[1:]).iteritems():
    print(f'HMI{hmi} controls {az}')
</code>```

Output:

```<code>HMI1 controls az1
HMI2 controls az2
HMI3 controls az3
HMI4 controls az3
HMI5 controls az4
HMI6 controls az4
HMI7 controls az5
HMI8 controls az5
HMI9 controls az6
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a spreadsheet that looks as follows:

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

HMI1 controls AZ1

HMI2 controls AZ2

HMI3 controls AZ3

HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

HMIX | AZX

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])

Body:
Given df,

df = pd.DataFrame({'hmi_number':np.arange(1,10),
                  'az1':['x']+[np.nan]*8,
                  'az2':[np.nan]+['x']+[np.nan]*7,
                  'az3':[np.nan]*2+['x']*2+[np.nan]*5,
                  'az4':[np.nan]*4+['x']*2+[np.nan]*3,
                  'az5':[np.nan]*6+['x']*2+[np.nan],
                  'az6':[np.nan]*8+['x']})

Try this:

for hmi, az in (df.set_index('hmi_number')=='x').dot(df.columns[1:]).iteritems():
    print(f'HMI{hmi} controls {az}')

Output:

HMI1 controls az1
HMI2 controls az2
HMI3 controls az3
HMI4 controls az3
HMI5 controls az4
HMI6 controls az4
HMI7 controls az5
HMI8 controls az5
HMI9 controls az6


问:
I am not able to understand what is been going in the following code...#Method Overloading

class something:

    def __init__(self, pages):
        self.noofpages=pages

    def __add__(self,b):
        return str(self.noofpages + b.noofpages)+'hii'

m=something(10)
n=something(20)
print(m+n)
```

Output :- 30hii

How 10 is going to self.noofpages and 20 to b.noofpages

答:
Yes that's correct

Answer is:

```<code>30hii
</code>```

The magic method add is doing exactly that

Notice that u have method that takes exactly two arguments

```<code>First Argument is self
Second Argument is b
</code>```

So u are actually assign these values here:

```<code>self.noofpages = m = 20
b.noofpages = n = 10
</code>```

Now for the return you get extra string

```<code>return str(self.noofpages + b.noofpages)+'hii' = m + n + "hii"
== 20 + 10 + "hii" == 30hii
</code>```

To better understand the magic method add , just Remove it and Run the Code
u will get Error

Body:
class something:

    def __init__(self, pages):
        self.noofpages=pages

    def __add__(self,b):
        return str(self.noofpages + b.noofpages)+'hii'

m=something(10)
n=something(20)
print(m+n)

Output :- 30hii

How 10 is going to self.noofpages and 20 to b.noofpages

Body:
Yes that's correct

Answer is:

30hii

The magic method add is doing exactly that

Notice that u have method that takes exactly two arguments

First Argument is self
Second Argument is b

So u are actually assign these values here:

self.noofpages = m = 20
b.noofpages = n = 10

Now for the return you get extra string

return str(self.noofpages + b.noofpages)+'hii' = m + n + "hii"
== 20 + 10 + "hii" == 30hii

To better understand the magic method add , just Remove it and Run the Code
u will get Error


问:
google cloud authentication with bearer token via nodejs
My client has a GraphQL API running on Google cloud run.

I have recieved a service account for authentication as well as access to the gcloud command line tool.

When using gcloud command line like so:

```<code>gcloud auth print-identity-token
</code>```

I can generate a token that can be used to make post requests to the api. This works and I can make successful post requests to the api from postman, insomnia and from my nodejs app.

However, when I use JWT authentication with "googleapis" or "google-auth" npm libraries like so :

```<code>var { google } = require('googleapis')

let privatekey = require('./auth/google/service-account.json')

let jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  ['https://www.googleapis.com/auth/cloud-platform']
)

jwtClient.authorize(function(err, _token) {
  if (err) {
    console.log(err)
    return err
  } else {
    console.log('token obj:', _token)
  }
})
</code>```

This outputs a "bearer" token:

```<code>token obj: {
  access_token: 'ya29.c.Ko8BvQcMD5zU-0raojM_u2FZooWMyhB9Ni0Yv2_dsGdjuIDeL1tftPg0O17uFrdtkCuJrupBBBK2IGfUW0HGtgkYk-DZiS1aKyeY9wpXTwvbinGe9sud0k1POA2vEKiGONRqFBSh9-xms3JhZVdCmpBi5EO5aGjkkJeFI_EBry0E12m2DTm0T_7izJTuGQ9hmyw',
  token_type: 'Bearer',
  expiry_date: 1581954138000,
  id_token: undefined,
  refresh_token: 'jwt-placeholder'
}
</code>```

however this bearer token does not work as the one above and always gives an "unauthorised error 401" when making the same requests as with the gcloud command "gcloud auth print-identity-token".

Please help, I am not sure why the first bearer token works but the one generated with JWT does not.

EDIT

I have also tried to get an identity token instead of an access token like so :

```<code>let privatekey = require('./auth/google/service-account.json')

let jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  []
)

jwtClient
  .fetchIdToken('https://my.audience.url')
  .then((res) => console.log('res:', res))
  .catch((err) => console.log('err', err))
</code>```

This prints an identity token, however, using this also just gives a "401 unauthorised" message.

Edit to show how I am calling the endpoint

Just a side note, any of these methods below work with the command line identity token, however when generated via JWT, it returns a 401

Method 1:

```<code> const client = new GraphQLClient(baseUrl, {
        headers: {
          Authorization: 'Bearer ' + _token.id_token
        }
      })
      const query = `{
        ... my graphql query goes here ...
    }`
      client
        .request(query)
        .then((data) => {
          console.log('result from query:', data)
          res.send({ data })
          return 0
        })
        .catch((err) => {
          res.send({ message: 'error ' + err })
          return 0
        })
    }
</code>```

Method 2 (using the "authorized" client I have created with google-auth):

```<code>  const res = await client.request({
    url: url,
    method: 'post',
    data: `{
        My graphQL query goes here ...
    }`
  })
  console.log(res.data)
}
</code>```

答:
You can find the official documentation for node OAuth2

```<code>A complete OAuth2 example:

const {OAuth2Client} = require('google-auth-library');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');

// Download your OAuth2 configuration from the Google
const keys = require('./oauth2.keys.json');

/**
 * Start by acquiring a pre-authenticated oAuth2 client.
 */
async function main() {
  const oAuth2Client = await getAuthenticatedClient();
  // Make a simple request to the People API using our pre-authenticated client. The `request()` method
  // takes an GaxiosOptions object.  Visit https://github.com/JustinBeckwith/gaxios.
  const url = 'https://people.googleapis.com/v1/people/me?personFields=names';
  const res = await oAuth2Client.request({url});
  console.log(res.data);

  // After acquiring an access_token, you may want to check on the audience, expiration,
  // or original scopes requested.  You can do that with the `getTokenInfo` method.
  const tokenInfo = await oAuth2Client.getTokenInfo(
    oAuth2Client.credentials.access_token
  );
  console.log(tokenInfo);
}

/**
 * Create a new OAuth2Client, and go through the OAuth2 content
 * workflow.  Return the full client to the callback.
 */
function getAuthenticatedClient() {
  return new Promise((resolve, reject) => {
    // create an oAuth client to authorize the API call.  Secrets are kept in a `keys.json` file,
    // which should be downloaded from the Google Developers Console.
    const oAuth2Client = new OAuth2Client(
      keys.web.client_id,
      keys.web.client_secret,
      keys.web.redirect_uris[0]
    );

    // Generate the url that will be used for the consent dialog.
    const authorizeUrl = oAuth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: 'https://www.googleapis.com/auth/userinfo.profile',
    });

    // Open an http server to accept the oauth callback. In this simple example, the
    // only request to our webserver is to /oauth2callback?code=<code>
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            // acquire the code from the querystring, and close the web server.
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            const code = qs.get('code');
            console.log(`Code is ${code}`);
            res.end('Authentication successful! Please return to the console.');
            server.destroy();

            // Now that we have the code, use that to acquire tokens.
            const r = await oAuth2Client.getToken(code);
            // Make sure to set the credentials on the OAuth2 client.
            oAuth2Client.setCredentials(r.tokens);
            console.info('Tokens acquired.');
            resolve(oAuth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        open(authorizeUrl, {wait: false}).then(cp => cp.unref());
      });
    destroyer(server);
  });
}

main().catch(console.error);

</code>```

Edit

Another example for cloud run.

```<code>// sample-metadata:
//   title: ID Tokens for Cloud Run
//   description: Requests a Cloud Run URL with an ID Token.
//   usage: node idtokens-cloudrun.js <url> [<target-audience>]

'use strict';

function main(
  url = 'https://service-1234-uc.a.run.app',
  targetAudience = null
) {
  // [START google_auth_idtoken_cloudrun]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const url = 'https://YOUR_CLOUD_RUN_URL.run.app';
  const {GoogleAuth} = require('google-auth-library');
  const auth = new GoogleAuth();

  async function request() {
    if (!targetAudience) {
      // Use the request URL hostname as the target audience for Cloud Run requests
      const {URL} = require('url');
      targetAudience = new URL(url).origin;
    }
    console.info(
      `request Cloud Run ${url} with target audience ${targetAudience}`
    );
    const client = await auth.getIdTokenClient(targetAudience);
    const res = await client.request({url});
    console.info(res.data);
  }

  request().catch(err => {
    console.error(err.message);
    process.exitCode = 1;
  });
  // [END google_auth_idtoken_cloudrun]
}

const args = process.argv.slice(2);
main(...args);
</code>```

Body:
My client has a GraphQL API running on Google cloud run.

I have recieved a service account for authentication as well as access to the gcloud command line tool.

When using gcloud command line like so:

gcloud auth print-identity-token

I can generate a token that can be used to make post requests to the api. This works and I can make successful post requests to the api from postman, insomnia and from my nodejs app.

However, when I use JWT authentication with "googleapis" or "google-auth" npm libraries like so :

var { google } = require('googleapis')

let privatekey = require('./auth/google/service-account.json')

let jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  ['https://www.googleapis.com/auth/cloud-platform']
)

jwtClient.authorize(function(err, _token) {
  if (err) {
    console.log(err)
    return err
  } else {
    console.log('token obj:', _token)
  }
})

This outputs a "bearer" token:

token obj: {
  access_token: 'ya29.c.Ko8BvQcMD5zU-0raojM_u2FZooWMyhB9Ni0Yv2_dsGdjuIDeL1tftPg0O17uFrdtkCuJrupBBBK2IGfUW0HGtgkYk-DZiS1aKyeY9wpXTwvbinGe9sud0k1POA2vEKiGONRqFBSh9-xms3JhZVdCmpBi5EO5aGjkkJeFI_EBry0E12m2DTm0T_7izJTuGQ9hmyw',
  token_type: 'Bearer',
  expiry_date: 1581954138000,
  id_token: undefined,
  refresh_token: 'jwt-placeholder'
}

however this bearer token does not work as the one above and always gives an "unauthorised error 401" when making the same requests as with the gcloud command "gcloud auth print-identity-token".

Please help, I am not sure why the first bearer token works but the one generated with JWT does not.

EDIT

I have also tried to get an identity token instead of an access token like so :

let privatekey = require('./auth/google/service-account.json')

let jwtClient = new google.auth.JWT(
  privatekey.client_email,
  null,
  privatekey.private_key,
  []
)

jwtClient
  .fetchIdToken('https://my.audience.url')
  .then((res) => console.log('res:', res))
  .catch((err) => console.log('err', err))

This prints an identity token, however, using this also just gives a "401 unauthorised" message.

Edit to show how I am calling the endpoint

Just a side note, any of these methods below work with the command line identity token, however when generated via JWT, it returns a 401

Method 1:

 const client = new GraphQLClient(baseUrl, {
        headers: {
          Authorization: 'Bearer ' + _token.id_token
        }
      })
      const query = `{
        ... my graphql query goes here ...
    }`
      client
        .request(query)
        .then((data) => {
          console.log('result from query:', data)
          res.send({ data })
          return 0
        })
        .catch((err) => {
          res.send({ message: 'error ' + err })
          return 0
        })
    }

Method 2 (using the "authorized" client I have created with google-auth):

  const res = await client.request({
    url: url,
    method: 'post',
    data: `{
        My graphQL query goes here ...
    }`
  })
  console.log(res.data)
}

Body:
You can find the official documentation for node OAuth2

A complete OAuth2 example:

const {OAuth2Client} = require('google-auth-library');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');

// Download your OAuth2 configuration from the Google
const keys = require('./oauth2.keys.json');

/**
 * Start by acquiring a pre-authenticated oAuth2 client.
 */
async function main() {
  const oAuth2Client = await getAuthenticatedClient();
  // Make a simple request to the People API using our pre-authenticated client. The `request()` method
  // takes an GaxiosOptions object.  Visit https://github.com/JustinBeckwith/gaxios.
  const url = 'https://people.googleapis.com/v1/people/me?personFields=names';
  const res = await oAuth2Client.request({url});
  console.log(res.data);

  // After acquiring an access_token, you may want to check on the audience, expiration,
  // or original scopes requested.  You can do that with the `getTokenInfo` method.
  const tokenInfo = await oAuth2Client.getTokenInfo(
    oAuth2Client.credentials.access_token
  );
  console.log(tokenInfo);
}

/**
 * Create a new OAuth2Client, and go through the OAuth2 content
 * workflow.  Return the full client to the callback.
 */
function getAuthenticatedClient() {
  return new Promise((resolve, reject) => {
    // create an oAuth client to authorize the API call.  Secrets are kept in a `keys.json` file,
    // which should be downloaded from the Google Developers Console.
    const oAuth2Client = new OAuth2Client(
      keys.web.client_id,
      keys.web.client_secret,
      keys.web.redirect_uris[0]
    );

    // Generate the url that will be used for the consent dialog.
    const authorizeUrl = oAuth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: 'https://www.googleapis.com/auth/userinfo.profile',
    });

    // Open an http server to accept the oauth callback. In this simple example, the
    // only request to our webserver is to /oauth2callback?code=<code>
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            // acquire the code from the querystring, and close the web server.
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            const code = qs.get('code');
            console.log(`Code is ${code}`);
            res.end('Authentication successful! Please return to the console.');
            server.destroy();

            // Now that we have the code, use that to acquire tokens.
            const r = await oAuth2Client.getToken(code);
            // Make sure to set the credentials on the OAuth2 client.
            oAuth2Client.setCredentials(r.tokens);
            console.info('Tokens acquired.');
            resolve(oAuth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        open(authorizeUrl, {wait: false}).then(cp => cp.unref());
      });
    destroyer(server);
  });
}

main().catch(console.error);

Edit

Another example for cloud run.

// sample-metadata:
//   title: ID Tokens for Cloud Run
//   description: Requests a Cloud Run URL with an ID Token.
//   usage: node idtokens-cloudrun.js <url> [<target-audience>]

'use strict';

function main(
  url = 'https://service-1234-uc.a.run.app',
  targetAudience = null
) {
  // [START google_auth_idtoken_cloudrun]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const url = 'https://YOUR_CLOUD_RUN_URL.run.app';
  const {GoogleAuth} = require('google-auth-library');
  const auth = new GoogleAuth();

  async function request() {
    if (!targetAudience) {
      // Use the request URL hostname as the target audience for Cloud Run requests
      const {URL} = require('url');
      targetAudience = new URL(url).origin;
    }
    console.info(
      `request Cloud Run ${url} with target audience ${targetAudience}`
    );
    const client = await auth.getIdTokenClient(targetAudience);
    const res = await client.request({url});
    console.info(res.data);
  }

  request().catch(err => {
    console.error(err.message);
    process.exitCode = 1;
  });
  // [END google_auth_idtoken_cloudrun]
}

const args = process.argv.slice(2);
main(...args);


问:
Submitting data to different tabs using google sheet script editor
In my spreadsheet script editor, I have the below codes:

Code.gs

```<code>function doGet() {
    return HtmlService.createTemplateFromFile('checkForm.html')
}

function doPost1(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var checkForm = ss.getSheetByName("checkForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    var startTime = newRow[1];
    var endTime = newRow[2];
    var cal = CalendarApp.getCalendarById("ID");
    var allEvents = cal.getEvents(new Date(startTime), new Date(endTime));
    if (allEvents.length > 0) {
    return HtmlService.createTemplateFromFile('calendarAgenda.html')
    }else {
    return HtmlService.createTemplateFromFile('bookingForm.html')
    };

  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

function doPost2(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var bookForm = ss.getSheetByName("bookForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    return ContentService
    .createTextOutput(JSON.stringify('Successfully received. Thank you!'))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

</code>```

checkForm.html

```<code><!DOCTYPE html>
<body>
<form name="class1Check" id="class1Check" action="ScriptURL" target="_self" method="POST">
Start Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="Start Date & Time">
<br><br>
End Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="End Date & Time">
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>
<script>
function postData(form) {
  google.script.run.withSuccessHandler(postData).doPost1(e);
}
</script>
</body>
</html>
</code>```

bookingForm.html

```<code><!DOCTYPE html>
<body>
<form name="class1Booking" id="class1Booking" action="ScriptURL" target="_self" method="POST">
<inputs> ..
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>
<script>
function postData(form) {
  google.script.run.withSuccessHandler(postData).doPost2(e);
}
</script>
</body>
</html>
</code>```

The goGet function returns the "checkForm.html" page that when submitted is supposed to run the doPost1 function to send the data to tab "checkForm" in the spreadsheet and then returns the second page "bookingForm.html" that when submitted is supposed to run the doPost2 function to send the data to tab "bookForm" and then returns a certain text output

When I submit the check form, I receive the error "Script function not found: doPost" and I think I might have some issues with google.script.run that I tried to modify several times with no luck. Any help and thanks in advance

答:
Forget about the doPost().  Try something like this.

HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <style>#msg{display:none;}</style>
  </head>
  <body>
    <form>
      <!--><inputs type="text" name="name1">-->
      <button type="button"  value="Submit" onclick="processForm(this.parentNode);" />
      </form>
 <div id="msg"></div>
 <script>
   $(function(){
     //You can get stuff from the server after the dom has loaded.  I know it takes some time but it's a simple way to intialize.  Personally for my own sutff Id rather do this that use templated html
   });

  function processFormC(form) {
    //input validation
    google.script.run
    .withSuccessHandler(function(obj){
      $('#msg').css("display","block");
      $('#msg').html(obj.msg);
    })
    .processFormS(form);
  }
</script>
  </body>
</html>
</code>```

GS:

```<code>function processFormS(obj) {
  //obj.name1...
  return {msg:'Got it.'}
}

function doGet() {
    return HtmlService.createHtmlOutputFromFile('whatever file name')
}
</code>```

And personally I prefer putting all of the javascript and css in the same file because it's easier to find later on.  Yes I know it can get large but again that's my choice it doesn't have to be your choice.

Body:
In my spreadsheet script editor, I have the below codes:

Code.gs

function doGet() {
    return HtmlService.createTemplateFromFile('checkForm.html')
}

function doPost1(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var checkForm = ss.getSheetByName("checkForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    var startTime = newRow[1];
    var endTime = newRow[2];
    var cal = CalendarApp.getCalendarById("ID");
    var allEvents = cal.getEvents(new Date(startTime), new Date(endTime));
    if (allEvents.length > 0) {
    return HtmlService.createTemplateFromFile('calendarAgenda.html')
    }else {
    return HtmlService.createTemplateFromFile('bookingForm.html')
    };

  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

function doPost2(e) {

  Logger.log(JSON.stringify(e))
  if (!e || !e.parameter) {
    return;
  }
  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);
  var scriptProp = PropertiesService.getScriptProperties();

  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var bookForm = ss.getSheetByName("bookForm");
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    return ContentService
    .createTextOutput(JSON.stringify('Successfully received. Thank you!'))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

checkForm.html

<!DOCTYPE html>

<form name="class1Check" id="class1Check" action="ScriptURL" target="_self" method="POST">
Start Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="Start Date & Time">

End Date & Time
<input class="w3-input w3-border" type="datetime-local" required name="End Date & Time">
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>

bookingForm.html

<!DOCTYPE html>

<form name="class1Booking" id="class1Booking" action="ScriptURL" target="_self" method="POST">
<inputs> ..
<button type="submit" onclick="google.script.run.doPost1(this.parentNode)">Check</button>
</form>

The goGet function returns the "checkForm.html" page that when submitted is supposed to run the doPost1 function to send the data to tab "checkForm" in the spreadsheet and then returns the second page "bookingForm.html" that when submitted is supposed to run the doPost2 function to send the data to tab "bookForm" and then returns a certain text output

When I submit the check form, I receive the error "Script function not found: doPost" and I think I might have some issues with google.script.run that I tried to modify several times with no luck. Any help and thanks in advance

Body:
Forget about the doPost().  Try something like this.

HTML:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <style>#msg{display:none;}</style>
  </head>
  <body>
    <form>
      <!--><inputs type="text" name="name1">-->
      <button type="button"  value="Submit" onclick="processForm(this.parentNode);" />
      </form>
 <div id="msg"></div>
 <script>
   $(function(){
     //You can get stuff from the server after the dom has loaded.  I know it takes some time but it's a simple way to intialize.  Personally for my own sutff Id rather do this that use templated html
   });

  function processFormC(form) {
    //input validation
    google.script.run
    .withSuccessHandler(function(obj){
      $('#msg').css("display","block");
      $('#msg').html(obj.msg);
    })
    .processFormS(form);
  }
</script>
  </body>
</html>

GS:

function processFormS(obj) {
  //obj.name1...
  return {msg:'Got it.'}
}

function doGet() {
    return HtmlService.createHtmlOutputFromFile('whatever file name')
}

And personally I prefer putting all of the javascript and css in the same file because it's easier to find later on.  Yes I know it can get large but again that's my choice it doesn't have to be your choice.


问:
Using hasNext() Scanner method to only allow a set of X inputs
How can I use the scanner hasNext() method to ensure that the user only selects a value between 1 and 20 and then use that value as a String to return in fillSpot variable?  The code below is lacking a way to check if the input is between 1 and 20.  I am also receiving the error code fillSpot cannot be resolved to a variable on the final return line. Any help would be much appreciated!

```<code>public String giveInput() {

    Scanner in = new Scanner(System.in);
int space;

do {
        System.out.println("Enter numerical value between 1 and 20");
        while (in.hasNext()) {
            String fillSpot = in.nextLine();
            System.out.printf("\"%s\" is not a valid input.\n", fillSpot);
        }
        space = in.nextInt();
    } while (space < 1 || space < 20);

    return fillSpot;
}
</code>```

答:
I would suggest something like this :

```<code>public String giveInput() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter numerical value between 1 and 20");
        int input=in.nextInt();
        if(input<1 || input>20) {
            System.out.println(input + " is not a valid input.");
        }else {
            // do your work
            System.out.println("Valid Input");
        }
return Integer.toString(input);

}
</code>```

Let me know if it helps.

Body:
How can I use the scanner hasNext() method to ensure that the user only selects a value between 1 and 20 and then use that value as a String to return in fillSpot variable?  The code below is lacking a way to check if the input is between 1 and 20.  I am also receiving the error code fillSpot cannot be resolved to a variable on the final return line. Any help would be much appreciated!

public String giveInput() {

    Scanner in = new Scanner(System.in);
int space;

do {
        System.out.println("Enter numerical value between 1 and 20");
        while (in.hasNext()) {
            String fillSpot = in.nextLine();
            System.out.printf("\"%s\" is not a valid input.\n", fillSpot);
        }
        space = in.nextInt();
    } while (space < 1 || space < 20);

    return fillSpot;
}

Body:
I would suggest something like this :

public String giveInput() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter numerical value between 1 and 20");
        int input=in.nextInt();
        if(input<1 || input>20) {
            System.out.println(input + " is not a valid input.");
        }else {
            // do your work
            System.out.println("Valid Input");
        }
return Integer.toString(input);

}

Let me know if it helps.


问:
Sorting of list by matching the 'input' lists in Python
I have a (probably quite simple) problem I cannot figure out in Python.

Say I have a list
X1 = [1,2,3]
with the corresponding list
Y1 = [5,6,7]
and a list
X2 = [2,1,3]
with corresponding list
Y2 = [8,9,10]
where X1 and X2 contain the same values but in different order. How can I match the order of X2 to that of X1, while the X2 Y2 pairs remain intact? The answer should be then Y2 = [9,8,10].

Thank you in advance!

答:
```<code>n = len(X1)
inds = range(n)
d = {X2[i_]:Y2[i_] for i_ in inds}
nY2 = [d[X1[i_]] for i_ in inds]
</code>```


问:
Javascript array of functions: Pass each function as parameter to another function
I have a usercase where I get an array of functions from backend something like:

```<code>var arr = [A(){}, B(){}, C(){}];
</code>```

Now I need a way to execute them such that each function in the array is passed as a parameter to another function in the array.

```<code>A(B(C()));
</code>```

答:
You can use Array.prototype.reduce to execute consecutive calls to a list of functions.

Update: As ASDFGerte suggests, you can use reduceRight instead of reduce to reverse the function execution flow.

const text = 'That will be 3.50';
const funcList = [extractNumber, parseNumeric, formatCurrency];

console.log('Parsed:', chainFunctions(funcList, text));
console.log('Parsed:', chainFunctionsReverse(funcList.reverse(), text));

function chainFunctions(funcList, startingValue) {
  return funcList.reduce((result, func) => func(result), startingValue);
}

function chainFunctionsReverse(funcList, startingValue) {
  return funcList.reduceRight((result, func) => func(result), startingValue);
}

function extractNumber(str) {
  return str.match(/\b(\d+(\.\d+)?\b)/)[1];
}

function parseNumeric(numStr) {
  return parseFloat(numStr);
}

function formatCurrency(num) {
  return `$${num.toFixed(2)}`;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code>```

Body:
I have a usercase where I get an array of functions from backend something like:

var arr = [A(){}, B(){}, C(){}];

Now I need a way to execute them such that each function in the array is passed as a parameter to another function in the array.

A(B(C()));

Body:
You can use Array.prototype.reduce to execute consecutive calls to a list of functions.

Update: As ASDFGerte suggests, you can use reduceRight instead of reduce to reverse the function execution flow.

const text = 'That will be 3.50';
const funcList = [extractNumber, parseNumeric, formatCurrency];

console.log('Parsed:', chainFunctions(funcList, text));
console.log('Parsed:', chainFunctionsReverse(funcList.reverse(), text));

function chainFunctions(funcList, startingValue) {
  return funcList.reduce((result, func) => func(result), startingValue);
}

function chainFunctionsReverse(funcList, startingValue) {
  return funcList.reduceRight((result, func) => func(result), startingValue);
}

function extractNumber(str) {
  return str.match(/\b(\d+(\.\d+)?\b)/)[1];
}

function parseNumeric(numStr) {
  return parseFloat(numStr);
}

function formatCurrency(num) {
  return `$${num.toFixed(2)}`;
}

.as-console-wrapper { top: 0; max-height: 100% !important; }


问:
dynamically insert mat-checkbox
I want to dynamically insert a <mat-checkbox> element into a component.
and I inserted two <mat-checkbox> elements. one inserted statically (i.e into the template file directly).

and the other one inserted dynamically, and contains a <mat-checkbox> and another normal checkbox <input type="checkbox" />

the first one (the statically inserted one) rendered without any problem.

also the normal input inserted dynamically without any problem.

but the <mat-checkbox> that dynamically inserted didn't render as expected.

component.html:

```<code><mat-checkbox> checkbox (static) </mat-checkbox>

<div [innerHTML] = "test2">

</code>```

component.ts:

```<code> this.test= `
     <mat-checkbox>mat-checkbox</mat-checkbox><br />
     <input type="checkbox" /> normal checkbox
  `

  this.test2 = this.sanitizer.bypassSecurityTrustHtml(this.test);

</code>```

I created a Reproduction on stackblitz:

https://stackblitz.com/edit/angular-hsjevo

also I need to create checkboxes from categories, and append some extra spaces before each sub-category

i.e:

category

sub category

sub of sub category

category2

each category or sub-category is <mat-checkbox value="$id"> $title

答:
innerHTML property of div tag can only parse and render regular HTML elements like input, etc. To dynamically create Angular components like mat-checkbox, you need to inform Angular about those components. Let's see how this can be done below:

We need a placeholder in the AppComponent template where we can add the mat-checkbox component dynamically. We can use <ng-template> tag as a placeholder in this case.

app.component.html

```<code><mat-checkbox>mat-checkbox (static)</mat-checkbox> <hr />

dynamic angular component:<br/>
<ng-template #placeholder></ng-template>
</code>```

In AppComponent typescript file, we need to refer this placeholder and append the mat-checkbox component. Find the inline comments for explanation.

app.component.ts

```<code>import {
  Component,
  ComponentFactoryResolver,
  OnInit,
  Renderer2,
  ViewChild,
  ViewContainerRef
} from '@angular/core';
import {MatCheckbox} from '@angular/material';

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  // Get reference to the ng-template placeholder tag
  @ViewChild('placeholder', {read: ViewContainerRef, static: true}) placeholder: ViewContainerRef;

  constructor(
    private resolver: ComponentFactoryResolver,
    private renderer: Renderer2) {}

  ngOnInit() {
    this.createComponent();
  }

  createComponent() {
    // creating the mat-checkbox tag body content
    let content = this.renderer.createText(' mat-checkbox (dynamic)');
    // clear any previously appended element or component
    this.placeholder.clear();
    // resolve the MatCheckbox component and get the factory class to create the component dynamically
    let factory = this.resolver.resolveComponentFactory(MatCheckbox);
    // create the component and append to the placeholder in the template
    let ref = this.placeholder.createComponent(factory);
    // set the mat-checkbox body content
    (ref.location.nativeElement as HTMLElement).appendChild(content);
  }
}
</code>```

In order for the above code to work, we need to inform Angular that we would be expecting to resolve the MatCheckbox component at runtime. Make the following changes in app.module.ts.

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { MatCheckboxModule, MatCheckbox } from '@angular/material';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, MatCheckboxModule ],
  declarations: [ AppComponent, HelloComponent ],
  // Inform Angular about those components which will be created dynamically by including them in entryComponents field
  entryComponents: [ MatCheckbox ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

Now you should be able to see the mat-checkbox created dynamically at runtime.
View the complete example here (https://stackblitz.com/edit/angular-e7vhue)

For more information, refer this article.

Hope this helped your query.

Title: dynamically insert mat-checkbox

Body:
I want to dynamically insert a <mat-checkbox> element into a component.
and I inserted two <mat-checkbox> elements. one inserted statically (i.e into the template file directly).

and the other one inserted dynamically, and contains a <mat-checkbox> and another normal checkbox <input type="checkbox" />

the first one (the statically inserted one) rendered without any problem.

also the normal input inserted dynamically without any problem.

but the <mat-checkbox> that dynamically inserted didn't render as expected.

component.html:

<mat-checkbox> checkbox (static) </mat-checkbox>

component.ts:

 this.test= `
     <mat-checkbox>mat-checkbox</mat-checkbox>

     <input type="checkbox" /> normal checkbox
  `

  this.test2 = this.sanitizer.bypassSecurityTrustHtml(this.test);

I created a Reproduction on stackblitz:

https://stackblitz.com/edit/angular-hsjevo

also I need to create checkboxes from categories, and append some extra spaces before each sub-category

i.e:

category

sub category

sub of sub category

category2

each category or sub-category is <mat-checkbox value="$id"> $title

Body:
innerHTML property of div tag can only parse and render regular HTML elements like input, etc. To dynamically create Angular components like mat-checkbox, you need to inform Angular about those components. Let's see how this can be done below:

We need a placeholder in the AppComponent template where we can add the mat-checkbox component dynamically. We can use <ng-template> tag as a placeholder in this case.

app.component.html

<mat-checkbox>mat-checkbox (static)</mat-checkbox> <hr />

dynamic angular component:<br/>
<ng-template #placeholder></ng-template>

In AppComponent typescript file, we need to refer this placeholder and append the mat-checkbox component. Find the inline comments for explanation.

app.component.ts

import {
  Component,
  ComponentFactoryResolver,
  OnInit,
  Renderer2,
  ViewChild,
  ViewContainerRef
} from '@angular/core';
import {MatCheckbox} from '@angular/material';

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  // Get reference to the ng-template placeholder tag
  @ViewChild('placeholder', {read: ViewContainerRef, static: true}) placeholder: ViewContainerRef;

  constructor(
    private resolver: ComponentFactoryResolver,
    private renderer: Renderer2) {}

  ngOnInit() {
    this.createComponent();
  }

  createComponent() {
    // creating the mat-checkbox tag body content
    let content = this.renderer.createText(' mat-checkbox (dynamic)');
    // clear any previously appended element or component
    this.placeholder.clear();
    // resolve the MatCheckbox component and get the factory class to create the component dynamically
    let factory = this.resolver.resolveComponentFactory(MatCheckbox);
    // create the component and append to the placeholder in the template
    let ref = this.placeholder.createComponent(factory);
    // set the mat-checkbox body content
    (ref.location.nativeElement as HTMLElement).appendChild(content);
  }
}

In order for the above code to work, we need to inform Angular that we would be expecting to resolve the MatCheckbox component at runtime. Make the following changes in app.module.ts.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { MatCheckboxModule, MatCheckbox } from '@angular/material';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, MatCheckboxModule ],
  declarations: [ AppComponent, HelloComponent ],
  // Inform Angular about those components which will be created dynamically by including them in entryComponents field
  entryComponents: [ MatCheckbox ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Now you should be able to see the mat-checkbox created dynamically at runtime.
View the complete example here (https://stackblitz.com/edit/angular-e7vhue)

For more information, refer this article.

Hope this helped your query.


问:
Generate Separate Font Files
Is it possible to generate separate font files from a original file. Meaning I have different font styles for bold & italic? Any help would be greatly appreciated.</p>

答:
"Possible"? Yes, but it's not quite so straightforward as that.

Font manipulation tools exist that can read an original file and perform font-wide manipulations such as emboldening & slanting ("italic"), and you can then generate the derived font styles. So, it is technically correct to say that it is "possible". And in fact, many operating systems employ something like this on-the-fly (at rendering time) to produce "fake" bold and italic fonts where there is no real instance. However:

1) Simple mathematical emboldening and slanting of base ("Regular") designs often introduces undesirable artifacts that require clean-up. Performing that clean-up assumes some level of familiarity with font design principles and tooling, as well as the original font design itself. People involved in this area of work spend years studying and practicing how to do this well.

2) Many fonts that you use every day are provided to you under license, and in some cases that license does not allow you to distribute derivative works of the original. So if you decide to go this route, be certain that the base font's license allows manipulation and distribution of said derivatives (unless you only care about it for personal use).

Title: Generate Separate Font Files


问:
how do i store the value of max(variable)?
when i run it and after pressing the second 'n' it doesn't satisfy the logic and the reason is max returns 0(check the last printf) so how can i store the new value in max?

```<code>//A GAME FOR GUESSING YOUR NUMBER BY USING THE BINARY SEARCH ALGORITHM
#include <stdio.h>
int main()
{

int min=1;
int max,z,i;
char ans;

printf("\t\t\t***GUESSING GAME***\n");
printf("Let put a rang, the min number is 1, the max is? \n");
scanf("%d",&max);//--> 15

z=(min+max)/2; //the average

while(i<max)
{
 dis:
 printf("The number is %d? (y/n)\n",z); //--> z =( min(1) + max(15) ) / 2 = 8
 scanf("%s",&ans);

 if(ans=='n')
 {

     printf("Is %d too high? (y/n)\n",z);
     scanf("%s",&ans);
     //new range [1,8]
     if(ans=='y')
     {
         z=(min+z)/2;  //--> z =( min(1) + z(8) ) / 2 = 4
         goto dis;
     }
</code>```

THIS "

```<code>     //new range [8,15]
     if(ans=='n')
     {
         z=(z+max)/2; //it should be z =( z(8) + max(15) ) / 2 = 11
         goto dis;
     }
</code>```

"

```<code> }
 if(ans=='y')
 {
     printf("\\BINGO/");
</code>```

the value of max will be 0

```<code>    // printf("max %d z %d",max,z);

 }
 i++;
}

}
</code>```

答:
The program has undefined behavior because in the condition of the loop

```<code>while(i<max)
{
</code>```

there is used an uninitialized variable i.

This call

```<code> scanf("%s",&ans);
</code>```

also invokes undefined behavior because there is passed address of one character while the call of scanf tries to read a string. For example if the user enters 'n' scanf write to the addressed memory two characters 'n' and '\0'.

Instead use

```<code>scanf(" %c",&ans);
</code>```

Pay attention to the blank before the conversion specifier %c.

And do not use the goto statement. Instead use a loop.

Body:
when i run it and after pressing the second 'n' it doesn't satisfy the logic and the reason is max returns 0(check the last printf) so how can i store the new value in max?

//A GAME FOR GUESSING YOUR NUMBER BY USING THE BINARY SEARCH ALGORITHM
#include <stdio.h>
int main()
{

int min=1;
int max,z,i;
char ans;

printf("\t\t\t***GUESSING GAME***\n");
printf("Let put a rang, the min number is 1, the max is? \n");
scanf("%d",&max);//--> 15

z=(min+max)/2; //the average

while(i<max)
{
 dis:
 printf("The number is %d? (y/n)\n",z); //--> z =( min(1) + max(15) ) / 2 = 8
 scanf("%s",&ans);

 if(ans=='n')
 {

     printf("Is %d too high? (y/n)\n",z);
     scanf("%s",&ans);
     //new range [1,8]
     if(ans=='y')
     {
         z=(min+z)/2;  //--> z =( min(1) + z(8) ) / 2 = 4
         goto dis;
     }

THIS "

     //new range [8,15]
     if(ans=='n')
     {
         z=(z+max)/2; //it should be z =( z(8) + max(15) ) / 2 = 11
         goto dis;
     }

"

 }
 if(ans=='y')
 {
     printf("\\BINGO/");

the value of max will be 0

    // printf("max %d z %d",max,z);

 }
 i++;
}

}

Body:
The program has undefined behavior because in the condition of the loop

while(i<max)
{

there is used an uninitialized variable i.

This call

 scanf("%s",&ans);

also invokes undefined behavior because there is passed address of one character while the call of scanf tries to read a string. For example if the user enters 'n' scanf write to the addressed memory two characters 'n' and '\0'.

Instead use

scanf(" %c",&ans);

Pay attention to the blank before the conversion specifier %c.

And do not use the goto statement. Instead use a loop.


问:
SparkUI not showing Tab (Jobs, Stages, Storage, Environment,...) when run in standalone mode
I'm running spark master through the following command:

./sbin/start-master.sh

After that I went to http://localhost:8080, and I saw the following page.

I was expecting to see the tab with Jobs, Environments, ... like the following

Could someone help me to understand where the problem is?

Do I need extra configuration?

Thanks

Giuseppe

答: I think what you are looking for is the SparkUI, which you should first create a SparkContext. For example, you could run pyspark if you have that installed, and when it starts correctly, you would see a sparkUI spawned at port 4040 or 4041...</p>


问:
which http verb/best practice to update an entity without payload to send?
purpose is really simple:
i want to modify entities but i have no data to send in payload, as request is really easy.
In fact, my url is something like :

```<code>/v1/{customerId}/release/old/subscriptions
</code>```

==> the code update entity Subscription for customerId asked.

the question is:
    @GetMapping : ok but is not RESTFULL as entity is modified!
    @PutMapping : ok but no payload to send !
    @PostMapping : ok but no payload to send !

what is best practice ?

i want to do some

答:
which http verb/best practice to update an entity without payload to send?

The general rule is that you use POST unless the semantics of your message match a more specific method.

PUT with an empty payload is a request to make the current representation of the resource zero bytes long.  Think "delete the contents of the file".

PATCH requests are supposed to include a patch-document in the payload; and so the meaning would be whatever an empty document of that particular media type means.  I don't think I've ever heard of a case where an empty patch document does something interesting.

POST requests are intended for any semantic that isn't worth standardizing.

Body:
purpose is really simple:
i want to modify entities but i have no data to send in payload, as request is really easy.
In fact, my url is something like :

/v1/{customerId}/release/old/subscriptions

==> the code update entity Subscription for customerId asked.

the question is:
    @GetMapping : ok but is not RESTFULL as entity is modified!
    @PutMapping : ok but no payload to send !
    @PostMapping : ok but no payload to send !

what is best practice ?

i want to do some


问:
Send a text message Using FCM and Twilio
I want to send a text message to a particular user's number stored in Firebase Database. For that I have Used FCM and Twilio. My problem is that I got following errors. (Follwed tutorial from  https://angularfirebase.com/lessons/sms-texting-with-twilio/)

errrrror { Error: getaddrinfo ENOTFOUND api.twilio.com api.twilio.com:443
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
  code: 'ENOTFOUND',
  errno: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'api.twilio.com',
  host: 'api.twilio.com',
  port: 443 }```

答: Your country block twilio ,you can use proxy before you send a request to twilio.in english you can deploy your project on a external server in another country </p>


问:
Why the property 'classList' cannot be read?
I am trying to add and remove a class depending on whether a variable is equal to 0. Here is my code:

```<code>import { LitElement, html } from 'lit-element';

class SelectCounter extends LitElement {
static get properties() {
    return {
        numPassengers: {type: Number},
    };
}

constructor() {
    super();
    this.numPassengers = 0;
    this.disableState();
}

createRenderRoot() {
    return this;
}

disableState() {
    this.btn = document.querySelector('.minus');
    if (this.numPassengers === 0) {
        this.btn.classList.add('counter__btn--disable');
    }
}

render(){
    return html`
        <div class="counter">
            <a class="counter__btn minus" href="#"></a>
            <span class="counter__label">${this.numPassengers}</span>
            <a class="counter__btn" href="#"></a>
        </div>
    `;
}
}
customElements.define('select-counter', SelectCounter);
</code>```

I've tried it in several ways but I don't understand why it happens. Any idea?

答:
You're calling disableState() in the constructor, when the DOM of the component is not ready yet so this:

this.btn = document.querySelector('.minus');
```
<p>is <code>null</code>.</p>
<p>If you move that logic in <code>firstUpdated()</code> then it should work.</p>
<pre class="lang-js prettyprint-override"><code>firstUpdated() {
    disableState();
}

disableState() {
    // Also, consider querySelecting inside this.renderRoot
    // to avoid picking elements with the same class in
    // other parts of the document
    this.btn = this.renderRoot.querySelector('.minus');
    // ...
}
</code>```

Note that you can do the same thing in a more declarative way, without the need to select the element:

render() {
    return html`

            ${this.numPassengers}

    `;
}
```
<p>or by using <code>lit-html</code>'s <code>classMap</code> directive:</p>
<pre class="lang-js prettyprint-override"><code>import {classMap} from 'lit-html/directives/class-map.js';

// ...

render() {
    return html`
        <div class="counter">

            <span class="counter__label">${this.numPassengers}</span>

        </div>
    `;
}
</code>```

Body:
I am trying to add and remove a class depending on whether a variable is equal to 0. Here is my code:

import { LitElement, html } from 'lit-element';

class SelectCounter extends LitElement {
static get properties() {
    return {
        numPassengers: {type: Number},
    };
}

constructor() {
    super();
    this.numPassengers = 0;
    this.disableState();
}

createRenderRoot() {
    return this;
}

disableState() {
    this.btn = document.querySelector('.minus');
    if (this.numPassengers === 0) {
        this.btn.classList.add('counter__btn--disable');
    }
}

render(){
    return html`

            ${this.numPassengers}

    `;
}
}
customElements.define('select-counter', SelectCounter);

I've tried it in several ways but I don't understand why it happens. Any idea?

Body:
You're calling disableState() in the constructor, when the DOM of the component is not ready yet so this:

this.btn = document.querySelector('.minus');

is null.

If you move that logic in firstUpdated() then it should work.

firstUpdated() {
    disableState();
}

disableState() {
    // Also, consider querySelecting inside this.renderRoot
    // to avoid picking elements with the same class in
    // other parts of the document
    this.btn = this.renderRoot.querySelector('.minus');
    // ...
}

Note that you can do the same thing in a more declarative way, without the need to select the element:

render() {
    return html`
        <div class="counter">
            <a class="counter__btn minus ${this.numPassengers === 0 ? 'counter__btn--disable' : ''}" href="#"></a>
            <span class="counter__label">${this.numPassengers}</span>
            <a class="counter__btn" href="#"></a>
        </div>
    `;
}

or by using lit-html's classMap directive:

import {classMap} from 'lit-html/directives/class-map.js';

// ...

render() {
    return html`
        <div class="counter">
            <a class=${classMap({
                counter__btn: true,
                minus: true,
                'counter__btn--disable': this.numPassengers === 0,
            })} href="#"></a>
            <span class="counter__label">${this.numPassengers}</span>
            <a class="counter__btn" href="#"></a>
        </div>
    `;
}


问:
Using rdmsr/rdpmc for branch prediction accuracy
I am trying to understand how does a branch prediction unit work in a CPU.

I have used papi and also linux's perf-events but both of them do not give accurate results (for my case).

This is my code:

```<code>void func(int* arr, int sequence_len){
  for(int i = 0; i < sequence_len; i++){
      // region starts
      if(arr[i]){
          do_sth();
      }
      // region ends
  }
}
</code>```

My array consists of 0's and 1's. It has a pattern with a size of sequence_len. For example, if my size is 8, then it has a pattern of 0 1 0 1 0 0 1 1 or something like that.

Trial 1:

I am trying to understand how CPU predicts those branches. So, I have used papi and set up performance counter for branch predictions mispredicted (I know that it also counts indirect branches).

```<code>int func(){
  papi_read(r1);
  for(){
    //... same as above
  }
  papi_read(r2);
  return r2-r1;
}

int main(){
   init_papi();
   for(int i = 0; i < 10; i++)
     res[i] = func();

   print(res[i]);
}

</code>```

What I see as an output is that (for sequence length of 200)

100 #iter1
40  #iter2
10  #iter3
3
0
0
#...
```

<p>So, at first, the CPU blindly predicts the sequence, only success half of the time. In the next iterations, the CPU can predict better and better. After some amount of iterations, the CPU can guess that perfectly.</p>

<p><strong>Trial 2</strong></p>

<p>I would like to see, at which array index does the CPU misprediction.</p>

```int* func(){
  int* results;
  for(){
    papi_read(r1);
    if(arr[i])
        do_sth();
    papi_read(r2);
    res[i] = r2-r1;
  }
  return res;
}

int main(){
   init_papi();
   for(int i = 0; i < 10; i++)
     res[i] = func();

   print(res[i]);
}
```

<p>Expected result:</p>

<pre class="lang-sh prettyprint-override"><code>#1st iteration, 0 means no mispred, 1 means mispred
1 0 0 1 1 0 0 0 1 1 0... # total of 200 results
Mispred: 100/200
#2nd iteration
0 0 0 0 1 0 0 0 1 0 0... # total of 200 results
Mispred: 40/200 # it learned from previous iteration
#3rd iteration
0 0 0 0 0 0 0 0 1 0 0... # total of 200 results
Mispred: 10/200 # continues to learn
#...
</code>```

Received result:

#1st iteration
1 0 0 1 1 0 0 0 1 1 0... # total of 200 results
Mispred: 100/200
#2nd iteration
1 0 0 0 1 1 0 1 0 0 0... # total of 200 results
Mispred: 100/200 # it DID NOT learn from previous iteration
#3rd iteration
0 1 0 1 0 1 0 1 1 0 0... # total of 200 results
Mispred: 100/200 # NO LEARNING
#...
```

My observation

When I measure the misprediction outside of the for loop, I can see that CPU learns from its mispredictions. However, when I try to measure single branch instructions misprediction, then the CPU either cannot learn, or I am measuring it wrongly.

My explanation

I am giving 200 as a sequence length. The CPU has one small branch predictor, like 2-3 bit saturated counter in Intels, and one big global branch predictor. When I measure outside of the loop, I introduce less noise to the measurement. By less noise, I mean the papi calls.

Think about this: outside of the loop measurement

global history is: papi_start, branch_outcome1, branch_outcome2, branch_outcome3, ..., papi_end, papi_start (2nd loop of main iteration), branch_outcome1, ...

So, the branch predictor somehow finds the pattern in the same branch.

However, if I try to measure single branch instruction then the global history is:
papi_start, branchoutcome1, papiend, papistart, branchoutcome2, papiend...

So, I am introducing more and more branches to global history. I assume the global history cannot hold many branch entries and therefore, it cannot find any correlation/pattern in the desired if statement(branch).

As a result

I need to measure a single branch prediction outcome. I know that the CPU can learn the 200 pattern if I don't introduce papi too much. I have looked at the papi calls and I have seen lots of for loops, if conditions.

That is why I need better measurement. I have tried linux perf-event but it makes ioctl calls, which is a system call and I pollute the global history with system calls, and therefore, not a good measurement.

I have read that rdpmc and rdmsr instructions and I assume that since they are only instructions, I will not pollute the global history, and I can measure single branch instruction at a time.

However, I have no clue about how I can do that. I have AMD 3600 CPU. These are the links that I found online but I couldn't figure out how to do that. In addition to that, am I missing something?

Intel rdpmc

AMD Performance manual

答:
You have assumed that the PAPI and/or perf_events code has a relatively light footprint.  This is incorrect.  If you change the performance counter event to something like "instructions retired" or "CPU cycles not halted", you will be able to see how much overhead this operation contains in your software environment.  The details will depend on your OS version, but I expect the overhead to be in the hundreds of instructions/thousands of cycles because of the kernel crossing required to read the counters in perf_events (which is used by PAPI).  The code path will certainly include its own branches.

If your kernel supports "User-Mode RDPMC" (CR4.PCE=1), you can read a performance counter with a single instruction.  Examples are available in https://github.com/jdmccalpin/low-overhead-timers.

Even when limiting the measurement code to the native RDPMC instruction (and the surrounding code to save the results), measurements are disruptive to the processor pipeline.  RDPMC is a microcoded instruction.  On the Ryzen core, the instruction executes 20 micro-ops and has a throughput of one instruction per 20 cycles. (Ref: https://www.agner.org/optimize/instruction_tables.pdf)

Any measurements at fine granularities are challenging because the out-of-order capabilities of modern processors interact with the user code in ways that are poorly documented and difficult to anticipate.  More notes on this topic (also relevant to AMD processors) are at http://sites.utexas.edu/jdm4372/2018/07/23/comments-on-timing-short-code-sections-on-intel-processors/

Body:
I am trying to understand how does a branch prediction unit work in a CPU.

I have used papi and also linux's perf-events but both of them do not give accurate results (for my case).

This is my code:

void func(int* arr, int sequence_len){
  for(int i = 0; i < sequence_len; i++){
      // region starts
      if(arr[i]){
          do_sth();
      }
      // region ends
  }
}

My array consists of 0's and 1's. It has a pattern with a size of sequence_len. For example, if my size is 8, then it has a pattern of 0 1 0 1 0 0 1 1 or something like that.

Trial 1:

I am trying to understand how CPU predicts those branches. So, I have used papi and set up performance counter for branch predictions mispredicted (I know that it also counts indirect branches).

int func(){
  papi_read(r1);
  for(){
    //... same as above
  }
  papi_read(r2);
  return r2-r1;
}

int main(){
   init_papi();
   for(int i = 0; i < 10; i++)
     res[i] = func();

   print(res[i]);
}

What I see as an output is that (for sequence length of 200)

100 #iter1
40  #iter2
10  #iter3
3
0
0
#...

So, at first, the CPU blindly predicts the sequence, only success half of the time. In the next iterations, the CPU can predict better and better. After some amount of iterations, the CPU can guess that perfectly.

Trial 2

I would like to see, at which array index does the CPU misprediction.

int* func(){
  int* results;
  for(){
    papi_read(r1);
    if(arr[i])
        do_sth();
    papi_read(r2);
    res[i] = r2-r1;
  }
  return res;
}

int main(){
   init_papi();
   for(int i = 0; i < 10; i++)
     res[i] = func();

   print(res[i]);
}

Expected result:

#1st iteration, 0 means no mispred, 1 means mispred
1 0 0 1 1 0 0 0 1 1 0... # total of 200 results
Mispred: 100/200
#2nd iteration
0 0 0 0 1 0 0 0 1 0 0... # total of 200 results
Mispred: 40/200 # it learned from previous iteration
#3rd iteration
0 0 0 0 0 0 0 0 1 0 0... # total of 200 results
Mispred: 10/200 # continues to learn
#...

Received result:

#1st iteration
1 0 0 1 1 0 0 0 1 1 0... # total of 200 results
Mispred: 100/200
#2nd iteration
1 0 0 0 1 1 0 1 0 0 0... # total of 200 results
Mispred: 100/200 # it DID NOT learn from previous iteration
#3rd iteration
0 1 0 1 0 1 0 1 1 0 0... # total of 200 results
Mispred: 100/200 # NO LEARNING
#...

My observation

When I measure the misprediction outside of the for loop, I can see that CPU learns from its mispredictions. However, when I try to measure single branch instructions misprediction, then the CPU either cannot learn, or I am measuring it wrongly.

My explanation

I am giving 200 as a sequence length. The CPU has one small branch predictor, like 2-3 bit saturated counter in Intels, and one big global branch predictor. When I measure outside of the loop, I introduce less noise to the measurement. By less noise, I mean the papi calls.

Think about this: outside of the loop measurement

global history is: papi_start, branch_outcome1, branch_outcome2, branch_outcome3, ..., papi_end, papi_start (2nd loop of main iteration), branch_outcome1, ...

So, the branch predictor somehow finds the pattern in the same branch.

However, if I try to measure single branch instruction then the global history is:
papi_start, branchoutcome1, papiend, papistart, branchoutcome2, papiend...

So, I am introducing more and more branches to global history. I assume the global history cannot hold many branch entries and therefore, it cannot find any correlation/pattern in the desired if statement(branch).

As a result

I need to measure a single branch prediction outcome. I know that the CPU can learn the 200 pattern if I don't introduce papi too much. I have looked at the papi calls and I have seen lots of for loops, if conditions.

That is why I need better measurement. I have tried linux perf-event but it makes ioctl calls, which is a system call and I pollute the global history with system calls, and therefore, not a good measurement.

I have read that rdpmc and rdmsr instructions and I assume that since they are only instructions, I will not pollute the global history, and I can measure single branch instruction at a time.

However, I have no clue about how I can do that. I have AMD 3600 CPU. These are the links that I found online but I couldn't figure out how to do that. In addition to that, am I missing something?

Intel rdpmc

AMD Performance manual


问:
Segfault after deleting elements from vector
I'm currently working on a project, more precisely a tangram game.
I have a problem with a segfault and I don't understand why.

Given that I have a whole project, I will try to simplify the problem :
I have a GameManager class that contains in particular a Menu object (and other things, but I don't think that is important. The gameManager is used to inititialize this object and manage it.
The Menu contains a vector of Button(each button has a lambda to perform an action when the user click on it).

```<code>std::vector<std::unique_ptr<Button>> buttons;
</code>```

To illustrate how it works I will take an example : if the user clicks on the "Load" button, the gameManager delete the current Buttons contained in the menu and add new buttons in that menu.

```<code>void GameManager::initMainMenuButtons() {
...
menu -> addButton(std::unique_ptr<Button>(new Button(x1, y1, x2, y2, "Create",
    [this]{
        std::cout << "Create level" << std::endl;
        menu->clear()
        initCreateLevelButtons();
        actionManager->setMenu(menu);
    }
)));
...
}
</code>```

In that code sample, I have a method initMainMenuButtons that adds several buttons in the menu , like "Load" or "Quit".
When the user clicks on "Create", I want to change the interface (adding and deleting buttons). So, to delete the buttons, i call the method clear()

```<code>void Menu::clear() {
  buttons.clear();
  decorationPieces.clear(); // not interesting
}
</code>```

I'm using unique_ptr, thus, I don't have to delete the buttons mannualy.
So far, no problem : the vector of buttons seems to be empty (size is 0).
Next, the method initCreateLevelButtons() is called. This method is very similar to initMainMenu : it adds buttons in the menu, nothing else. During this call, the buttons seems to be correctly added in the vector, I printed the content of the vector at the end and the vector contains the correct buttons.

And there, the problem appears : after the call of initCreateLevelButtons(), there is a segfault when i want to use the menu, so, actionManager->setMenu(menu); doesn't work. I tried to print the menu std::cout << menu << std::endl, and test if this pointer is nullptr, but it doesn't work either. I don't understand why the menu seems to be correct at the last line of initCreateLevelButtons() and becomes invalid just after.
If I doesn't clear the vector of buttons (the menu->clear instruction), the program works, but, the last buttons are still here).

I tried to use raw pointers and I notices that the program is able to clear the vector as long as the buttons are not deleted (If I add a loop to delete the buttons, the problem arises), so, I conclued that the probleme is the buttons deleting. I don't understanf why, I'm stuck.
I don't know if I explained it weel, because, as I have already said, the code is part of a whole project, it's hard to introduce classes without introduce other things.
if you want details or the complete code of methods, I can provide them.

答:
menu sustains lifetime of some button

button sustain lifetime of lambda

when you click button lambda clears menu

menu destructor clears button, button clears lambda

lambda continues execution when it in fact has been already destroyed -> undefined behavior ends with a crash

Now question is: Do you own Button class?

If yes then the easiest way to fix it, is to invoke copy of lambda in the button.

Body:
I'm currently working on a project, more precisely a tangram game.
I have a problem with a segfault and I don't understand why.

Given that I have a whole project, I will try to simplify the problem :
I have a GameManager class that contains in particular a Menu object (and other things, but I don't think that is important. The gameManager is used to inititialize this object and manage it.
The Menu contains a vector of Button(each button has a lambda to perform an action when the user click on it).

std::vector<std::unique_ptr<Button>> buttons;

To illustrate how it works I will take an example : if the user clicks on the "Load" button, the gameManager delete the current Buttons contained in the menu and add new buttons in that menu.

void GameManager::initMainMenuButtons() {
...
menu -> addButton(std::unique_ptr<Button>(new Button(x1, y1, x2, y2, "Create",
    [this]{
        std::cout << "Create level" << std::endl;
        menu->clear()
        initCreateLevelButtons();
        actionManager->setMenu(menu);
    }
)));
...
}

In that code sample, I have a method initMainMenuButtons that adds several buttons in the menu , like "Load" or "Quit".
When the user clicks on "Create", I want to change the interface (adding and deleting buttons). So, to delete the buttons, i call the method clear()

void Menu::clear() {
  buttons.clear();
  decorationPieces.clear(); // not interesting
}

I'm using unique_ptr, thus, I don't have to delete the buttons mannualy.
So far, no problem : the vector of buttons seems to be empty (size is 0).
Next, the method initCreateLevelButtons() is called. This method is very similar to initMainMenu : it adds buttons in the menu, nothing else. During this call, the buttons seems to be correctly added in the vector, I printed the content of the vector at the end and the vector contains the correct buttons.

And there, the problem appears : after the call of initCreateLevelButtons(), there is a segfault when i want to use the menu, so, actionManager->setMenu(menu); doesn't work. I tried to print the menu std::cout << menu << std::endl, and test if this pointer is nullptr, but it doesn't work either. I don't understand why the menu seems to be correct at the last line of initCreateLevelButtons() and becomes invalid just after.
If I doesn't clear the vector of buttons (the menu->clear instruction), the program works, but, the last buttons are still here).

I tried to use raw pointers and I notices that the program is able to clear the vector as long as the buttons are not deleted (If I add a loop to delete the buttons, the problem arises), so, I conclued that the probleme is the buttons deleting. I don't understanf why, I'm stuck.
I don't know if I explained it weel, because, as I have already said, the code is part of a whole project, it's hard to introduce classes without introduce other things.
if you want details or the complete code of methods, I can provide them.


问:
Can you do this using jquery?
Is it possible to do this from within a class?

```<code>   $("#" + field).click(this.validate);
</code>```

So basically I want to pass a function of the object that should be executed whenever something is clicked. Also, if there are more than 1 instances of this object, then the correct instance (i.e the one which runs this code for the given field) should be executed.

答:
From inside a class you're typically better off using the .find function.</p>

```<code>var child = this.find('.someChildClass');
var child2 = this.find('#someChildId');
</code>```

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Title: Can you do this using jquery?

Body:
Is it possible to do this from within a class?

   $("#" + field).click(this.validate);

So basically I want to pass a function of the object that should be executed whenever something is clicked. Also, if there are more than 1 instances of this object, then the correct instance (i.e the one which runs this code for the given field) should be executed.

Body:
From inside a class you're typically better off using the .find function.

var child = this.find('.someChildClass');
var child2 = this.find('#someChildId');

OwnerDisplayName: justin


问:
Should I use Static class for Database connectivity in C#.net?
I have a class which contain all the database connection activities. What i want to know is should i make this class as static then i can call anywhere without creating it.
but the application runs in different pcs in same network in same time.

OR ELSE

should i create a normal class that can be use in other classes by inheriting it?

答:
Apart from decluttering  there is a good reason why the class that makes database connection should be static. Usually in a application, one db connection is all you need. The way its usually designed is, you have a static class with a static method. On first call the static method checks if the connection object is null. If yes it creates a new connection and returns this. For future calls the method will just return this connection.
This also makes it simpler to make sure you close connection because now all you need is another static method in this class that closes this connection.
Hope that helps. </p>

ContentLicense: CC BY-SA 3.0


问:
Specified Class is not a Driver. Can't add MySQL Connector/J 8.0 to Netbeans 8.0
I can't get MySQL 8.0 jdbc driver set up in Netbeans. Can anyone help?

My Netbeans 8.0 IDE was set up using an older version of the MySQL JDBC Driver, 5.1.23. I upgraded MySQL to 8.0 and am trying to setup a new JDBC Driver in Netbeans because the old driver isn't able to connect to the new DB (*see note at end).

These are the steps I followed.

Step 1: I removed the old mysql driver jar file from D:\Program Files\NetBeans 8.0\ide\modules\ext and copied the new mysql-connector-java-8.0.12.jar file and restarted the IDE.

Step 2: In the Services tab under Databases I right clicked on Drivers and New Driver...

Step 3: In the dialog box that shows up I click the Add... button and I select the new driver jar D:\Program Files\NetBeans 8.0\ide\modules\ext\mysql-connector-java-8.0.12.jar

At this point the Driver Class automatically gets populated with com.mysql.jdbc.Driver and I can't hit the OK button because there's a message Specified class is not a driver (java.sql.Driver)

I tried changing it to com.mysql.cj.jdbc.Driver but it still gave the same message.

I decompiled com.mysql.jdbc.Driver from the jar file and got this:

```<code>package com.mysql.jdbc;

import java.io.PrintStream;
import java.sql.SQLException;

public class Driver
  extends com.mysql.cj.jdbc.Driver
{
  public Driver()
    throws SQLException
  {}

  static
  {
    System.err.println("Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.");
  }
}
</code>```

and for com.mysql.cj.jdbc.Driver I got this

```<code>package com.mysql.cj.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Driver
  extends NonRegisteringDriver
  implements java.sql.Driver
{
  public Driver()
    throws SQLException
  {}

  static
  {
    try
    {
      DriverManager.registerDriver(new Driver());
    }
    catch (SQLException E)
    {
      throw new RuntimeException("Can't register driver!");
    }
  }
}
</code>```

So com.mysql.jdbc.Driver extends com.mysql.cj.jdbc.Driver which implements java.sql.Driver so I don't know what the error is all about.

Anyone have any idea how to resolve this? I tried a 6.0 driver and got the same error. The 5 driver works but can't connect to DB.

Side note. with the old 5 driver I was getting ClassCastException when trying to connect to database. BigInt can't be Cast to Long. When I changed the driver in the application to the new driver that problem went away.

答:
Use Connection Properties button and add a property with field name serverTimezone and value UTC.

This should work if error was caused by timezone issue.

Body:
I can't get MySQL 8.0 jdbc driver set up in Netbeans. Can anyone help?

My Netbeans 8.0 IDE was set up using an older version of the MySQL JDBC Driver, 5.1.23. I upgraded MySQL to 8.0 and am trying to setup a new JDBC Driver in Netbeans because the old driver isn't able to connect to the new DB (*see note at end).

These are the steps I followed.

Step 1: I removed the old mysql driver jar file from D:\Program Files\NetBeans 8.0\ide\modules\ext and copied the new mysql-connector-java-8.0.12.jar file and restarted the IDE.

Step 2: In the Services tab under Databases I right clicked on Drivers and New Driver...

Step 3: In the dialog box that shows up I click the Add... button and I select the new driver jar D:\Program Files\NetBeans 8.0\ide\modules\ext\mysql-connector-java-8.0.12.jar

At this point the Driver Class automatically gets populated with com.mysql.jdbc.Driver and I can't hit the OK button because there's a message Specified class is not a driver (java.sql.Driver)

I tried changing it to com.mysql.cj.jdbc.Driver but it still gave the same message.

I decompiled com.mysql.jdbc.Driver from the jar file and got this:

package com.mysql.jdbc;

import java.io.PrintStream;
import java.sql.SQLException;

public class Driver
  extends com.mysql.cj.jdbc.Driver
{
  public Driver()
    throws SQLException
  {}

  static
  {
    System.err.println("Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.");
  }
}

and for com.mysql.cj.jdbc.Driver I got this

package com.mysql.cj.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Driver
  extends NonRegisteringDriver
  implements java.sql.Driver
{
  public Driver()
    throws SQLException
  {}

  static
  {
    try
    {
      DriverManager.registerDriver(new Driver());
    }
    catch (SQLException E)
    {
      throw new RuntimeException("Can't register driver!");
    }
  }
}

So com.mysql.jdbc.Driver extends com.mysql.cj.jdbc.Driver which implements java.sql.Driver so I don't know what the error is all about.

Anyone have any idea how to resolve this? I tried a 6.0 driver and got the same error. The 5 driver works but can't connect to DB.

Side note. with the old 5 driver I was getting ClassCastException when trying to connect to database. BigInt can't be Cast to Long. When I changed the driver in the application to the new driver that problem went away.