问:
NodeJS query processing results design pattern avoid nested then statements
I am writing an application in NodeJS10 and Mongoose5. I am writing a custom server-side pagination function. I want to run the pagination in a controller for separation of concerns and reusability.

I have a query to get data and return it in a then() response handler. I am then calling the custom pagination function inside the then() handler. This works, but I am concerned about the "nested" then/catch patterns. I think this might be messy especially if there is any additional processing required on the data before returning the response.

Here is the "nested" structure. How can I improve this to make it no longer nested and more readable while still catching all possible errors and returning the response correctly? Note that this works just fine, it's just the design pattern is messy and I want to avoid the "nested" then() statements if possible.

```<code>router.get('/:id', (req, res, next) => {
  const origin = 'routes/items.js GET /:id';

  const id = req.params.id;

  items.find({
    _id: id
  }).then(data => {

    uiCtrl.pagination(data, req.query).then((result) => {
      res.status(200).send(result);
    }).catch((error) => {
      console.error(`pagination failed ${error}`);
      res.status(500).send(`pagination failed ${error}`);
    });

  }).catch((error) => {
    console.log(`${origin} ${error}`);
    res.status(404).send('Not found');
  });

});
</code>```

Here is the custom async function being called inside the query result above.

```<code>const uiCtrl = {};

uiCtrl.pagination = async (data, query) => {

  // pagination logic here
  return data;
}

module.exports = uiCtrl;
</code>```

答:
Here is a rewrite using normal async/await stuff:

```<code>var data, results;
try {
   data = await items.find({_id:id}).toArray();
}
catch (err) {
   console.log(`${origin} ${error}`);
   res.status(404).send('Not found');
}
try {
   results = await uiCtrl.pagination(data, req.query);
}
catch (err) {
   console.error(`pagination failed ${error}`);
   res.status(500).send(`pagination failed ${error}`);
}
</code>```

It should be noted that given the fact that I know nothing more of your code than what I can see, there are probably some other things you can do that will make the code better to read and easier to use (ie rejecting a promise and doing something meaningful with it instead of throwing exceptions).  You would also need to have all this code wrapped in an async method so you can the await keyword.

EDIT

For completion's sake given the full code now I would start by rewriting it something like this:

```<code>router.get('/:id', async (req, res, next) => {
  const origin = 'routes/items.js GET /:id';

  const id = req.params.id;

  var itemResults, paginationResults;
  try {
     itemResults = await items.find({_id: id}).toArray();
  }
  catch (err) {
     console.log(`${origin} ${error}`);
     res.status(404).send('Not found');
  }
  try {
     paginationResults = await uiCtrl.pagination(data, req.query);
     res.status(200).send(result);
  }
  catch (err) {
     console.error(`pagination failed ${error}`);
     res.status(500).send(`pagination failed ${error}`);
  }
});
</code>```

One other thing I would do as a sort of optimization or housekeeping thing would be to move the error catching into a single catch block and parse the error out there to make things more concise.

Also including this as it talks about something called callback hell which is very relevant to the information you are asking about.

http://callbackhell.com/

Body:
I am writing an application in NodeJS10 and Mongoose5. I am writing a custom server-side pagination function. I want to run the pagination in a controller for separation of concerns and reusability.

I have a query to get data and return it in a then() response handler. I am then calling the custom pagination function inside the then() handler. This works, but I am concerned about the "nested" then/catch patterns. I think this might be messy especially if there is any additional processing required on the data before returning the response.

Here is the "nested" structure. How can I improve this to make it no longer nested and more readable while still catching all possible errors and returning the response correctly? Note that this works just fine, it's just the design pattern is messy and I want to avoid the "nested" then() statements if possible.

router.get('/:id', (req, res, next) => {
  const origin = 'routes/items.js GET /:id';

  const id = req.params.id;

  items.find({
    _id: id
  }).then(data => {

    uiCtrl.pagination(data, req.query).then((result) => {
      res.status(200).send(result);
    }).catch((error) => {
      console.error(`pagination failed ${error}`);
      res.status(500).send(`pagination failed ${error}`);
    });

  }).catch((error) => {
    console.log(`${origin} ${error}`);
    res.status(404).send('Not found');
  });

});

Here is the custom async function being called inside the query result above.

const uiCtrl = {};

uiCtrl.pagination = async (data, query) => {

  // pagination logic here
  return data;
}

module.exports = uiCtrl;

Body:
Here is a rewrite using normal async/await stuff:

var data, results;
try {
   data = await items.find({_id:id}).toArray();
}
catch (err) {
   console.log(`${origin} ${error}`);
   res.status(404).send('Not found');
}
try {
   results = await uiCtrl.pagination(data, req.query);
}
catch (err) {
   console.error(`pagination failed ${error}`);
   res.status(500).send(`pagination failed ${error}`);
}

It should be noted that given the fact that I know nothing more of your code than what I can see, there are probably some other things you can do that will make the code better to read and easier to use (ie rejecting a promise and doing something meaningful with it instead of throwing exceptions).  You would also need to have all this code wrapped in an async method so you can the await keyword.

EDIT

For completion's sake given the full code now I would start by rewriting it something like this:

router.get('/:id', async (req, res, next) => {
  const origin = 'routes/items.js GET /:id';

  const id = req.params.id;

  var itemResults, paginationResults;
  try {
     itemResults = await items.find({_id: id}).toArray();
  }
  catch (err) {
     console.log(`${origin} ${error}`);
     res.status(404).send('Not found');
  }
  try {
     paginationResults = await uiCtrl.pagination(data, req.query);
     res.status(200).send(result);
  }
  catch (err) {
     console.error(`pagination failed ${error}`);
     res.status(500).send(`pagination failed ${error}`);
  }
});

One other thing I would do as a sort of optimization or housekeeping thing would be to move the error catching into a single catch block and parse the error out there to make things more concise.

Also including this as it talks about something called callback hell which is very relevant to the information you are asking about.

http://callbackhell.com/


来源: stackexchange

问:
select with index on DataTable?
After I get DataTable from sqlAdapter I'm closing connection.
If I preform SELECT from this DataTable, does the select use the index
I created in the DB?

what code do I need to write for using the index?

答: See this: Do ADO.Net DataTables have indexes?</p>

ContentLicense: CC BY-SA 3.0

Title: select with index on DataTable?


问:
Why aren't Web Workers used more?
Web Workers are a technology that I brush up against from time to time, whether as the subject of blog post, or a mention in a presentation.

During a more recent presentation I attended, the speaker said about web workers:

I'm not really sure why they aren't used more.

I realised, having thought about it, that for a technology with such obvious benefits &  use cases, web workers seem to have had a fairly slow, or narrow adoption.

Is there some inherent issue with Web workers that makes them less useful? Am I just looking in the wrong places for examples of their use? Or is it that Javascript programmers in general are not particularly used to creating multi-threaded applications.

答:
Since most answers to this question are a few years old, here's my perspective on the current state of things, as of May 2019.

Web Workers are now supported in commonly-targeted browsers, and I'd argue that browser support is no longer a significant obstacle to their use. Despite that, Web Workers still aren't commonly used, and most web developers I interact with don't use them.

Certainly not every website needs to do enough heavy lifting to justify a Web Worker; many websites don't need JavaScript at all. So, I wouldn't expect to see Web Workers in a majority of websites realistically.

But "heavy lifting" is not the only factor in justifying a Web Worker – another is ease of use. Web Workers are a significant challenge to use in many contexts. Note that the Web Worker API involves splitting your build outputs into separate files, or generating that code (e.g. with Data URIs or fn.toString()) at runtime. Web developers use many different build systems, and often have many dependencies in their projects. Configuring the project to create these additional build artifacts with the right dependencies can be difficult, or at least it varies with the build system you have.

Furthermore, this work almost invariably has to be done by each web developer, for each individual project. You could expect much higher Web Worker adoption if WWs were commonly used inside the popular libraries and frameworks that developers already depend on. But they aren't (for API-related reasons, if I had to guess), even for libraries that do a significant amount of synchronous work. And as long as using the main thread is the default, easiest thing to do, that's what most developers will continue to do.

Title: Why aren't Web Workers used more?

ContentLicense: CC BY-SA 4.0


问:
PostgreSQL + Rails citext
I am trying to move to heroku which uses PostgreSQL 8.4 which has a citext column type which is nice since the app was written for MySQL.

Is there any way to use :citext with rails (so that if the migrations are run on MySQL the citext would just use string/text?

I found this ticket, but it seems like it isn't going to be a part of rails for a while:
https://rails.lighthouseapp.com/projects/8994/tickets/3174-add-support-for-postgresql-citext-column-type

答:
As others have mentioned, Rails now has native support for the citext column type (since 4.2).

To migrate existing columns you need to enable the citext extension and then change_column. Change colum is non-reversible so you'll need separate up and down methods.

class ConvertUserNameToCaseInsensitive < ActiveRecord::Migration[6.0]
  def up
    enable_extension 'citext' # only the first migration you add a citext column
    change_column :user, :name, :citext
  end

  def down
    change_column :user, :name, :string
    disable_extension 'citext' # reverse order, only the first migration you add a citext column (this will be the last time you remove one in a rollback)
  end
end
```

<p>Disable extension is only required the last time you remove a citext column when rolling back so rather than add ugly comments it might be better to have separate migrations and explain the reason why in your commit message:</p>

<pre class="lang-rb prettyprint-override"><code># migration 1.rb
class EnableCitext < ActiveRecord::Migration[6.0]
  def change
    enable_extension 'citext'
  end
end

# migration 2.rb
class ConvertUserNameToCaseInsensitive < ActiveRecord::Migration[6.0]
  def up
    change_column :user, :name, :citext
  end

  def down
    change_column :user, :name, :string
  end
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: PostgreSQL + Rails citext

Body:
As others have mentioned, Rails now has native support for the citext column type (since 4.2).

To migrate existing columns you need to enable the citext extension and then change_column. Change colum is non-reversible so you'll need separate up and down methods.

class ConvertUserNameToCaseInsensitive < ActiveRecord::Migration[6.0]
  def up
    enable_extension 'citext' # only the first migration you add a citext column
    change_column :user, :name, :citext
  end

  def down
    change_column :user, :name, :string
    disable_extension 'citext' # reverse order, only the first migration you add a citext column (this will be the last time you remove one in a rollback)
  end
end

Disable extension is only required the last time you remove a citext column when rolling back so rather than add ugly comments it might be better to have separate migrations and explain the reason why in your commit message:

# migration 1.rb
class EnableCitext < ActiveRecord::Migration[6.0]
  def change
    enable_extension 'citext'
  end
end

# migration 2.rb
class ConvertUserNameToCaseInsensitive < ActiveRecord::Migration[6.0]
  def up
    change_column :user, :name, :citext
  end

  def down
    change_column :user, :name, :string
  end
end


问:
Standard method or best practices for foreign keys when exporting and merging databases
Is there a best practice when merging two databases (with identical schema) that have tables with foreign keys? I'm looking for a way with MySQL (or any standard SQL language feature) to export the rows with a place holder for the foreign key and, upon import, insert the proper newly assigned value once the row which defines the foreign key (via auto-increment) has assigned one.

I can do this via programming outside of SQL but am curious if there is a better approach using only SQL or MySQL-specific methods.

If programming is the only option, is there a recommended method (export as JSON)? My attempts work but are not elegant and I end up writing all the import methods myself which is prone to errors and bugs.

答:
I don't know of any native methods, but my general approach when dealing with such situations (if I understand your question correctly - clone data that would have 2 tables, joined by a foreign key for a second table that happens to be an identity column on first table), is as follows:

NOTE: this ONLY works if the first table (the one with identity column that serves as a foreign key, ALSO has a unique set of columns that is not the identity column). This is called a "natural key" (hat/tip @rd_nielsen). Hopefully, you already have one in the form of a unique index on first table that isn't the unique key.

Example: Table "t1" has columns id1, c1, c2, c3, c4 and table "t2" has id2, id1, d1, d2, d3 where id1 is an identity column in t1 and a foreign key in t2; and c1+c2 is a natural key in t1.

The technique relies on building a temporary transition table that replaces the foreign key in second table to be first table's natural key, instead of first table's identity column.

Find unique combo of columns (c1+c2 in this example) in first table which is the natural key.

Run a join query, that joins first table's natural key's columns, with the second table; via the foreign key; into a temp table.

```<code>-- Sybase syntax.
SELECT t1.c1, t1.c2, t2.d1, t2.d2, t2.d3
INTO   tempdb..t2_lookupable
WHERE  t1.id1 = t2.id1

-- While at it, let's build the migratable columns (everything except identity) for t1
SELECT t1.c1, t1.c2, t1.c3, t1.c4
INTO   tempdb..t1_lookupable
</code>```

Clone the data from tempdb..t1_lookupable and tempdb..t2_lookupable tables to the target as needed.

This can involve doing merges between your two databases worth of data, or anything else that is needed to be done. Could be bcp out/in, could be some other method - depends on what you do.

Populate new t1 table from data in tempdb..t1_lookupable on target

```<code>-- Could be a BCP
SELECT c1, c2, c3, c4   -- id1 will get autopopulated, being an identity column
FROM   tempdb..t1_lookupable
</code>```

Now, the tricky part - populate the new t2 table, from a combo of new t1 table, and t2_lookupable table, by finding correct new "id1" value by joining those 2 tables on c1, c2 unique key set:

```<code>SELECT t1.id1, t2t.d1, t2t.d2, t2t.d3
INTO
FROM   t1, tempdb..t2_lookupable t2t
WHERE  t1.c1 = t2t.c1
 AND   t1.c1 = t2t.c2
</code>```

Body:
I don't know of any native methods, but my general approach when dealing with such situations (if I understand your question correctly - clone data that would have 2 tables, joined by a foreign key for a second table that happens to be an identity column on first table), is as follows:

NOTE: this ONLY works if the first table (the one with identity column that serves as a foreign key, ALSO has a unique set of columns that is not the identity column). This is called a "natural key" (hat/tip @rd_nielsen). Hopefully, you already have one in the form of a unique index on first table that isn't the unique key.

Example: Table "t1" has columns id1, c1, c2, c3, c4 and table "t2" has id2, id1, d1, d2, d3 where id1 is an identity column in t1 and a foreign key in t2; and c1+c2 is a natural key in t1.

The technique relies on building a temporary transition table that replaces the foreign key in second table to be first table's natural key, instead of first table's identity column.

Find unique combo of columns (c1+c2 in this example) in first table which is the natural key.

Run a join query, that joins first table's natural key's columns, with the second table; via the foreign key; into a temp table.

-- Sybase syntax.
SELECT t1.c1, t1.c2, t2.d1, t2.d2, t2.d3
INTO   tempdb..t2_lookupable
WHERE  t1.id1 = t2.id1

-- While at it, let's build the migratable columns (everything except identity) for t1
SELECT t1.c1, t1.c2, t1.c3, t1.c4
INTO   tempdb..t1_lookupable

Clone the data from tempdb..t1_lookupable and tempdb..t2_lookupable tables to the target as needed.

This can involve doing merges between your two databases worth of data, or anything else that is needed to be done. Could be bcp out/in, could be some other method - depends on what you do.

Populate new t1 table from data in tempdb..t1_lookupable on target

-- Could be a BCP
SELECT c1, c2, c3, c4   -- id1 will get autopopulated, being an identity column
FROM   tempdb..t1_lookupable

Now, the tricky part - populate the new t2 table, from a combo of new t1 table, and t2_lookupable table, by finding correct new "id1" value by joining those 2 tables on c1, c2 unique key set:

SELECT t1.id1, t2t.d1, t2t.d2, t2t.d3
INTO
FROM   t1, tempdb..t2_lookupable t2t
WHERE  t1.c1 = t2t.c1
 AND   t1.c1 = t2t.c2


问:
How to create a table that loops over data in Postgres
I want to create a table that returns the top 10 aggregate cons_name over a given week, that repeats every day.

So for 5/29/2019 it will pull the top 10 cons_name by their sum dating back to 5/22/2019.

Then, for 5/28/2019, the top 10 cons_name by their sum back to 5/21/2019.

A table of top 10 dating back 7 days all the way to 2018-12-01.

I can make the simple code dating back 7 days but, I have tried Windows to no avail.

```<code>SELECT cons_name,
       pricedate,
       sum(shadow)
FROM spp.rtbinds
WHERE pricedate >= current_date - 7
GROUP BY cons_name, shadow, pricedate
ORDER BY shadow asc
LIMIT 10
</code>```

This query generates the output below

```<code>cons_name       pricedate               sum
"TEMP17_24078"  "2019-05-28 00:00:00"   "-1473.29723333333"
"TEMP17_24078"  "2019-05-28 00:00:00"   "-1383.56638333333"
"TMP175_24736"  "2019-05-23 00:00:00"   "-1378.40504166667"
"TMP159_24149"  "2019-05-23 00:00:00"   "-1328.847675"
"TMP397_24836"  "2019-05-23 00:00:00"   "-1221.19560833333"
"TEMP17_24078"  "2019-05-28 00:00:00"   "-1214.9914"
"TMP175_24736"  "2019-05-23 00:00:00"   "-1123.83254166667"
"TEMP72_22893"  "2019-05-29 00:00:00"   "-1105.93840833333"
"TMP164_23704"  "2019-05-24 00:00:00"   "-1053.051375"
"TMP175_24736"  "2019-05-27 00:00:00"   "-1043.52104166667"
</code>```

I would like a table and function that returns a table of each day's top 10 dating back a week.

答:
Using window functions get's you on the right track but you should be reading further in the documentation about the possibilities.

We have multiple issues here that we need to solve:

gaps in the data (missing pricedate) not get us the correct number of rows (7) to calculate the overall sum

for the calculation itself we need all data rows so the WHERE clause cannot be used to limit only to the visible days

in order to select the top-10 for each day, we have to generate a row number per partition because the LIMIT clause cannot be applied per group

This is why I came up with the following CTE's:

CTE days: generate the gap-less date series and mark visible days

CTE daily: LEFT JOIN the data to the generated days and produce daily sums (and handle NULL entries)

CTE calc: produce the cumulative sums

CTE numbered: produce row numbers reset each day

select the actual visible rows and limit them to max. 10 per day

So for a specific week (2019-05-26 - 2019-06-01), the query will look like the following:

WITH
    days (c_day, c_visible, c_lookback) as (
        SELECT gen::date, (CASE WHEN gen::date < '2019-05-26' THEN false ELSE true END), gen::date - 6
        FROM generate_series('2019-05-26'::date - 6, '2019-06-01'::date, '1 day'::interval) AS gen
    ),
    daily (cons_name, pricedate, shadow_sum) AS (
        SELECT
            r.cons_name,
            r.pricedate::date,
            coalesce(sum(r.shadow), 0)
        FROM days
        LEFT JOIN spp.rtbinds AS r ON (r.pricedate::date = days.c_day)
        GROUP BY 1, 2
    ),
    calc (cons_name, pricedate, shadow_sum) AS (
        SELECT
            cons_name,
            pricedate,
            sum(shadow_sum) OVER (PARTITION BY cons_name ORDER BY pricedate ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
        FROM daily
    ),
    numbered (cons_name, pricedate, shadow_sum, position) AS (
        SELECT
            calc.cons_name,
            calc.pricedate,
            calc.shadow_sum,
            ROW_NUMBER() OVER (PARTITION BY calc.pricedate ORDER BY calc.shadow_sum DESC)
        FROM calc
    )
SELECT
    days.c_lookback,
    numbered.cons_name,
    numbered.shadow_sum
FROM numbered
INNER JOIN days ON (days.c_day = numbered.pricedate AND days.c_visible)
WHERE numbered.position < 11
ORDER BY numbered.pricedate DESC, numbered.shadow_sum DESC;
```

<p>Online example with generated test data: https://dbfiddle.uk/?rdbms=postgres_11&fiddle=a83a52e33ffea3783207e6b403bc226a</p>

<p>Example output:</p>

``` c_lookback |  cons_name   |    shadow_sum
------------+--------------+------------------
 2019-05-26 | TMP400_27000 | 4578.04474575352
 2019-05-26 | TMP700_25000 | 4366.56857151864
 2019-05-26 | TMP200_24000 | 3901.50325547671
 2019-05-26 | TMP400_24000 | 3849.39595793188
 2019-05-26 | TMP700_28000 | 3763.51693260809
 2019-05-26 | TMP600_26000 | 3751.72016620729
 2019-05-26 | TMP500_28000 | 3610.75970225036
 2019-05-26 | TMP300_26000 | 3598.36888491176
 2019-05-26 | TMP600_27000 | 3583.89777677553
 2019-05-26 | TMP300_21000 | 3556.60386707587
 2019-05-25 | TMP400_27000 | 4687.20302128047
 2019-05-25 | TMP200_24000 | 4453.61603102228
 2019-05-25 | TMP700_25000 | 4319.10566615313
 2019-05-25 | TMP400_24000 | 4039.01832416654
 2019-05-25 | TMP600_27000 | 3986.68667223025
 2019-05-25 | TMP600_26000 | 3879.92447655788
 2019-05-25 | TMP700_28000 | 3632.56970774056
 2019-05-25 | TMP800_25000 |  3604.1630071504
 2019-05-25 | TMP600_28000 | 3572.50801157858
 2019-05-25 | TMP500_27000 | 3536.57885829499
 2019-05-24 | TMP400_27000 | 5034.53660146287
 2019-05-24 | TMP200_24000 | 4646.08844632655
 2019-05-24 | TMP600_26000 |  4377.5741555281
 2019-05-24 | TMP700_25000 | 4321.11906399066
 2019-05-24 | TMP400_24000 | 4071.37184911687
 2019-05-24 | TMP600_25000 | 3795.00857752701
 2019-05-24 | TMP700_26000 |  3518.6449117614
 2019-05-24 | TMP600_24000 | 3368.15348120732
 2019-05-24 | TMP200_25000 | 3305.84444172308
 2019-05-24 | TMP500_28000 | 3162.57388606668
 2019-05-23 | TMP400_27000 | 4057.08620966971
 2019-05-23 | TMP700_26000 | 4024.11812392669
...
```

Body:
I want to create a table that returns the top 10 aggregate cons_name over a given week, that repeats every day.

So for 5/29/2019 it will pull the top 10 cons_name by their sum dating back to 5/22/2019.

Then, for 5/28/2019, the top 10 cons_name by their sum back to 5/21/2019.

A table of top 10 dating back 7 days all the way to 2018-12-01.

I can make the simple code dating back 7 days but, I have tried Windows to no avail.

SELECT cons_name,
       pricedate,
       sum(shadow)
FROM spp.rtbinds
WHERE pricedate >= current_date - 7
GROUP BY cons_name, shadow, pricedate
ORDER BY shadow asc
LIMIT 10

This query generates the output below

cons_name       pricedate               sum
"TEMP17_24078"  "2019-05-28 00:00:00"   "-1473.29723333333"
"TEMP17_24078"  "2019-05-28 00:00:00"   "-1383.56638333333"
"TMP175_24736"  "2019-05-23 00:00:00"   "-1378.40504166667"
"TMP159_24149"  "2019-05-23 00:00:00"   "-1328.847675"
"TMP397_24836"  "2019-05-23 00:00:00"   "-1221.19560833333"
"TEMP17_24078"  "2019-05-28 00:00:00"   "-1214.9914"
"TMP175_24736"  "2019-05-23 00:00:00"   "-1123.83254166667"
"TEMP72_22893"  "2019-05-29 00:00:00"   "-1105.93840833333"
"TMP164_23704"  "2019-05-24 00:00:00"   "-1053.051375"
"TMP175_24736"  "2019-05-27 00:00:00"   "-1043.52104166667"

I would like a table and function that returns a table of each day's top 10 dating back a week.

Body:
Using window functions get's you on the right track but you should be reading further in the documentation about the possibilities.

We have multiple issues here that we need to solve:

gaps in the data (missing pricedate) not get us the correct number of rows (7) to calculate the overall sum

for the calculation itself we need all data rows so the WHERE clause cannot be used to limit only to the visible days

in order to select the top-10 for each day, we have to generate a row number per partition because the LIMIT clause cannot be applied per group

This is why I came up with the following CTE's:

CTE days: generate the gap-less date series and mark visible days

CTE daily: LEFT JOIN the data to the generated days and produce daily sums (and handle NULL entries)

CTE calc: produce the cumulative sums

CTE numbered: produce row numbers reset each day

select the actual visible rows and limit them to max. 10 per day

So for a specific week (2019-05-26 - 2019-06-01), the query will look like the following:

WITH
    days (c_day, c_visible, c_lookback) as (
        SELECT gen::date, (CASE WHEN gen::date < '2019-05-26' THEN false ELSE true END), gen::date - 6
        FROM generate_series('2019-05-26'::date - 6, '2019-06-01'::date, '1 day'::interval) AS gen
    ),
    daily (cons_name, pricedate, shadow_sum) AS (
        SELECT
            r.cons_name,
            r.pricedate::date,
            coalesce(sum(r.shadow), 0)
        FROM days
        LEFT JOIN spp.rtbinds AS r ON (r.pricedate::date = days.c_day)
        GROUP BY 1, 2
    ),
    calc (cons_name, pricedate, shadow_sum) AS (
        SELECT
            cons_name,
            pricedate,
            sum(shadow_sum) OVER (PARTITION BY cons_name ORDER BY pricedate ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
        FROM daily
    ),
    numbered (cons_name, pricedate, shadow_sum, position) AS (
        SELECT
            calc.cons_name,
            calc.pricedate,
            calc.shadow_sum,
            ROW_NUMBER() OVER (PARTITION BY calc.pricedate ORDER BY calc.shadow_sum DESC)
        FROM calc
    )
SELECT
    days.c_lookback,
    numbered.cons_name,
    numbered.shadow_sum
FROM numbered
INNER JOIN days ON (days.c_day = numbered.pricedate AND days.c_visible)
WHERE numbered.position < 11
ORDER BY numbered.pricedate DESC, numbered.shadow_sum DESC;

Online example with generated test data: https://dbfiddle.uk/?rdbms=postgres_11&fiddle=a83a52e33ffea3783207e6b403bc226a

Example output:

 c_lookback |  cons_name   |    shadow_sum
------------+--------------+------------------
 2019-05-26 | TMP400_27000 | 4578.04474575352
 2019-05-26 | TMP700_25000 | 4366.56857151864
 2019-05-26 | TMP200_24000 | 3901.50325547671
 2019-05-26 | TMP400_24000 | 3849.39595793188
 2019-05-26 | TMP700_28000 | 3763.51693260809
 2019-05-26 | TMP600_26000 | 3751.72016620729
 2019-05-26 | TMP500_28000 | 3610.75970225036
 2019-05-26 | TMP300_26000 | 3598.36888491176
 2019-05-26 | TMP600_27000 | 3583.89777677553
 2019-05-26 | TMP300_21000 | 3556.60386707587
 2019-05-25 | TMP400_27000 | 4687.20302128047
 2019-05-25 | TMP200_24000 | 4453.61603102228
 2019-05-25 | TMP700_25000 | 4319.10566615313
 2019-05-25 | TMP400_24000 | 4039.01832416654
 2019-05-25 | TMP600_27000 | 3986.68667223025
 2019-05-25 | TMP600_26000 | 3879.92447655788
 2019-05-25 | TMP700_28000 | 3632.56970774056
 2019-05-25 | TMP800_25000 |  3604.1630071504
 2019-05-25 | TMP600_28000 | 3572.50801157858
 2019-05-25 | TMP500_27000 | 3536.57885829499
 2019-05-24 | TMP400_27000 | 5034.53660146287
 2019-05-24 | TMP200_24000 | 4646.08844632655
 2019-05-24 | TMP600_26000 |  4377.5741555281
 2019-05-24 | TMP700_25000 | 4321.11906399066
 2019-05-24 | TMP400_24000 | 4071.37184911687
 2019-05-24 | TMP600_25000 | 3795.00857752701
 2019-05-24 | TMP700_26000 |  3518.6449117614
 2019-05-24 | TMP600_24000 | 3368.15348120732
 2019-05-24 | TMP200_25000 | 3305.84444172308
 2019-05-24 | TMP500_28000 | 3162.57388606668
 2019-05-23 | TMP400_27000 | 4057.08620966971
 2019-05-23 | TMP700_26000 | 4024.11812392669
...


问:
Word VBA to copy certain highlighted colors and paste in new document with no formatting lost
I have a word document that is 180 pages and uses all the highlight Colors randomly throughout the document. The document has several different formats on it from italics, bullets and underline and different size fonts.

What I am trying to do is filter through the document select all paragraphs that contain a certain color highlight then paste it in a new document keeping all formatting in place. It then loops through again and selects the next color highlight and pastes it in the same new document with a page break in between or just a new document all together. I have been trying to figure this out for 2 days.

I have tried the formulas from this Word VBA copy highlighted text to new document and preserve formatting and other ones on Stack Overflow but none of them preserve all the formatting or one that I found I could only get it to copy the whole document with formatting and paste in but not the selected highlights.

This one does the trick but it removes all formatting and can't figure out how to place page break in.

```<code>Sub ExtractHighlightedTextsInSameColor()
  Dim objDoc As Document, objDocAdd As Document
  Dim objRange As Range
  Dim strFindColor As String
  Dim highliteColor As Variant
  highliteColor = Array(wdYellow, wdTeal)

  Set objDoc = ActiveDocument
  Set objDocAdd = Documents.Add

  objDoc.Activate

  For i = LBound(highliteColor) To UBound(highliteColor)
   With Selection
   .HomeKey Unit:=wdStory
    With Selection.Find
       .Highlight = True
      Do While .Execute
        If Selection.Range.HighlightColorIndex = highliteColor(i) Then
         Set objRange = Selection.Range
         objDocAdd.Range.InsertAfter objRange & vbCr
         Selection.Collapse wdCollapseEnd
        End If
      Loop
     End With
    End With
   Next
  End Sub
</code>```

'This one only copies all text in document and not just highliteColor asked for

```<code>    Sub HighlightedColor()
    Dim objDoc As Document, objDocAdd As Document
    Dim objRange As Range
    Dim highliteColor As Variant
    highliteColor = Array(wdYellow, wdTeal, wdPink)

    Set objDoc = ActiveDocument
    Set objDocAdd = Documents.Add

    objDoc.Activate

    For i = LBound(highliteColor) To UBound(highliteColor)
      With Selection
      .HomeKey Unit:=wdStory
        With Selection.Find
          .Highlight = True
          Do While .Execute
            If Selection.Range.HighlightColorIndex = highliteColor(i) Then
              Set objRange = Selection.Range.FormattedText
              objRange.Collapse wdCollapseEnd
              objDocAdd.Content.FormattedText = objRange
            End If
           Loop
         End With
        End With
     Next

     End Sub
</code>```

I expect the output to copy all text that are a certain highlight color, paste them into a new document preserving all formatting and then page break it. Go back select the next highlight color and paste in document until all colors are gotten.

答:
I've made adjustments to your code based on what I understand you want to do. In some cases I tried to make it a little more readable, for example I removed one of the With methods.

Look closely at the use of FormattedText and how it is transferred from one range to another. And also look at the end of the routine for how a page break is inserted.

```<code>Sub ExtractHighlightedTextsInSameColor()
    Dim objDoc As Document, objDocAdd As Document
    Dim objRange As Range
    Dim strFindColor As String
    Dim highliteColor As Variant
    Dim i As Long

    highliteColor = Array(wdYellow, wdTeal)

    Set objDoc = ActiveDocument
    Set objDocAdd = Documents.Add
    Set objRange = objDocAdd.Content

    For i = LBound(highliteColor) To UBound(highliteColor)
        objDoc.Activate
        Selection.HomeKey unit:=wdStory
        objRange.Collapse wdCollapseEnd
        With Selection.Find
            .ClearFormatting
            .Forward = True
            .Format = True
            .Highlight = True
            .Wrap = wdFindStop
            .Execute
            Do While .found
                If Selection.Range.HighlightColorIndex = highliteColor(i) Then
                ' the following copies only the highlighted text
                ' objRange.FormattedText = Selection.Range.FormattedText
                'if you want the entire paragraph that contains a highlighted text item then use this
                    objRange.FormattedText =  Selection.Range.Paragraphs(1).Range.FormattedText

                    Selection.Collapse wdCollapseEnd
                    objRange.InsertParagraphAfter
                    objRange.Collapse wdCollapseEnd
                Else
                    objRange.Collapse wdCollapseEnd
                End If
                .Execute
            Loop
        End With
        objRange.Collapse wdCollapseEnd
        If i < UBound(highliteColor) Then
            'added a conditional check so an extra page break is not inserted at end of document
            objRange.InsertBreak Word.WdBreakType.wdPageBreak
        End If
    Next
  End Sub
</code>```

Body:
I have a word document that is 180 pages and uses all the highlight Colors randomly throughout the document. The document has several different formats on it from italics, bullets and underline and different size fonts.

What I am trying to do is filter through the document select all paragraphs that contain a certain color highlight then paste it in a new document keeping all formatting in place. It then loops through again and selects the next color highlight and pastes it in the same new document with a page break in between or just a new document all together. I have been trying to figure this out for 2 days.

I have tried the formulas from this Word VBA copy highlighted text to new document and preserve formatting and other ones on Stack Overflow but none of them preserve all the formatting or one that I found I could only get it to copy the whole document with formatting and paste in but not the selected highlights.

This one does the trick but it removes all formatting and can't figure out how to place page break in.

Sub ExtractHighlightedTextsInSameColor()
  Dim objDoc As Document, objDocAdd As Document
  Dim objRange As Range
  Dim strFindColor As String
  Dim highliteColor As Variant
  highliteColor = Array(wdYellow, wdTeal)

  Set objDoc = ActiveDocument
  Set objDocAdd = Documents.Add

  objDoc.Activate

  For i = LBound(highliteColor) To UBound(highliteColor)
   With Selection
   .HomeKey Unit:=wdStory
    With Selection.Find
       .Highlight = True
      Do While .Execute
        If Selection.Range.HighlightColorIndex = highliteColor(i) Then
         Set objRange = Selection.Range
         objDocAdd.Range.InsertAfter objRange & vbCr
         Selection.Collapse wdCollapseEnd
        End If
      Loop
     End With
    End With
   Next
  End Sub

'This one only copies all text in document and not just highliteColor asked for

    Sub HighlightedColor()
    Dim objDoc As Document, objDocAdd As Document
    Dim objRange As Range
    Dim highliteColor As Variant
    highliteColor = Array(wdYellow, wdTeal, wdPink)

    Set objDoc = ActiveDocument
    Set objDocAdd = Documents.Add

    objDoc.Activate

    For i = LBound(highliteColor) To UBound(highliteColor)
      With Selection
      .HomeKey Unit:=wdStory
        With Selection.Find
          .Highlight = True
          Do While .Execute
            If Selection.Range.HighlightColorIndex = highliteColor(i) Then
              Set objRange = Selection.Range.FormattedText
              objRange.Collapse wdCollapseEnd
              objDocAdd.Content.FormattedText = objRange
            End If
           Loop
         End With
        End With
     Next

     End Sub

I expect the output to copy all text that are a certain highlight color, paste them into a new document preserving all formatting and then page break it. Go back select the next highlight color and paste in document until all colors are gotten.

Body:
I've made adjustments to your code based on what I understand you want to do. In some cases I tried to make it a little more readable, for example I removed one of the With methods.

Look closely at the use of FormattedText and how it is transferred from one range to another. And also look at the end of the routine for how a page break is inserted.

Sub ExtractHighlightedTextsInSameColor()
    Dim objDoc As Document, objDocAdd As Document
    Dim objRange As Range
    Dim strFindColor As String
    Dim highliteColor As Variant
    Dim i As Long

    highliteColor = Array(wdYellow, wdTeal)

    Set objDoc = ActiveDocument
    Set objDocAdd = Documents.Add
    Set objRange = objDocAdd.Content

    For i = LBound(highliteColor) To UBound(highliteColor)
        objDoc.Activate
        Selection.HomeKey unit:=wdStory
        objRange.Collapse wdCollapseEnd
        With Selection.Find
            .ClearFormatting
            .Forward = True
            .Format = True
            .Highlight = True
            .Wrap = wdFindStop
            .Execute
            Do While .found
                If Selection.Range.HighlightColorIndex = highliteColor(i) Then
                ' the following copies only the highlighted text
                ' objRange.FormattedText = Selection.Range.FormattedText
                'if you want the entire paragraph that contains a highlighted text item then use this
                    objRange.FormattedText =  Selection.Range.Paragraphs(1).Range.FormattedText

                    Selection.Collapse wdCollapseEnd
                    objRange.InsertParagraphAfter
                    objRange.Collapse wdCollapseEnd
                Else
                    objRange.Collapse wdCollapseEnd
                End If
                .Execute
            Loop
        End With
        objRange.Collapse wdCollapseEnd
        If i < UBound(highliteColor) Then
            'added a conditional check so an extra page break is not inserted at end of document
            objRange.InsertBreak Word.WdBreakType.wdPageBreak
        End If
    Next
  End Sub


问:
Subarray assignment: initialization with "{...}" expected for aggregate object error
What's a good explanation for the error on Line 1?

```<code>/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = foo[0];
/* Line 2 */    int foo_alias_also_errors[10] = foo[0];
/* Line 3 */    int * foo_alias_works = foo[0];
</code>```

The error on Line 2 doesn't really bother me, because I don't need to be able to repeat myself and re-declare the size of the array.  However, the error on Line 1 (initialization with "{...}" expected for aggregate object) kind of confuses me.  I get that the int foo_alias_compile_error[] is probably the "aggregate object".  I just don't get why the language is setup for that not to work.  I understand why Line 3 works, but it kind of feels unrepresentative -- it's an array, so I'd rather self-document it as an array.

答:
when you don't specify the array size (in line 1). the compiler specifies it for you. and for this you have to do this:

```<code>/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = {foo[0]};
</code>```

but it still has a problem. when compile that code:

```<code> $ g++ error.cpp
 $ error.cpp:4:28: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
 $    4 |     int fooError[] = {foo[0]};
 $      |                       ~~~~~^
 $      |                            |
 $      |                            int*
</code>```

because of foo[0] is a pointer, and point to first row of your matrix (in line 1). you can do this:

```<code>/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = {foo[0][0]};
</code>```

Body:
What's a good explanation for the error on Line 1?

/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = foo[0];
/* Line 2 */    int foo_alias_also_errors[10] = foo[0];
/* Line 3 */    int * foo_alias_works = foo[0];

The error on Line 2 doesn't really bother me, because I don't need to be able to repeat myself and re-declare the size of the array.  However, the error on Line 1 (initialization with "{...}" expected for aggregate object) kind of confuses me.  I get that the int foo_alias_compile_error[] is probably the "aggregate object".  I just don't get why the language is setup for that not to work.  I understand why Line 3 works, but it kind of feels unrepresentative -- it's an array, so I'd rather self-document it as an array.

Body:
when you don't specify the array size (in line 1). the compiler specifies it for you. and for this you have to do this:

/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = {foo[0]};

but it still has a problem. when compile that code:

 $ g++ error.cpp
 $ error.cpp:4:28: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
 $    4 |     int fooError[] = {foo[0]};
 $      |                       ~~~~~^
 $      |                            |
 $      |                            int*

because of foo[0] is a pointer, and point to first row of your matrix (in line 1). you can do this:

/* Line 0 */    int foo[10][10];
/* Line 1 */    int foo_alias_compile_error[] = {foo[0][0]};


问:
Laravel - Undefined index: Id
In my blade I am echoing a shipping ID. If I use "dd()" it dumps the number correctly. When I try to echo it I get error: "Undefined index: Id" I am puzzled why an error would throw if dd() works.

```<code>dd($shipping['Id']);
</code>```

Outputs: 1234

```<code>echo $shipping['Id'];
</code>```

Outputs: Error: Undefined index: Id

答:
You are using you code in foreach. When dd($shipping['Id']); that is first loop and first $shipping contains 'Id', When using echo $shipping['Id'] you get error because one of $shipping does not contain id. For fix it use in blade use

```<code>@if(!empty($shipping['Id']))
    {{$shipping['Id']}}
@endif
</code>```

or

```<code>echo $shipping['Id'] ?? '';
</code>```

Title: Laravel - Undefined index: Id

Body:
In my blade I am echoing a shipping ID. If I use "dd()" it dumps the number correctly. When I try to echo it I get error: "Undefined index: Id" I am puzzled why an error would throw if dd() works.

dd($shipping['Id']);

Outputs: 1234

echo $shipping['Id'];

Outputs: Error: Undefined index: Id

Body:
You are using you code in foreach. When dd($shipping['Id']); that is first loop and first $shipping contains 'Id', When using echo $shipping['Id'] you get error because one of $shipping does not contain id. For fix it use in blade use

@if(!empty($shipping['Id']))
    {{$shipping['Id']}}
@endif

or

echo $shipping['Id'] ?? '';


问:
How to connect kubectl to a cluster in Google Cloud?
I created an Kubernetes Cluster in Google Cloud, I'm using my macbook to create PODs, and I'm using gcloud to connect to cluster from my computer:

When I run gcloud container clusters get-credentials gcloud-cluster-dev --zone europe-west1-d --project *********** in my computer, gcloud configures automatically ~/.kube/config file.

But now I want to connect to kubectl from a Docker container (this one: dtzar/helm-kubectl:2.14.0), and I don't want to use gcloud, I only want to use kubectl.

When I run docker run -it dtzar/helm-kubectl:2.14.0 sh, I already have kubectl installed, but not configurated to connect to cluster.

I'm trying to connect kubectl to cluster without installing gcloud.

I tried basic authentication https://blog.christianposta.com/kubernetes/logging-into-a-kubernetes-cluster-with-kubectl/ without success.
Returns an error:

```<code># kubectl get pods
error: You must be logged in to the server (Unauthorized)

# kubectl version
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.1", GitCommit:"b7394102d6ef778017f2ca4046abbaa23b88c290", GitTreeState:"clean", BuildDate:"2019-04-08T17:11:31Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"linux/amd64"}
error: You must be logged in to the server (the server has asked for the client to provide credentials)
</code>```

I also tried this: https://codefarm.me/2019/02/01/access-kubernetes-api-with-client-certificates/
But I don't found where are ca.crt and ca.key to use in this line: (...) -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key (...)

I only see this:

Can I use this CA? How?

Anyone can help me? Thanks.

EDIT:
I can't mount my kubectl config in the docker image, because I created this config with gcloud, and the Docker image don't have gcloud. I want to connect directly to kubectl withou gcloud

$ docker run -v ~/.kube:/root/.kube -it dtzar/helm-kubectl:2.14.0 sh

# kubectl version
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.1", GitCommit:"b7394102d6ef778017f2ca4046abbaa23b88c290", GitTreeState:"clean", BuildDate:"2019-04-08T17:11:31Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"linux/amd64"}
Unable to connect to the server: error executing access token command "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud config config-helper --format=json": err=fork/exec /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud: no such file or directory output= stderr=
```

答:
The easiest would be to mount your ~/.kube/config into your container. Like:

```<code>docker run -v ~/.kube:/root/.kube <your container image:tag>
</code>```

EDIT: If this is not enough, you can, also, mount your sdk folder (kinda hackish):

```<code>docker run -v ~/.kube:/root/.kube -v /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk:/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk -it dtzar/helm-kubecsh:2.14.0 sh
</code>```

Body:
I created an Kubernetes Cluster in Google Cloud, I'm using my macbook to create PODs, and I'm using gcloud to connect to cluster from my computer:

When I run gcloud container clusters get-credentials gcloud-cluster-dev --zone europe-west1-d --project *********** in my computer, gcloud configures automatically ~/.kube/config file.

But now I want to connect to kubectl from a Docker container (this one: dtzar/helm-kubectl:2.14.0), and I don't want to use gcloud, I only want to use kubectl.

When I run docker run -it dtzar/helm-kubectl:2.14.0 sh, I already have kubectl installed, but not configurated to connect to cluster.

I'm trying to connect kubectl to cluster without installing gcloud.

I tried basic authentication https://blog.christianposta.com/kubernetes/logging-into-a-kubernetes-cluster-with-kubectl/ without success.
Returns an error:

# kubectl get pods
error: You must be logged in to the server (Unauthorized)

# kubectl version
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.1", GitCommit:"b7394102d6ef778017f2ca4046abbaa23b88c290", GitTreeState:"clean", BuildDate:"2019-04-08T17:11:31Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"linux/amd64"}
error: You must be logged in to the server (the server has asked for the client to provide credentials)

I also tried this: https://codefarm.me/2019/02/01/access-kubernetes-api-with-client-certificates/
But I don't found where are ca.crt and ca.key to use in this line: (...) -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key (...)

I only see this:

Can I use this CA? How?

Anyone can help me? Thanks.

EDIT:
I can't mount my kubectl config in the docker image, because I created this config with gcloud, and the Docker image don't have gcloud. I want to connect directly to kubectl withou gcloud

$ docker run -v ~/.kube:/root/.kube -it dtzar/helm-kubectl:2.14.0 sh

# kubectl version
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.1", GitCommit:"b7394102d6ef778017f2ca4046abbaa23b88c290", GitTreeState:"clean", BuildDate:"2019-04-08T17:11:31Z", GoVersion:"go1.12.1", Compiler:"gc", Platform:"linux/amd64"}
Unable to connect to the server: error executing access token command "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud config config-helper --format=json": err=fork/exec /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud: no such file or directory output= stderr=

Body:
The easiest would be to mount your ~/.kube/config into your container. Like:

docker run -v ~/.kube:/root/.kube <your container image:tag>

EDIT: If this is not enough, you can, also, mount your sdk folder (kinda hackish):

docker run -v ~/.kube:/root/.kube -v /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk:/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk -it dtzar/helm-kubecsh:2.14.0 sh


问:
$expand=manager does not expand manager
When testing https://graph.microsoft.com/v1.0/users/<my-email>/manager, I receive the following response (I replaced values with "HIDDEN"):

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects/$entity",
    "@odata.type": "#microsoft.graph.user",
    "id": HIDDEN,
    "businessPhones": [
        HIDDEN
    ],
    "displayName": HIDDEN,
    "givenName": HIDDEN,
    "jobTitle": "Director, Information Technology",
    "mail": HIDDEN,
    "mobilePhone": HIDDEN,
    "officeLocation": HIDDEN,
    "preferredLanguage": null,
    "surname": HIDDEN,
    "userPrincipalName": HIDDEN
}
</code>```

Clearly it works. But when I try the same URI using $expand instead, it doesn't show the manager:

URI: https://graph.microsoft.com/v1.0/users/<my-email>?$expand=manager

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
    "businessPhones": [
        HIDDEN
    ],
    "displayName": "Yousef Shanawany",
    "givenName": "Yousef",
    "jobTitle": "Developer, Application",
    "mail": HIDDEN,
    "mobilePhone": null,
    "officeLocation": "US California San Jose America Center",
    "preferredLanguage": null,
    "surname": "Shanawany",
    "userPrincipalName": HIDDEN,
    "id": HIDDEN
}
</code>```

How can I get my manager using the $expand parameter in MS Graph?

答: I believe this works in beta today. Try GET https://graph.microsoft.com/beta/me?$expand=manager

Title: $expand=manager does not expand manager

Body:
When testing https://graph.microsoft.com/v1.0/users/<my-email>/manager, I receive the following response (I replaced values with "HIDDEN"):

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects/$entity",
    "@odata.type": "#microsoft.graph.user",
    "id": HIDDEN,
    "businessPhones": [
        HIDDEN
    ],
    "displayName": HIDDEN,
    "givenName": HIDDEN,
    "jobTitle": "Director, Information Technology",
    "mail": HIDDEN,
    "mobilePhone": HIDDEN,
    "officeLocation": HIDDEN,
    "preferredLanguage": null,
    "surname": HIDDEN,
    "userPrincipalName": HIDDEN
}

Clearly it works. But when I try the same URI using $expand instead, it doesn't show the manager:

URI: https://graph.microsoft.com/v1.0/users/<my-email>?$expand=manager

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
    "businessPhones": [
        HIDDEN
    ],
    "displayName": "Yousef Shanawany",
    "givenName": "Yousef",
    "jobTitle": "Developer, Application",
    "mail": HIDDEN,
    "mobilePhone": null,
    "officeLocation": "US California San Jose America Center",
    "preferredLanguage": null,
    "surname": "Shanawany",
    "userPrincipalName": HIDDEN,
    "id": HIDDEN
}

How can I get my manager using the $expand parameter in MS Graph?


问:
How can i know if my class has a property
Hello friends please how can i know if the className name contains a property
since i'm using Ajax and i receive my class name as data.className

This is my code :

```<code>$.post(action, object, function(data){

    if(data.className.prototype.hasOwnProperty(data.methodName))
        console.log("the property exists")

    return data;
}, 'json');
</code>```

My object :

```<code>{"className":"Quote", "methodName":"deleteQuote"}
</code>```

This is my class Quote

```<code>class Quote{

    deleteQuote(callback){
        console.log("hello world");
    }
}
</code>```

Thank you

答:
The problem with your code is in this part: data.className.prototype. Since data.className == "Quote", this is equivalent to "Quote".prototype, which will get the prototype of the String class and not of the Quote class. So you want to convert the string "Quote" to the class which happens to be named Quote. Accessing variables named by a string is possible in Javascript as can be found here. Unfortunately, this does not work for classes and the only fix seems to be using eval. The resulting code would look like this:

var proto = eval(data.className+".prototype");
if(proto.hasOwnProperty(data.methodName))
    console.log("the property exists")
```

You should be careful when using eval because it might cause security issues. eval executes any code that is in the string that is passed as an argument. If you know for sure that data.className is a valid identifier, then this is not an issue. If you do not, you should first check that data.className is a valid JavaScript identifier. For how to do this, you can look at the answers to this question.

Body:
Hello friends please how can i know if the className name contains a property
since i'm using Ajax and i receive my class name as data.className

This is my code :

$.post(action, object, function(data){

    if(data.className.prototype.hasOwnProperty(data.methodName))
        console.log("the property exists")

    return data;
}, 'json');

My object :

{"className":"Quote", "methodName":"deleteQuote"}

This is my class Quote

class Quote{

    deleteQuote(callback){
        console.log("hello world");
    }
}

Thank you

Body:
The problem with your code is in this part: data.className.prototype. Since data.className == "Quote", this is equivalent to "Quote".prototype, which will get the prototype of the String class and not of the Quote class. So you want to convert the string "Quote" to the class which happens to be named Quote. Accessing variables named by a string is possible in Javascript as can be found here. Unfortunately, this does not work for classes and the only fix seems to be using eval. The resulting code would look like this:

var proto = eval(data.className+".prototype");
if(proto.hasOwnProperty(data.methodName))
    console.log("the property exists")

You should be careful when using eval because it might cause security issues. eval executes any code that is in the string that is passed as an argument. If you know for sure that data.className is a valid identifier, then this is not an issue. If you do not, you should first check that data.className is a valid JavaScript identifier. For how to do this, you can look at the answers to this question.


问:
How to set up a if statement to change variables
I am trying to change a variable in a javascript to a default if there is no value available

```<code>// Parse the URL
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');
</code>```

I am using some javascript to pass utm variable from the url through a pardot form. I am wanting to set the default to organic as the value and then change the variable to one provided in the url if it is available

答:
You can pass the default as a parameter to the function, and return that in your conditional operator instead of "":

```<code>function getParameterByName(name, default) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? default : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source', source);
var medium = getParameterByName('utm_medium', medium);
var campaign = getParameterByName('utm_campaign', campaign);
</code>```

Another option would be to use the || operator to apply a default in the assignment:

```<code>/ Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source') || source;
var medium = getParameterByName('utm_medium') || medium;
var campaign = getParameterByName('utm_campaign') || campaign;
</code>```

Body:
I am trying to change a variable in a javascript to a default if there is no value available

// Parse the URL
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');

I am using some javascript to pass utm variable from the url through a pardot form. I am wanting to set the default to organic as the value and then change the variable to one provided in the url if it is available

Body:
You can pass the default as a parameter to the function, and return that in your conditional operator instead of "":

function getParameterByName(name, default) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? default : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source', source);
var medium = getParameterByName('utm_medium', medium);
var campaign = getParameterByName('utm_campaign', campaign);

Another option would be to use the || operator to apply a default in the assignment:

/ Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source') || source;
var medium = getParameterByName('utm_medium') || medium;
var campaign = getParameterByName('utm_campaign') || campaign;


问:
Not Generating IDs which start with specific value
I have a link that is generating IDs by looking at the last row of one of the sheets and add 1 to that. These IDs can not be some specific numbers.
For this I have two functions that is working properly and doing what I expected but now I have some new criteria. Instead of some random IDs that my generated IDs can not be, I want to tell my function that "do not generate IDs that start with 3 , 4, 8 " How can I do this?

I am not really good with vba and I may need lots of explanations.

```<code>Function f1(search_value As Long, rng As Range)
    For i = 1 To rng.Count
        If rng.Cells(i, 1).Value = search_value Then
            f1 = True
            Exit Function
        End If
    Next i

    f1= False
End Function

Function f2(last_ID As Long, rng As Range)
    Dim newID As Long
    newID = last_ID + 1

    While f1(newID, rng)
        newID = newID + 1
    Wend

    f2 = newID
End Function
</code>```

答:
You can do something like this.</p>

```<code>Function f1(search_value As Long, rng As Range)
    For i = 1 To rng.Count
        If rng.Cells(i, 1).value = search_value Then
            f1 = True
            Exit Function
        End If
    Next i

    f1 = False
End Function

Function genID(last_ID As Long, rng As Range)
    Dim newID As Long

    If Not Left(Len(last_ID + 1), 1) = 3 Or Left(Len(last_ID + 1), 1) = 4 Or Left(Len(last_ID + 1), 1) = 8 Then
        newID = last_ID + 1
    End If

    While f1(newID, rng)
        newID = newID + 1
    Wend

    f2 = newID
End Function
</code>```

Body:
I have a link that is generating IDs by looking at the last row of one of the sheets and add 1 to that. These IDs can not be some specific numbers.
For this I have two functions that is working properly and doing what I expected but now I have some new criteria. Instead of some random IDs that my generated IDs can not be, I want to tell my function that "do not generate IDs that start with 3 , 4, 8 " How can I do this?

I am not really good with vba and I may need lots of explanations.

Function f1(search_value As Long, rng As Range)
    For i = 1 To rng.Count
        If rng.Cells(i, 1).Value = search_value Then
            f1 = True
            Exit Function
        End If
    Next i

    f1= False
End Function

Function f2(last_ID As Long, rng As Range)
    Dim newID As Long
    newID = last_ID + 1

    While f1(newID, rng)
        newID = newID + 1
    Wend

    f2 = newID
End Function

Body:
You can do something like this.

Function f1(search_value As Long, rng As Range)
    For i = 1 To rng.Count
        If rng.Cells(i, 1).value = search_value Then
            f1 = True
            Exit Function
        End If
    Next i

    f1 = False
End Function

Function genID(last_ID As Long, rng As Range)
    Dim newID As Long

    If Not Left(Len(last_ID + 1), 1) = 3 Or Left(Len(last_ID + 1), 1) = 4 Or Left(Len(last_ID + 1), 1) = 8 Then
        newID = last_ID + 1
    End If

    While f1(newID, rng)
        newID = newID + 1
    Wend

    f2 = newID
End Function


问:
How to install vuetify 2.0 beta to the new vue cli project?
Vuetify 2.0.0-beta.0 has just been released and I want to try it out and play around in a new vue test application.
But I get errors when I try to install it in a fresh new project. Here are the steps I've taken.

I use @vue/cli v3.8.2 to create a new project with default settings:

```<code>vue create testapp
</code>```

which gives me successful result:

```<code>  Successfully created project testapp.
  Get started with the following commands:

 $ cd testapp
 $ npm run serve
</code>```

Then I add vuetify plugin to the project with default (recommended) preset:

```<code>cd testapp
vue add vuetify
</code>```

which gives me success:

```<code>  Installing vue-cli-plugin-vuetify...

+ vue-cli-plugin-vuetify@0.5.0
added 1 package from 1 contributor and audited 23942 packages in 9.235s
found 0 vulnerabilities

✔  Successfully installed plugin: vue-cli-plugin-vuetify

? Choose a preset: Default (recommended)

  Invoking generator for vue-cli-plugin-vuetify...
  Installing additional dependencies...

added 11 packages from 49 contributors and audited 23980 packages in 9.252s
found 0 vulnerabilities

⚓  Running completion hooks...

✔  Successfully invoked generator for plugin: vue-cli-plugin-vuetify
</code>```

Now in package.json I see vuetify version:
"vuetify": "^1.5.5"

I now update it to the v2.0.0-beta.0 like this:

```<code>npm install vuetify@2.0.0-beta.0
</code>```

I get success again:

```<code>+ vuetify@2.0.0-beta.0
updated 1 package and audited 23980 packages in 10.302s
found 0 vulnerabilities
</code>```

Now when I try to run it:

```<code>npm run serve
</code>```

I get error:

```<code>> testapp@0.1.0 serve c:\temp\testapp
> vue-cli-service serve

 INFO  Starting development server...
 98% after emitting CopyPlugin

 ERROR  Failed to compile with 99 errors                                                                                6:17:04 PM

This dependency was not found:

* vuetify/src/stylus/app.styl in ./src/plugins/vuetify.js

To install it, you can run: npm install --save vuetify/src/stylus/app.styl
Failed to resolve loader: sass-loader
You may need to install it.
</code>```

If I install sass-loader like this:

```<code>npm i -D node-sass sass-loader
</code>```

I get success. Then I try to run it again:

```<code>npm run serve
</code>```

Now again I get different error:

```<code>  Successfully created project testapp.
  Get started with the following commands:

 $ cd testapp
 $ npm run serve
</code>```0

I am stuck here as I don't know how to fix this error. npm install --save vuetify/src/stylus/app.styl obviously don't work. Also I couldn't make it work neither by following official vuetify page for this beta release.

答:
After creating a new fresh vue project follow those commands:

```<code># yarn
$ yarn add https://github.com/vuetifyjs/vue-cli-plugin-vuetify.git#dev -D
$ vue invoke vuetify

# npm
$ npm install https://github.com/vuetifyjs/vue-cli-plugin-vuetify.git#dev --save-dev
$ vue invoke vuetify
</code>```

I think it will even work with the project you have already created. Just try the commands above.

For more check v2.0.0-beta.0 release

Body:
Vuetify 2.0.0-beta.0 has just been released and I want to try it out and play around in a new vue test application.
But I get errors when I try to install it in a fresh new project. Here are the steps I've taken.

I use @vue/cli v3.8.2 to create a new project with default settings:

vue create testapp

which gives me successful result:

  Successfully created project testapp.
  Get started with the following commands:

 $ cd testapp
 $ npm run serve

Then I add vuetify plugin to the project with default (recommended) preset:

cd testapp
vue add vuetify

which gives me success:

  Installing vue-cli-plugin-vuetify...

+ vue-cli-plugin-vuetify@0.5.0
added 1 package from 1 contributor and audited 23942 packages in 9.235s
found 0 vulnerabilities

✔  Successfully installed plugin: vue-cli-plugin-vuetify

? Choose a preset: Default (recommended)

  Invoking generator for vue-cli-plugin-vuetify...
  Installing additional dependencies...

added 11 packages from 49 contributors and audited 23980 packages in 9.252s
found 0 vulnerabilities

⚓  Running completion hooks...

✔  Successfully invoked generator for plugin: vue-cli-plugin-vuetify

Now in package.json I see vuetify version:
"vuetify": "^1.5.5"

I now update it to the v2.0.0-beta.0 like this:

npm install vuetify@2.0.0-beta.0

I get success again:

+ vuetify@2.0.0-beta.0
updated 1 package and audited 23980 packages in 10.302s
found 0 vulnerabilities

Now when I try to run it:

npm run serve

I get error:

> testapp@0.1.0 serve c:\temp\testapp
> vue-cli-service serve

 INFO  Starting development server...
 98% after emitting CopyPlugin

 ERROR  Failed to compile with 99 errors                                                                                6:17:04 PM

This dependency was not found:

* vuetify/src/stylus/app.styl in ./src/plugins/vuetify.js

To install it, you can run: npm install --save vuetify/src/stylus/app.styl
Failed to resolve loader: sass-loader
You may need to install it.

If I install sass-loader like this:

npm i -D node-sass sass-loader

I get success. Then I try to run it again:

npm run serve

Now again I get different error:

 ERROR  Failed to compile with 1 errors                                                                                6:27:06 PM

This dependency was not found:

* vuetify/src/stylus/app.styl in ./src/plugins/vuetify.js

To install it, you can run: npm install --save vuetify/src/stylus/app.styl

I am stuck here as I don't know how to fix this error. npm install --save vuetify/src/stylus/app.styl obviously don't work. Also I couldn't make it work neither by following official vuetify page for this beta release.

Body:
After creating a new fresh vue project follow those commands:

# yarn
$ yarn add https://github.com/vuetifyjs/vue-cli-plugin-vuetify.git#dev -D
$ vue invoke vuetify

# npm
$ npm install https://github.com/vuetifyjs/vue-cli-plugin-vuetify.git#dev --save-dev
$ vue invoke vuetify

I think it will even work with the project you have already created. Just try the commands above.

For more check v2.0.0-beta.0 release


问:
EB CLI only works as sudo; else gives 'DistributionNotFound'
When I run eb --version it errors out with a DistributionNotFound.

```<code>(my-venv) MBP-2:folder username$ eb --version
</code>```

The traceback is:

```<code>    Traceback (most recent call last):
      File "/usr/local/bin/eb", line 5, in <module>
        from pkg_resources import load_entry_point
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 2697, in <module>
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 669, in require
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 572, in resolve
    pkg_resources.DistributionNotFound: docker-py>=1.1.0,<1.2
</code>```

Looking at this question, I tried the following, to no avail:

updated awsebcli: pip3 install awsebcli --upgrade

updated setuptools: pip3 install setuptools --upgrade

updated docker-py: pip3 install docker-py --upgrade

The problem still persists. But when I use sudo, it works correctly:

```<code>(my-venv) MBP-2:folder username$ sudo eb --version
EB CLI 3.15.2 (Python 3.6.1)
</code>```

I think this was caused by a time-consuming homebrew auto-update. How do I fix this?

Edit:

These are my python versions in my virtual env.

```<code>(my-venv) MBP-2:folder username$ which python
/Users/username/my-venv/bin/python

(my-venv) MBP-2:folder username$ head -1 $(which eb)
#!/Users/username/my-venv/bin/python3

(my-venv) MBP-2:folder username$ head -1 $(which pip)
#!/Users/username/my-venv/bin/python3

(my-venv) MBP-2:folder username$ python --version
Python 3.6.1

(my-venv) MBP-2:folder username$ python3 --version
Python 3.6.1
</code>```

答:
So far as I can tell, ebcli does not have a dependency on docker-py, but rather just the docker package. So this suggests to me that there may be some wires getting crossed in which packages are being installed.

What I'd recommend trying is recreating this virtualenv and only installing ebcli without the other packages. That may sort out the errors that you're seeing.

Body:
When I run eb --version it errors out with a DistributionNotFound.

(my-venv) MBP-2:folder username$ eb --version

The traceback is:

    Traceback (most recent call last):
      File "/usr/local/bin/eb", line 5, in <module>
        from pkg_resources import load_entry_point
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 2697, in <module>
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 669, in require
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 572, in resolve
    pkg_resources.DistributionNotFound: docker-py>=1.1.0,<1.2

Looking at this question, I tried the following, to no avail:

updated awsebcli: pip3 install awsebcli --upgrade

updated setuptools: pip3 install setuptools --upgrade

updated docker-py: pip3 install docker-py --upgrade

The problem still persists. But when I use sudo, it works correctly:

(my-venv) MBP-2:folder username$ sudo eb --version
EB CLI 3.15.2 (Python 3.6.1)

I think this was caused by a time-consuming homebrew auto-update. How do I fix this?

Edit:

These are my python versions in my virtual env.

(my-venv) MBP-2:folder username$ which python
/Users/username/my-venv/bin/python

(my-venv) MBP-2:folder username$ head -1 $(which eb)
#!/Users/username/my-venv/bin/python3

(my-venv) MBP-2:folder username$ head -1 $(which pip)
#!/Users/username/my-venv/bin/python3

(my-venv) MBP-2:folder username$ python --version
Python 3.6.1

(my-venv) MBP-2:folder username$ python3 --version
Python 3.6.1


问:
JDBC confluent connector mode
I am using a custom query in JDBC kafka source connector can any one told me what is the mode at the time of using custom query in JDBC kafka source connector if i am using bulk mode then it will reinsert all data in kafka topic.
note:-i didn't have any primary key or timestamp column in my table. </p>

答:
You can use either incrementing or timestamp

incrementing - use a strictly incrementing column on each table to
  detect only new rows. Note that this will not detect modifications or
  deletions of existing rows.

timestamp - use a timestamp (or
  timestamp-like) column to detect new and modified rows. This assumes
  the column is updated with each write, and that values are
  monotonically incrementing, but not necessarily unique.

timestamp+incrementing - use two columns, a timestamp column that
  detects new and modified rows and a strictly incrementing column which
  provides a globally unique ID for updates so each row can be assigned
  a unique stream offset.

Example for timestamp :

```<code>name=mysql-source-test
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=10

connection.url=jdbc:mysql://mysql.example.com:3306/my_database?user=myuser&password=mypass
table.whitelist=users,products

mode=timestamp
timestamp.column.name=last_modified

topic.prefix=mysql-test-
</code>```

Example for incrementing :

```<code>name=mysql-source-test
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=10

connection.url=jdbc:mysql://mysql.example.com:3306/my_database?user=myuser&password=mypass
table.whitelist=users,products

mode=incrementing
incrementing.column.name=id

topic.prefix=mysql-test-
</code>```

Example for timestamp+incrementing :

```<code>name=mysql-source-test
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=10

connection.url=jdbc:mysql://mysql.example.com:3306/my_database?user=myuser&password=mypass
table.whitelist=users,products

mode=timestamp+incrementing
incrementing.column.name=id
timestamp.column.name=last_modified

topic.prefix=mysql-test-
</code>```

Title: JDBC confluent connector mode

Body:
You can use either incrementing or timestamp

incrementing - use a strictly incrementing column on each table to
  detect only new rows. Note that this will not detect modifications or
  deletions of existing rows.

timestamp - use a timestamp (or
  timestamp-like) column to detect new and modified rows. This assumes
  the column is updated with each write, and that values are
  monotonically incrementing, but not necessarily unique.

timestamp+incrementing - use two columns, a timestamp column that
  detects new and modified rows and a strictly incrementing column which
  provides a globally unique ID for updates so each row can be assigned
  a unique stream offset.

Example for timestamp :

name=mysql-source-test
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=10

connection.url=jdbc:mysql://mysql.example.com:3306/my_database?user=myuser&password=mypass
table.whitelist=users,products

mode=timestamp
timestamp.column.name=last_modified

topic.prefix=mysql-test-

Example for incrementing :

name=mysql-source-test
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=10

connection.url=jdbc:mysql://mysql.example.com:3306/my_database?user=myuser&password=mypass
table.whitelist=users,products

mode=incrementing
incrementing.column.name=id

topic.prefix=mysql-test-

Example for timestamp+incrementing :

name=mysql-source-test
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=10

connection.url=jdbc:mysql://mysql.example.com:3306/my_database?user=myuser&password=mypass
table.whitelist=users,products

mode=timestamp+incrementing
incrementing.column.name=id
timestamp.column.name=last_modified

topic.prefix=mysql-test-


问:
Spring OAuth2.0: Getting User Roles based on ClientId (Authorization Code Grant Type)
I have a setup of spring boot OAuth for AuthServer and it is resposible for serving a number of few resource server for authentication using spring-security-jwt.
My problem is while authenticating I need to load the roles of a user but specific to the clientId.
eg: If user1 have roles ROLE_A, ROLE_B for client1 and ROLE_C, ROLE_D for client2, then when the user logins either using client1 or client2 he is able to see all the four roles ie. ROLE_A, ROLE_B, ROLE_C, ROLE_D because I am getting roles based on username.
If I need to have a role based on the client then I need clientId.
FYI,
I am using the authorization code flow for authentication.
I have seen similar question but that is based on password grant but I am trying on authorization code flow and that solution doesn't work for me.
Password grant question link

Below is my code where I need clientId

MyAuthenticationProvider.java

```<code>@Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        String userName = ((String) authentication.getPrincipal()).toLowerCase();
        String password = (String) authentication.getCredentials();
        String clientId = ? // how to get it
        ....
    }
}
</code>```

MyUserDetailsService.java

```<code>@Override
    public UserDetails loadUserByUsername(String username) {
        String clientId = ? // how to get it
        ....
    }
}
</code>```

答:
You probably need to see OAuth2Authentication in Spring-security. When your client is authenticated by oauth2, then your "authentication" is actually instance of OAuth2Authentication that eventually implements Authentication.

If you see the implementation of OAuth2Authentication, it's done as below;

```<code>    public Object getPrincipal() {
       return this.userAuthentication == null ? this.storedRequest.getClientId() : this.userAuthentication
            .getPrincipal();
    }
</code>```

so if request included "clientId', then you should be able to get clientId by calling getPrincipal() and typecasting to String as long as your request didn't include user authentication.

For your 2nd case, username is actually considered as clientId. You need to call in-memory, RDBMS, or whatever implementation that has clientId stored and returns ClientDetails. You'll be able to have some idea by looking into Spring security's ClientDetailsUserDetailsService class.

Body:
I have a setup of spring boot OAuth for AuthServer and it is resposible for serving a number of few resource server for authentication using spring-security-jwt.
My problem is while authenticating I need to load the roles of a user but specific to the clientId.
eg: If user1 have roles ROLE_A, ROLE_B for client1 and ROLE_C, ROLE_D for client2, then when the user logins either using client1 or client2 he is able to see all the four roles ie. ROLE_A, ROLE_B, ROLE_C, ROLE_D because I am getting roles based on username.
If I need to have a role based on the client then I need clientId.
FYI,
I am using the authorization code flow for authentication.
I have seen similar question but that is based on password grant but I am trying on authorization code flow and that solution doesn't work for me.
Password grant question link

Below is my code where I need clientId

MyAuthenticationProvider.java

@Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        String userName = ((String) authentication.getPrincipal()).toLowerCase();
        String password = (String) authentication.getCredentials();
        String clientId = ? // how to get it
        ....
    }
}

MyUserDetailsService.java

@Override
    public UserDetails loadUserByUsername(String username) {
        String clientId = ? // how to get it
        ....
    }
}

Body:
You probably need to see OAuth2Authentication in Spring-security. When your client is authenticated by oauth2, then your "authentication" is actually instance of OAuth2Authentication that eventually implements Authentication.

If you see the implementation of OAuth2Authentication, it's done as below;

    public Object getPrincipal() {
       return this.userAuthentication == null ? this.storedRequest.getClientId() : this.userAuthentication
            .getPrincipal();
    }

so if request included "clientId', then you should be able to get clientId by calling getPrincipal() and typecasting to String as long as your request didn't include user authentication.

For your 2nd case, username is actually considered as clientId. You need to call in-memory, RDBMS, or whatever implementation that has clientId stored and returns ClientDetails. You'll be able to have some idea by looking into Spring security's ClientDetailsUserDetailsService class.


问:
Not set focus when come back screen manager with kivy and python
I want set the focus in textinput. at the begining the focus set correctly but when i go to the next screen and come back to initial screen the focus dont set correctly.

This is a app with a rfid lector, I want to read a code and select enter or exit

main.py

import kivy
kivy.require('1.10.0') # replace with your current kivy version !

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder

class MyScreenManager(ScreenManager):
    def __init__(self,**kwargs):
        super(MyScreenManager,self).__init__()

class Menu1(Screen):
    def __init__(self, **kwargs):
        super(Menu1, self).__init__()

class Menu2(Screen):
    def __init__(self, **kwargs):
        super(Menu2, self).__init__()

Builder.load_file("main.kv")

class Fichaje(App):
    def build(self):
        return MyScreenManager()

if __name__ == '__main__':
    Fichaje().run()

```

<p><strong>main.kv</strong></p>

```
#:kivy 1.10.0
#:import WipeTransition kivy.uix.screenmanager.WipeTransition

<MyScreenManager>:
    #transition: WipeTransition()
    Menu1:
        id: menu1
    Menu2:
        id: menu2

<Menu1>:
    name: "screen1"
    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: input1
            size_hint_y: .1
            multiline: False
            focus: True
            on_text_validate:
                root.manager.current = "screen2"

        BoxLayout:

<Menu2>:
    name: "screen2"
    BoxLayout:
        Button:
            text:"Entrada"
            on_press:
                root.manager.current = "screen1"

        Button:
            text:"Salida"
            on_press:
                root.manager.current = "screen1"
```

No error messages but the focus is not in the right site,
Thanks

I change the code to simplify the error

答:
In the example, there is not an attempt to change the focus. But I assume this was tried but it lost focus again.

The reason the text input looses focus again, is because it gets focused before the mouse or tap is released. The on_press method, is followed by on_release where the text input looses focus again.

To fix this you can just set the focus in the on_release method instead.

The quickest is to only add one line of code to the kv file and change on_press to on_release.

```<code>root.manager.get_screen("screen1").ids["input1"].focus
</code>```

This line can be different by using object property in screen1, for example. Or if you cannot use the on_release method, maybe use clock to schedule a focus in some amount of time, and if the touch is still down, reschedule it.

But here is the quick fix.

```<code><Menu2>:
    name: "screen2"
    BoxLayout:
        Button:
            text:"Entrada"
            on_release:
                root.manager.current = "screen1"
                root.manager.get_screen("screen1").ids["input1"].focus = True
</code>```

Body:
I want set the focus in textinput. at the begining the focus set correctly but when i go to the next screen and come back to initial screen the focus dont set correctly.

This is a app with a rfid lector, I want to read a code and select enter or exit

main.py

import kivy
kivy.require('1.10.0') # replace with your current kivy version !

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder

class MyScreenManager(ScreenManager):
    def __init__(self,**kwargs):
        super(MyScreenManager,self).__init__()

class Menu1(Screen):
    def __init__(self, **kwargs):
        super(Menu1, self).__init__()

class Menu2(Screen):
    def __init__(self, **kwargs):
        super(Menu2, self).__init__()

Builder.load_file("main.kv")

class Fichaje(App):
    def build(self):
        return MyScreenManager()

if __name__ == '__main__':
    Fichaje().run()

main.kv

#:kivy 1.10.0
#:import WipeTransition kivy.uix.screenmanager.WipeTransition

<MyScreenManager>:
    #transition: WipeTransition()
    Menu1:
        id: menu1
    Menu2:
        id: menu2

<Menu1>:
    name: "screen1"
    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: input1
            size_hint_y: .1
            multiline: False
            focus: True
            on_text_validate:
                root.manager.current = "screen2"

        BoxLayout:

<Menu2>:
    name: "screen2"
    BoxLayout:
        Button:
            text:"Entrada"
            on_press:
                root.manager.current = "screen1"

        Button:
            text:"Salida"
            on_press:
                root.manager.current = "screen1"

No error messages but the focus is not in the right site,
Thanks

I change the code to simplify the error

Body:
In the example, there is not an attempt to change the focus. But I assume this was tried but it lost focus again.

The reason the text input looses focus again, is because it gets focused before the mouse or tap is released. The on_press method, is followed by on_release where the text input looses focus again.

To fix this you can just set the focus in the on_release method instead.

The quickest is to only add one line of code to the kv file and change on_press to on_release.

root.manager.get_screen("screen1").ids["input1"].focus

This line can be different by using object property in screen1, for example. Or if you cannot use the on_release method, maybe use clock to schedule a focus in some amount of time, and if the touch is still down, reschedule it.

But here is the quick fix.

<Menu2>:
    name: "screen2"
    BoxLayout:
        Button:
            text:"Entrada"
            on_release:
                root.manager.current = "screen1"
                root.manager.get_screen("screen1").ids["input1"].focus = True


问:
Callins specific function depending on macro parameter in C
I have multiple functions with very similar identifiers (func1(), func2(), func3(), ...) and i need to create a macro to call them all in one.

i already tried to use concatenation but i couldn't figure it out.

void func1() {}
void func2() {}
void func3() {}

#define call(N) // here needs to go the code to call the N func like func#N()
```

<p>so that later in the code i can do something like this:</p>

<pre class="lang-c prettyprint-override"><code>int main()
{
    for(int i = 0; i < 3; i++)
        call(i);
}
</code>```

if there are other methods that i don't know or you can do it in another way show me your ideas. if possible i'd like to stick with macros

答:
If N is guaranteed to be a digit 1, 2, or 3, one could use

```<code>#define call(N) func##N()
</code>```

but that could fail if N might have other forms.  If the only other possibility that needed to be accounted for would be that N could be a macro that would expand to a single digit, one could use:

```<code>#define do_call(N) func##N()
#define call(N) do_call(N)
</code>```

Alternatively, one could allow for N being computed in arbitrary fashion if the code were written as:

```<code>void (*const funcs[3])(void) = {func1, func2, func3};

void call(int n)
{
    funcs[n-1]();
}
</code>```

If the functions return a value or take parameters, replace the leading void with the return type and/or replace (void) with a parameter list.  This approach would work even if the value N is a complex expression or may not be known until runtime.

Body:
I have multiple functions with very similar identifiers (func1(), func2(), func3(), ...) and i need to create a macro to call them all in one.

i already tried to use concatenation but i couldn't figure it out.

void func1() {}
void func2() {}
void func3() {}

#define call(N) // here needs to go the code to call the N func like func#N()

so that later in the code i can do something like this:

int main()
{
    for(int i = 0; i < 3; i++)
        call(i);
}

if there are other methods that i don't know or you can do it in another way show me your ideas. if possible i'd like to stick with macros

Body:
If N is guaranteed to be a digit 1, 2, or 3, one could use

#define call(N) func##N()

but that could fail if N might have other forms.  If the only other possibility that needed to be accounted for would be that N could be a macro that would expand to a single digit, one could use:

#define do_call(N) func##N()
#define call(N) do_call(N)

Alternatively, one could allow for N being computed in arbitrary fashion if the code were written as:

void (*const funcs[3])(void) = {func1, func2, func3};

void call(int n)
{
    funcs[n-1]();
}

If the functions return a value or take parameters, replace the leading void with the return type and/or replace (void) with a parameter list.  This approach would work even if the value N is a complex expression or may not be known until runtime.


问:
View sent message on Firebase console
This is my first time using firebase. I am integrating Firebase Cloud Message with a node.js server and an Android client. When I push the messages to the server, the response is that the message went to the firebase server successfully.

But when I go to the firebase console, I don't see my message there and also my android device does not receive the message. I am sending the messages as topics and the android device has also subscribed to the topics.

I will be glad if someone can share a link to view the messages on the server or suggest what I am missing out.

Below is a sample response:
Message sent to Firebase for delivery, response:
{
  "name": "projects/my-project-id/messages/7660010658785245660"
}

Below is the code that I am using to push to the server

```<code>let admin       =   require('firebase-admin'),
    serviceAccount = require('the link to my service account is here'),
    fcmObj = {};

    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount)
      });

    fcmObj.sendMsg = function(){

      let options = {
        priority: "high",
        timeToLive: 60 * 60 *24
      },

      message = {
        data: {
          content: 'Hello.. we are testing our api and fcm.',
          sender: 'From Server'
        },
        topic: "News"
      };

// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message, options)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', JSON.stringify(response));
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });
}

module.exports = fcmObj;
</code>```

答:
Below is a sample response: Message sent to Firebase for delivery, response: { "name": "projects/my-project-id/messages/7660010658785245660" }

Means that your Firebase SDK is is sending the message successfully. (i.e. credentials are configured properly and SDK is initialised successfully.)

In your code, you've defined data( payload is optional, see documentation here: https://firebase.google.com/docs/cloud-messaging/concept-options#notification-messages-with-optional-data-payload), to display the notification message you need to add a notification object.

Just add following object in your message object and it should work then:

```<code>"notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    },
</code>```

Title: View sent message on Firebase console

Body:
This is my first time using firebase. I am integrating Firebase Cloud Message with a node.js server and an Android client. When I push the messages to the server, the response is that the message went to the firebase server successfully.

But when I go to the firebase console, I don't see my message there and also my android device does not receive the message. I am sending the messages as topics and the android device has also subscribed to the topics.

I will be glad if someone can share a link to view the messages on the server or suggest what I am missing out.

Below is a sample response:
Message sent to Firebase for delivery, response:
{
  "name": "projects/my-project-id/messages/7660010658785245660"
}

Below is the code that I am using to push to the server

let admin       =   require('firebase-admin'),
    serviceAccount = require('the link to my service account is here'),
    fcmObj = {};

    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount)
      });

    fcmObj.sendMsg = function(){

      let options = {
        priority: "high",
        timeToLive: 60 * 60 *24
      },

      message = {
        data: {
          content: 'Hello.. we are testing our api and fcm.',
          sender: 'From Server'
        },
        topic: "News"
      };

// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message, options)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', JSON.stringify(response));
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });
}

module.exports = fcmObj;

Body:
Below is a sample response: Message sent to Firebase for delivery, response: { "name": "projects/my-project-id/messages/7660010658785245660" }

Means that your Firebase SDK is is sending the message successfully. (i.e. credentials are configured properly and SDK is initialised successfully.)

In your code, you've defined data( payload is optional, see documentation here: https://firebase.google.com/docs/cloud-messaging/concept-options#notification-messages-with-optional-data-payload), to display the notification message you need to add a notification object.

Just add following object in your message object and it should work then:

"notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    },


问:
Modal component renders Twice on open
I'm using react-spring to animate a Modal based on @reach/dialog. The Modal can have any children. In the children I'm fetching some data based on some prop.

The problem is that the fetch call is made two times on opening the modal. I think it has probably to do with how I'm managing the state and that is causing re-renders.

I'v tried memoizing the children inside the modal and it didn't work, so I think that the problem is outside of the Modal component.

Here is something close to my code and how it is working  https://codesandbox.io/s/loving-liskov-1xouh

EDIT: I already know that if I remove the react-spring animation the double rendering doesn't happen, but I want to try keeping the animation intact.

Do you think you can help me to identify where is the bug? (Also some tips on good practice with hooks are highly appreciated).

答:
The problem is, that at the end of the animation AnotherComponent remounts. I read similar problems about react-spring. One way could be, that you lift out the state from AnotherComponent to the index.js. This way the state will not lost at remount and you can prevent refetching the data.

```<code>const AnotherComponent = ({ url, todo, setTodo }) => {
  useEffect(() => {
    if (todo.length === 0) {
      axios.get(url).then(res => setTodo(res.data));
    }
  });
....
}
</code>```

Here is my version: https://codesandbox.io/s/quiet-pond-idyee

Title: Modal component renders Twice on open

Body:
The problem is, that at the end of the animation AnotherComponent remounts. I read similar problems about react-spring. One way could be, that you lift out the state from AnotherComponent to the index.js. This way the state will not lost at remount and you can prevent refetching the data.

const AnotherComponent = ({ url, todo, setTodo }) => {
  useEffect(() => {
    if (todo.length === 0) {
      axios.get(url).then(res => setTodo(res.data));
    }
  });
....
}

Here is my version: https://codesandbox.io/s/quiet-pond-idyee