问:
Trouble downloading file from Gdrive : 403 forbidden error
I have a website with google drive file picker feature, which lets user's select file from the Gdrive account and upload to my website.

This functionality was working fine but suddenly it stopped working from last 3-4 days and I am getting error "403 Forbidden : client do not have permission".
Can someone please advice what can be the issue ?

答:
It seems that the issue you are encountering is mostly due to the fact that you're not using a valid access token for your operation.

The 403 Forbidden client error response code indicates that the server understood the request but refuses to authorize it.

Solution

Identify the access scopes

In order to get the appropriate access token, you should compare the scopes included in the access token response to the scopes required to access the features and functionality of your application dependent upon the Drive API.

If you have recently changed your scopes for your application, you will need to get a new access token which will correspond to the new scopes you have used.

Declaring multiple scopes can be done like this:

```<code>string[] scopes = new string[] { DriveService.Scope.DriveAppsReadonly,
                                 DriveService.Scope.DriveAppdata,
                                 ...
};
</code>```

Refresh your access token

According to the Using OAuth 2.0 to Access Google APIs documentation:

Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.

So, in order to still be able to perform all the operations as you did before, you will need to refresh your access token.

Reference

Using OAuth 2.0 to Access Google APIs;

Drive v2.

Body:
It seems that the issue you are encountering is mostly due to the fact that you're not using a valid access token for your operation.

The 403 Forbidden client error response code indicates that the server understood the request but refuses to authorize it.

Solution

Identify the access scopes

In order to get the appropriate access token, you should compare the scopes included in the access token response to the scopes required to access the features and functionality of your application dependent upon the Drive API.

If you have recently changed your scopes for your application, you will need to get a new access token which will correspond to the new scopes you have used.

Declaring multiple scopes can be done like this:

string[] scopes = new string[] { DriveService.Scope.DriveAppsReadonly,
                                 DriveService.Scope.DriveAppdata,
                                 ...
};

Refresh your access token

According to the Using OAuth 2.0 to Access Google APIs documentation:

Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.

So, in order to still be able to perform all the operations as you did before, you will need to refresh your access token.

Reference

Using OAuth 2.0 to Access Google APIs;

Drive v2.


来源: stackexchange

问:
Typescript save object to server and keep metadata
In an Angular app, I have an object with some metadata on it's properties using Reflect.defineMetadata(). I need to save this object on the server and parse it back keeping my metadata.
JSON.parse() and JSON.stringify() loose this data. How can I do this?

答:
Instead of sending data to server. Try to get the data itself from server. So you use restangular directly fetch that data with an URL. Use window.localStorage.setItem('Data', JSON.stringify(data));

Use Data by var t= JSON.parse(localStorage.getItem('Data')) anywhere in app. Thats how you are supposed to do it.

Replicate same scenario if you want to use APP to send data to server. Handle at server side. Send from server using above way

ContentLicense: CC BY-SA 4.0


问:
Java - Why is the whitespace being read in as a word?
I am attempting to read in a .txt file and print out the top twenty most common words and the top twenty least common words. However, whitespace appears as a word when it should not be counted as one. As I show in the Output, the whitespace appears as the second most common word, when it should not.
Here is my code.

```<code>public class WordFreqCount {

    public static void main(String[] args) throws IOException {

        HashMap<String, Integer> frequencyMap = new HashMap<String, Integer>();

        FileReader bookFile = new FileReader("book.txt");
        Scanner s = new Scanner(new FileReader("book.txt"));

        while(s.hasNext()) {
            String line = s.nextLine();
            line.trim();
            String[] words = line.split("\\W+");
            for (int i = 0; i < words.length; i ++) {

                if (frequencyMap.containsKey(words[i])) {
                    frequencyMap.replace(words[i], frequencyMap.get(words[i]) + 1);
                }
                else {
                    frequencyMap.put(words[i], 1);
                }
            }
        }
        s.close();

        List<Entry<String,Integer>> list = sortByValue(frequencyMap);

        System.out.println("Top 20 Most Appeared Words:");

        int counter1 = 1;
        List<Map.Entry<String, Integer>> topTwenty = list.subList(0, 20);
        for(Map.Entry<String, Integer> word : topTwenty) {
            System.out.println("(" + counter1 + "): " + word.getKey() + " --> " + word.getValue());
            counter1 += 1;
        }

        System.out.println();
        System.out.println("Top 20 Least Appeared Words:");

        int counter2 = 1;
        Collections.reverse(list);
        List<Map.Entry<String, Integer>> bottomTwenty = list.subList(0, 20);
        for(Map.Entry<String, Integer> word : bottomTwenty) {
            System.out.println("(" + counter2 + "): " + word.getKey() + " --> " + word.getValue());
            counter2 += 1;
        }
    }
}
</code>```

And the Output of my code is

```<code>(1): the --> 5426
(2):  --> 4986
(3): I --> 3038
(4): and --> 2887
(5): to --> 2788
(6): of --> 2733
(7): a --> 2595
(8): in --> 1747
(9): that --> 1664
(10): was --> 1393
(11): it --> 1303
(12): you --> 1283
(13): he --> 1168
(14): is --> 1131
(15): his --> 1103
(16): have --> 908
(17): my --> 907
(18): with --> 849
(19): had --> 821
(20): as --> 780

Top 20 Least Appeared Words:
(1): rival --> 1
(2): category --> 1
(3): arguments --> 1
(4): Bought --> 1
(5): billycock --> 1
(6): incoherent --> 1
(7): hail --> 1
(8): idle --> 1
(9): illustrious --> 1
(10): terminated --> 1
(11): Apaches --> 1
(12): topped --> 1
(13): laudanum --> 1
(14): filthy --> 1
(15): drama --> 1
(16): tune --> 1
(17): geology --> 1
(18): Mademoiselle --> 1
(19): balls --> 1
(20): Atkinson --> 1
</code>```

It was my understanding that using line.split("\W+") would parse the sentences to make sure nothing like whitespace, commas, etc. were counted in as words or within words. Am I missing something here?

A small portion of book.txt file

===========================================================================

```<code>almost no restrictions whatsoever.  You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.net

Title: The Adventures of Sherlock Holmes

Author: Arthur Conan Doyle

Posting Date: April 18, 2011 [EBook #1661]
First Posted: November 29, 2002

Language: English

*** START OF THIS PROJECT GUTENBERG EBOOK THE ADVENTURES OF SHERLOCK HOLMES ***

Produced by an anonymous Project Gutenberg volunteer and Jose Menendez

THE ADVENTURES OF SHERLOCK HOLMES

by

SIR ARTHUR CONAN DOYLE

   I. A Scandal in Bohemia
  II. The Red-headed League
 III. A Case of Identity
  IV. The Boscombe Valley Mystery
   V. The Five Orange Pips
  VI. The Man with the Twisted Lip
 VII. The Adventure of the Blue Carbuncle
VIII. The Adventure of the Speckled Band
  IX. The Adventure of the Engineer's Thumb
   X. The Adventure of the Noble Bachelor
  XI. The Adventure of the Beryl Coronet
 XII. The Adventure of the Copper Beeches

ADVENTURE I. A SCANDAL IN BOHEMIA

I.

To Sherlock Holmes she is always THE woman. I have seldom heard
him mention her under any other name. In his eyes she eclipses
and predominates the whole of her sex. It was not that he felt
any emotion akin to love for Irene Adler. All emotions, and that
one particularly, were abhorrent to his cold, precise but
admirably balanced mind. He was, I take it, the most perfect
reasoning and observing machine that the world has seen, but as a
lover he would have placed himself in a false position. He never
spoke of the softer passions, save with a gibe and a sneer. They
were admirable things for the observer--excellent for drawing the
veil from men's motives and actions. But for the trained reasoner
to admit such intrusions into his own delicate and finely
adjusted temperament was to introduce a distracting factor which
might throw a doubt upon all his mental results. Grit in a
sensitive instrument, or a crack in one of his own high-power
lenses, would not be more disturbing than a strong emotion in a
nature such as his. And yet there was but one woman to him, and
that woman was the late Irene Adler, of dubious and questionable
memory.

I had seen little of Holmes lately. My marriage had drifted us
away from each other. My own complete happiness, and the
home-centred interests which rise up around the man who first
finds himself master of his own establishment, were sufficient to
absorb all my attention, while Holmes, who loathed every form of
society with his whole Bohemian soul, remained in our lodgings in
Baker Street, buried among his old books, and alternating from
week to week between cocaine and ambition, the drowsiness of the
drug, and the fierce energy of his own keen nature. He was still,
as ever, deeply attracted by the study of crime, and occupied his
immense faculties and extraordinary powers of observation in
following out those clues, and clearing up those mysteries which
had been abandoned as hopeless by the official police. From time
to time I heard some vague account of his doings: of his summons
to Odessa in the case of the Trepoff murder, of his clearing up
of the singular tragedy of the Atkinson brothers at Trincomalee,
and finally of the mission which he had accomplished so
delicately and successfully for the reigning family of Holland.
Beyond these signs of his activity, however, which I merely
shared with all the readers of the daily press, I knew little of
my former friend and companion.```

```

答:
During debugging I found other lines than the blank ones, that gave issues:

" I. A Scandal in Bohemia.."

"*** START...".

An if (words[i].length() == 0) continue; will be a one size fits all, if placed in the beginning of your for loop. However, you can create your words by first removing unwanted characters, then trimming white spaces, and finally replacing unwanted empty lines with a null-terminator:

```<code>String[] words = line.replaceAll("\\p{Punct}","")  // punctuation
                     .trim()                       // needed as per both issues above
                     .replaceAll("^$","\0")        // terminate the string it it's empty
                     .split("\\W+");
</code>```

Body:
I am attempting to read in a .txt file and print out the top twenty most common words and the top twenty least common words. However, whitespace appears as a word when it should not be counted as one. As I show in the Output, the whitespace appears as the second most common word, when it should not.
Here is my code.

public class WordFreqCount {

    public static void main(String[] args) throws IOException {

        HashMap<String, Integer> frequencyMap = new HashMap<String, Integer>();

        FileReader bookFile = new FileReader("book.txt");
        Scanner s = new Scanner(new FileReader("book.txt"));

        while(s.hasNext()) {
            String line = s.nextLine();
            line.trim();
            String[] words = line.split("\\W+");
            for (int i = 0; i < words.length; i ++) {

                if (frequencyMap.containsKey(words[i])) {
                    frequencyMap.replace(words[i], frequencyMap.get(words[i]) + 1);
                }
                else {
                    frequencyMap.put(words[i], 1);
                }
            }
        }
        s.close();

        List<Entry<String,Integer>> list = sortByValue(frequencyMap);

        System.out.println("Top 20 Most Appeared Words:");

        int counter1 = 1;
        List<Map.Entry<String, Integer>> topTwenty = list.subList(0, 20);
        for(Map.Entry<String, Integer> word : topTwenty) {
            System.out.println("(" + counter1 + "): " + word.getKey() + " --> " + word.getValue());
            counter1 += 1;
        }

        System.out.println();
        System.out.println("Top 20 Least Appeared Words:");

        int counter2 = 1;
        Collections.reverse(list);
        List<Map.Entry<String, Integer>> bottomTwenty = list.subList(0, 20);
        for(Map.Entry<String, Integer> word : bottomTwenty) {
            System.out.println("(" + counter2 + "): " + word.getKey() + " --> " + word.getValue());
            counter2 += 1;
        }
    }
}

And the Output of my code is

(1): the --> 5426
(2):  --> 4986
(3): I --> 3038
(4): and --> 2887
(5): to --> 2788
(6): of --> 2733
(7): a --> 2595
(8): in --> 1747
(9): that --> 1664
(10): was --> 1393
(11): it --> 1303
(12): you --> 1283
(13): he --> 1168
(14): is --> 1131
(15): his --> 1103
(16): have --> 908
(17): my --> 907
(18): with --> 849
(19): had --> 821
(20): as --> 780

Top 20 Least Appeared Words:
(1): rival --> 1
(2): category --> 1
(3): arguments --> 1
(4): Bought --> 1
(5): billycock --> 1
(6): incoherent --> 1
(7): hail --> 1
(8): idle --> 1
(9): illustrious --> 1
(10): terminated --> 1
(11): Apaches --> 1
(12): topped --> 1
(13): laudanum --> 1
(14): filthy --> 1
(15): drama --> 1
(16): tune --> 1
(17): geology --> 1
(18): Mademoiselle --> 1
(19): balls --> 1
(20): Atkinson --> 1

It was my understanding that using line.split("\W+") would parse the sentences to make sure nothing like whitespace, commas, etc. were counted in as words or within words. Am I missing something here?

A small portion of book.txt file

===========================================================================

almost no restrictions whatsoever.  You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.net

Title: The Adventures of Sherlock Holmes

Author: Arthur Conan Doyle

Posting Date: April 18, 2011 [EBook #1661]
First Posted: November 29, 2002

Language: English

*** START OF THIS PROJECT GUTENBERG EBOOK THE ADVENTURES OF SHERLOCK HOLMES ***

Produced by an anonymous Project Gutenberg volunteer and Jose Menendez

THE ADVENTURES OF SHERLOCK HOLMES

by

SIR ARTHUR CONAN DOYLE

   I. A Scandal in Bohemia
  II. The Red-headed League
 III. A Case of Identity
  IV. The Boscombe Valley Mystery
   V. The Five Orange Pips
  VI. The Man with the Twisted Lip
 VII. The Adventure of the Blue Carbuncle
VIII. The Adventure of the Speckled Band
  IX. The Adventure of the Engineer's Thumb
   X. The Adventure of the Noble Bachelor
  XI. The Adventure of the Beryl Coronet
 XII. The Adventure of the Copper Beeches

ADVENTURE I. A SCANDAL IN BOHEMIA

I.

To Sherlock Holmes she is always THE woman. I have seldom heard
him mention her under any other name. In his eyes she eclipses
and predominates the whole of her sex. It was not that he felt
any emotion akin to love for Irene Adler. All emotions, and that
one particularly, were abhorrent to his cold, precise but
admirably balanced mind. He was, I take it, the most perfect
reasoning and observing machine that the world has seen, but as a
lover he would have placed himself in a false position. He never
spoke of the softer passions, save with a gibe and a sneer. They
were admirable things for the observer--excellent for drawing the
veil from men's motives and actions. But for the trained reasoner
to admit such intrusions into his own delicate and finely
adjusted temperament was to introduce a distracting factor which
might throw a doubt upon all his mental results. Grit in a
sensitive instrument, or a crack in one of his own high-power
lenses, would not be more disturbing than a strong emotion in a
nature such as his. And yet there was but one woman to him, and
that woman was the late Irene Adler, of dubious and questionable
memory.

I had seen little of Holmes lately. My marriage had drifted us
away from each other. My own complete happiness, and the
home-centred interests which rise up around the man who first
finds himself master of his own establishment, were sufficient to
absorb all my attention, while Holmes, who loathed every form of
society with his whole Bohemian soul, remained in our lodgings in
Baker Street, buried among his old books, and alternating from
week to week between cocaine and ambition, the drowsiness of the
drug, and the fierce energy of his own keen nature. He was still,
as ever, deeply attracted by the study of crime, and occupied his
immense faculties and extraordinary powers of observation in
following out those clues, and clearing up those mysteries which
had been abandoned as hopeless by the official police. From time
to time I heard some vague account of his doings: of his summons
to Odessa in the case of the Trepoff murder, of his clearing up
of the singular tragedy of the Atkinson brothers at Trincomalee,
and finally of the mission which he had accomplished so
delicately and successfully for the reigning family of Holland.
Beyond these signs of his activity, however, which I merely
shared with all the readers of the daily press, I knew little of
my former friend and companion.```

Body:
During debugging I found other lines than the blank ones, that gave issues:

" I. A Scandal in Bohemia.."

"*** START...".

An if (words[i].length() == 0) continue; will be a one size fits all, if placed in the beginning of your for loop. However, you can create your words by first removing unwanted characters, then trimming white spaces, and finally replacing unwanted empty lines with a null-terminator:

String[] words = line.replaceAll("\\p{Punct}","")  // punctuation
                     .trim()                       // needed as per both issues above
                     .replaceAll("^$","\0")        // terminate the string it it's empty
                     .split("\\W+");


问:
iis invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
I'm currently trying to add another table in here "dbo.ARTICLE_INCARNATION.article_incarnation_id", but I keep getting the error:

iis invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

I have tried what i know to fix it but no progress.

```<code>SELECT
'Summary',SUM( OBJ#CAB.object_qty) AS 'Sum est, OBW exist',
    AIN.article_incarnation_long_no AS 'Article no',
    AIN.article_incarnation_name AS 'Article name',

    SUM( OBJ#CAB.object_qty) AS 'Sum est, OBW exist',
    (SELECT
  isnull(sum(POI.purchase_order_item_qty_po),0)
 FROM
   [dbo].[PURCHASE_ORDER_ITEM] POI
WHERE
  POI.article_incarnation_id = AIN.article_incarnation_id
  AND POI.purchase_order_id IS NOT NULL),
    (SELECT sum(isnull(stock_object_qty_qty,0)) FROM [dbo].[STOCK_OBJECT_QTY] S  WHERE S.article_incarnation_id = OBJ#CAB.article_incarnation_id) AS 'Total on stock'
    /*AS 'Manko'
    AS 'PO',
    AS 'Not deliverd PO'*/
--skalmed

FROM

    OBJECT OBJ#CAB
    JOIN OBJECT_TYPE OTY#CAB ON OTY#CAB.object_type_id = OBJ#CAB.object_type_id
    AND OTY#CAB.object_type_no = 'CABLE'
    JOIN [dbo].[ARTICLE_INCARNATION] AIN ON OBJ#CAB.article_incarnation_id = AIN.article_incarnation_id
    AND AIN.article_unit_no = 'M'
    JOIN OBJECT_WORK OBW#CAB ON OBW#CAB.object_id = OBJ#CAB.object_id
    AND OBW#CAB.work_type_no IN ('EPU', 'EPA', 'IPA', 'XEPU', 'LI5', 'LE5')
    AND OBW#CAB.object_work_installed_qty IS NULL
GROUP BY
    AIN.article_incarnation_long_no,
    AIN.article_incarnation_name,
    ARTICLE_INCARNATION.article_incarnation_id,
    OBJ#CAB.article_incarnation_id
</code>```

答:
You have same table name but schemas are different that cause the problem. :

```<code>ARTICLE_INCARNATION.article_incarnation_id
</code>```

AND

```<code>[dbo].[ARTICLE_INCARNATION]
</code>```

Choose which one you want to aggregate or display. If you want both then define proper alias.

Body:
I'm currently trying to add another table in here "dbo.ARTICLE_INCARNATION.article_incarnation_id", but I keep getting the error:

iis invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

I have tried what i know to fix it but no progress.

SELECT
'Summary',SUM( OBJ#CAB.object_qty) AS 'Sum est, OBW exist',
    AIN.article_incarnation_long_no AS 'Article no',
    AIN.article_incarnation_name AS 'Article name',

    SUM( OBJ#CAB.object_qty) AS 'Sum est, OBW exist',
    (SELECT
  isnull(sum(POI.purchase_order_item_qty_po),0)
 FROM
   [dbo].[PURCHASE_ORDER_ITEM] POI
WHERE
  POI.article_incarnation_id = AIN.article_incarnation_id
  AND POI.purchase_order_id IS NOT NULL),
    (SELECT sum(isnull(stock_object_qty_qty,0)) FROM [dbo].[STOCK_OBJECT_QTY] S  WHERE S.article_incarnation_id = OBJ#CAB.article_incarnation_id) AS 'Total on stock'
    /*AS 'Manko'
    AS 'PO',
    AS 'Not deliverd PO'*/
--skalmed

FROM

    OBJECT OBJ#CAB
    JOIN OBJECT_TYPE OTY#CAB ON OTY#CAB.object_type_id = OBJ#CAB.object_type_id
    AND OTY#CAB.object_type_no = 'CABLE'
    JOIN [dbo].[ARTICLE_INCARNATION] AIN ON OBJ#CAB.article_incarnation_id = AIN.article_incarnation_id
    AND AIN.article_unit_no = 'M'
    JOIN OBJECT_WORK OBW#CAB ON OBW#CAB.object_id = OBJ#CAB.object_id
    AND OBW#CAB.work_type_no IN ('EPU', 'EPA', 'IPA', 'XEPU', 'LI5', 'LE5')
    AND OBW#CAB.object_work_installed_qty IS NULL
GROUP BY
    AIN.article_incarnation_long_no,
    AIN.article_incarnation_name,
    ARTICLE_INCARNATION.article_incarnation_id,
    OBJ#CAB.article_incarnation_id

Body:
You have same table name but schemas are different that cause the problem. :

ARTICLE_INCARNATION.article_incarnation_id

AND

[dbo].[ARTICLE_INCARNATION]

Choose which one you want to aggregate or display. If you want both then define proper alias.


问:
How to solve this Error: Cannot find module 'ibm-watson'
I have installed ibm-watson using "npm install ibm-watson" command
I can see the folder and its file in the node_modules folder, but still showing this error.
Node version - v10.15.3

```<code>const watson = require('ibm-watson');
const { IamAuthenticator } = require('ibm-watson/auth');
const { BasicAuthenticator } = require('ibm-watson/auth');

// to get an IAM Access Token
const authorization = new watson.AuthorizationV1({
  authenticator: new IamAuthenticator({ apikey: 'fakekey-1234' }),
});

authorization.getToken(function (err, token) {
  if (!token) {
    console.log('error: ', err);
  } else {
    // Use your token here
  }
});
</code>```

Other modules are importing fine, Only this module not importing.

```<code>internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module 'ibm-watson'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous>
</code>```

答:
I faced the same problem.

After reading the code, I understood.

There is only sdk.ts file, not index.ts  file.

https://github.com/watson-developer-cloud/node-sdk

```<code>// const watson = require('ibm-watson');
const watson = require('ibm-watson/sdk');
</code>```

But I still got the error.

Eventually it worked if I wrote the following

```<code>import AuthorizationV1 from 'ibm-watson/authorization/v1'
import { IamAuthenticator } from 'ibm-watson/auth'

const apikey = '********'
const authorization = new AuthorizationV1({
  url: 'https://iam.cloud.ibm.com/identity/token',
  authenticator: new IamAuthenticator({ apikey }),
})

authorization.getToken(function (err, token) {
  if (!token) {
    console.log('error: ', err);
  } else {
    // Use your token here
  }
});
</code>```

But there is a CORS problem. I don't know any more.

The answer was written here. I need to do it on the server side

https://github.com/watson-developer-cloud/node-sdk/issues/884#issuecomment-515050023

Body:
I have installed ibm-watson using "npm install ibm-watson" command
I can see the folder and its file in the node_modules folder, but still showing this error.
Node version - v10.15.3

const watson = require('ibm-watson');
const { IamAuthenticator } = require('ibm-watson/auth');
const { BasicAuthenticator } = require('ibm-watson/auth');

// to get an IAM Access Token
const authorization = new watson.AuthorizationV1({
  authenticator: new IamAuthenticator({ apikey: 'fakekey-1234' }),
});

authorization.getToken(function (err, token) {
  if (!token) {
    console.log('error: ', err);
  } else {
    // Use your token here
  }
});

Other modules are importing fine, Only this module not importing.

internal/modules/cjs/loader.js:584
    throw err;
    ^

Error: Cannot find module 'ibm-watson'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous>

Body:
I faced the same problem.

After reading the code, I understood.

There is only sdk.ts file, not index.ts  file.

https://github.com/watson-developer-cloud/node-sdk

// const watson = require('ibm-watson');
const watson = require('ibm-watson/sdk');

But I still got the error.

Eventually it worked if I wrote the following

import AuthorizationV1 from 'ibm-watson/authorization/v1'
import { IamAuthenticator } from 'ibm-watson/auth'

const apikey = '********'
const authorization = new AuthorizationV1({
  url: 'https://iam.cloud.ibm.com/identity/token',
  authenticator: new IamAuthenticator({ apikey }),
})

authorization.getToken(function (err, token) {
  if (!token) {
    console.log('error: ', err);
  } else {
    // Use your token here
  }
});

But there is a CORS problem. I don't know any more.

The answer was written here. I need to do it on the server side

https://github.com/watson-developer-cloud/node-sdk/issues/884#issuecomment-515050023


问:
not getting result as expected with fetch_object() in while loop
i m working on a project where i display some images uploaded by user and it is fetched from DB table with fetch_object() method, this is my code:

```<code><?php
     $ph1 = $media->fetch_assoc();
     echo "testarray";
     print_r($ph1);
     while ($photo = $media->fetch_object()) { ?>
          <li>
              <div class="gallery-item">
                   <a href="<?= $system->getDomain() ?>/uploads/<?= $photo->path ?>" data-fancybox="gallery">
                      <img src="<?= $system->getDomain() ?>/uploads/<?= $photo->path ?>" alt="User Uploaded Photos" />
                   </a>
               </div>
           </li>
<?php } ?>
</code>```

here $media is my result object from query.

the problem with my code is that, while loop starts iterating from 2nd row and skipping 1st. So, my image gallery shows all images except the latest uploaded image to server. I also test that this while loop skipping the 1st is because $photo variable is getting all entries except the 1st(or latest), I also test that both fetch_assoc() and fetch_object() gives the same result i.e. one row less and when i check number of rows returned from query with $media->num-rows it returns the exact number of rows that a user uploads. I just cant find why i m not getting first rows ??

答:
You're fetching the first result and not using it

When you run fetch_assoc() you are fetching the first result.

```<code>$media->fetch_assoc();
</code>```

Once the result has been fetched, it won't be fetched again, so when you loop through $media that result is no longer available, nor is it ever used.

Remove the following code and you won't skip the first iteration:

```<code>$ph1 = $media->fetch_assoc();
echo "testarray";
print_r($ph1);
</code>```

Body:
i m working on a project where i display some images uploaded by user and it is fetched from DB table with fetch_object() method, this is my code:

<?php
     $ph1 = $media->fetch_assoc();
     echo "testarray";
     print_r($ph1);
     while ($photo = $media->fetch_object()) { ?>

                   <a href="<?= $system->getDomain() ?>/uploads/<?= $photo->path ?>" data-fancybox="gallery">
                      <img src="<?= $system->getDomain() ?>/uploads/<?= $photo->path ?>" alt="User Uploaded Photos" />

<?php } ?>

here $media is my result object from query.

the problem with my code is that, while loop starts iterating from 2nd row and skipping 1st. So, my image gallery shows all images except the latest uploaded image to server. I also test that this while loop skipping the 1st is because $photo variable is getting all entries except the 1st(or latest), I also test that both fetch_assoc() and fetch_object() gives the same result i.e. one row less and when i check number of rows returned from query with $media->num-rows it returns the exact number of rows that a user uploads. I just cant find why i m not getting first rows ??

Body:
You're fetching the first result and not using it

When you run fetch_assoc() you are fetching the first result.

$media->fetch_assoc();

Once the result has been fetched, it won't be fetched again, so when you loop through $media that result is no longer available, nor is it ever used.

Remove the following code and you won't skip the first iteration:

$ph1 = $media->fetch_assoc();
echo "testarray";
print_r($ph1);


问:
How to split comma separated values in single cell to different columns in google sheet using GScript?
Have the above data in single cell of google sheet sheet1. Need to bring it to individual col's in sheet2.

```<code>categories: ScreenGuard item_meta: {'Brand': 'Lenovo', 'Series': 'Z', 'Model': '7r883', 'Length (mm)': '134', 'Width (mm)': '132', 'Total Area (sq mm)': '17688', '_measurement_data': '{"length":"{\\"value\\":\\"134\\",\\"unit\\":\\"mm\\"}","width":"{\\"value\\":\\"132\\",\\"unit\\":\\"mm\\"}","_measurement_needed":"17688","_measurement_needed_unit":"sq mm"}'} line_subtotal: 176.88 line_subtotal_tax: 0.00 line_tax: 0.00 line_total: 176.88 name: Screen Guard product_id: 10 quantity: 1 sku:  tags:  tax_class:  type: simple unit_price: 176.88 variation_id: 0
</code>```

this can repeat in the same cell ref the sheet for more examples

https://docs.google.com/spreadsheets/d/1NTqAi361vmaVQhgjWhs0y7oEZcb7K09W9unEE12nOkI/edit?usp=sharing

need Brand,Series,Model,Length, Width values in next sheet. Can this be achieved using formulas?

答:
Something like this as a first step?

```<code>function vanDikHoutZaagtMenPlanken(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = ss.getSheetByName("sheet1");
  var cellValue = sheet.getRange("A3").getValue();

  var arrayItems = [];
  var hlpItems = cellValue.split(/item_meta: /g);

  for(var i=1;i<hlpItems.length;i++){

    var item = hlpItems[i].split(/, 'Total Area/)[0].split(/, 'Total Area/)[0].replace(/'/g,'"')+ '}';
    item = JSON.parse(item);
    arrayItems.push(item);

  }

  //Edit -> Looping through the result to get every value needed

  for (var i = 0; i < arrayItems.length ; i++) {

    Logger.log(arrayItems[i])
    Logger.log(arrayItems[i].Brand)
    Logger.log(arrayItems[i].Series)
    Logger.log(arrayItems[i].Model)
    Logger.log(arrayItems[i]['Length (mm)'])
    Logger.log(arrayItems[i]['Width (mm)'])
    Logger.log("================================")

    // This is an example on how to set a value to the sheet2

    ss.getSheetByName("sheet2").getRange('B5').setValue(arrayItems[i].Brand);

  }

}
</code>```

Check the following links to see how to use:

getRange(a1Notation): To get the cells you need to work with.

getLastRow(): Returns the position of the last row that has content.

setValue(value): To set a value to a cell.

Body:
Have the above data in single cell of google sheet sheet1. Need to bring it to individual col's in sheet2.

categories: ScreenGuard item_meta: {'Brand': 'Lenovo', 'Series': 'Z', 'Model': '7r883', 'Length (mm)': '134', 'Width (mm)': '132', 'Total Area (sq mm)': '17688', '_measurement_data': '{"length":"{\\"value\\":\\"134\\",\\"unit\\":\\"mm\\"}","width":"{\\"value\\":\\"132\\",\\"unit\\":\\"mm\\"}","_measurement_needed":"17688","_measurement_needed_unit":"sq mm"}'} line_subtotal: 176.88 line_subtotal_tax: 0.00 line_tax: 0.00 line_total: 176.88 name: Screen Guard product_id: 10 quantity: 1 sku:  tags:  tax_class:  type: simple unit_price: 176.88 variation_id: 0

this can repeat in the same cell ref the sheet for more examples

https://docs.google.com/spreadsheets/d/1NTqAi361vmaVQhgjWhs0y7oEZcb7K09W9unEE12nOkI/edit?usp=sharing

need Brand,Series,Model,Length, Width values in next sheet. Can this be achieved using formulas?

Body:
Something like this as a first step?

function vanDikHoutZaagtMenPlanken(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = ss.getSheetByName("sheet1");
  var cellValue = sheet.getRange("A3").getValue();

  var arrayItems = [];
  var hlpItems = cellValue.split(/item_meta: /g);

  for(var i=1;i<hlpItems.length;i++){

    var item = hlpItems[i].split(/, 'Total Area/)[0].split(/, 'Total Area/)[0].replace(/'/g,'"')+ '}';
    item = JSON.parse(item);
    arrayItems.push(item);

  }

  //Edit -> Looping through the result to get every value needed

  for (var i = 0; i < arrayItems.length ; i++) {

    Logger.log(arrayItems[i])
    Logger.log(arrayItems[i].Brand)
    Logger.log(arrayItems[i].Series)
    Logger.log(arrayItems[i].Model)
    Logger.log(arrayItems[i]['Length (mm)'])
    Logger.log(arrayItems[i]['Width (mm)'])
    Logger.log("================================")

    // This is an example on how to set a value to the sheet2

    ss.getSheetByName("sheet2").getRange('B5').setValue(arrayItems[i].Brand);

  }

}

Check the following links to see how to use:

getRange(a1Notation): To get the cells you need to work with.

getLastRow(): Returns the position of the last row that has content.

setValue(value): To set a value to a cell.


问:
How to extract texts from text node isolating the
 tags within table?

I'm having an issue printing out in the same row, table data. Of course, I could just identify with css_selector("td"), but that prints out:
Name
Address
City/State
Phone in the same column
whereas I'm trying to create:
Name, Address, City/State, Phone to the same row

HTML: (see attached photo)

This seems like such a stupid problem to be hung up on... but I've been stuck for quite some time, and haven't been able to isolate
 tags.

Code:

```<code>for x in link:
driver.get(x)
try:
    i = 0
    while 0 < 20:
        name = driver.find_elements_by_xpath("/html/body/div[2]/div/div[1]/div/div/table/tbody/tr/td[1]/table/tbody/tr['"+str(i)+"']/td/strong")
        if name[i].is_displayed():
            print(name[i].text)

            i = i + 1
        else:
            i = i + 1
except(NoSuchElementException,JavascriptException, IndexError):
    continue
</code>```

I've identified it this way to try to simply return text of proceding siblings... again to no avail. driver.find_elements_by_css_selector("td")
Also returns the entire table data... but with it's breaks

答:
The
 add new line \n to the text of the , you split by it or remove it

```<code>tds = driver.find_elements_by_css_selector("td")
for td in tds:
     text = td.text.split('\n')
     print(text) # list: ['text1', 'text2', 'text3', 'text4']

     text = td.text.replace('\n', ' ')
     print(text) # str: 'textr text2 text3 text4'
</code>```

Title: How to extract texts from text node isolating the <br> tags within table?

Body:
I'm having an issue printing out in the same row, table data. Of course, I could just identify with css_selector("td"), but that prints out:
Name
Address
City/State
Phone in the same column
whereas I'm trying to create:
Name, Address, City/State, Phone to the same row

HTML: (see attached photo)

This seems like such a stupid problem to be hung up on... but I've been stuck for quite some time, and haven't been able to isolate
 tags.

Code:

for x in link:
driver.get(x)
try:
    i = 0
    while 0 < 20:
        name = driver.find_elements_by_xpath("/html/body/div[2]/div/div[1]/div/div/table/tbody/tr/td[1]/table/tbody/tr['"+str(i)+"']/td/strong")
        if name[i].is_displayed():
            print(name[i].text)

            i = i + 1
        else:
            i = i + 1
except(NoSuchElementException,JavascriptException, IndexError):
    continue

I've identified it this way to try to simply return text of proceding siblings... again to no avail. driver.find_elements_by_css_selector("td")
Also returns the entire table data... but with it's breaks

Body:
The <br> add new line \n to the text of the <td>, you split by it or remove it

tds = driver.find_elements_by_css_selector("td")
for td in tds:
     text = td.text.split('\n')
     print(text) # list: ['text1', 'text2', 'text3', 'text4']

     text = td.text.replace('\n', ' ')
     print(text) # str: 'textr text2 text3 text4'


问:
GitKraken won't let me open my Private Repository on GitLab
So, in addition to GitKraken won't let me clone from a private repo on GitHub
I get this screen when opening my GitLab Repo:

Anyone got a solution of how to make my Repo 'non-private' or how to make GitKraken let me open this without the Pro Plan?

Already tried:

Generating new SSH Key in GitKraken

Removing Repo, Generate new GitLab connection, Clone Repo

Checked GitLab: GitKraken is an Authorized applications

Git Pull via command line gives no trouble, so no permission issue

...

答:
(window users)
In your %appdata%/../Local/gitkraken, remove latest gk version you just updated, remove updater & use the previous version (& maybe buy a license)


问:
QueryItems azure-cosmos package
I'm trying to query a cosmos db and store a table into a pandas data frame (or just as a list, the problem is the same), using the following code

```<code>table_link= 'dbs/'+database_name+'/colls/'+container_name
query= 'SELECT * FROM '+container_name
df=pd.DataFrame(client.QueryItems(table_link,query,
                              {'enableCrossPartitionQuery': True}))
</code>```

but I have two problems with the output (see the image attached).

First, I have extra columns id, $pk, &id....that shouldn't be there (I could just ask for the columns that I want in the query, but I have several tables and that would mean to write a different one for each one of them). And second, for the actual columns of the table, I get a dict with two keys "t" and "v" beign v the real value of that field.

Any help? I'm not sure if this is the expected behaviour of QueryItems, but I don't see any way to avoid it.

答: Please check the Target API for your Cosmos DB account. More than likely it is Table API. If the API is not SQL API, you will need to use the SDK specific for a particular API of Cosmod DB account.

Title: QueryItems azure-cosmos package

Body:
I'm trying to query a cosmos db and store a table into a pandas data frame (or just as a list, the problem is the same), using the following code

table_link= 'dbs/'+database_name+'/colls/'+container_name
query= 'SELECT * FROM '+container_name
df=pd.DataFrame(client.QueryItems(table_link,query,
                              {'enableCrossPartitionQuery': True}))

but I have two problems with the output (see the image attached).

First, I have extra columns id, $pk, &id....that shouldn't be there (I could just ask for the columns that I want in the query, but I have several tables and that would mean to write a different one for each one of them). And second, for the actual columns of the table, I get a dict with two keys "t" and "v" beign v the real value of that field.

Any help? I'm not sure if this is the expected behaviour of QueryItems, but I don't see any way to avoid it.


问:
c++ memory leak when using std::string in shared memory array
I have this class

```<code>class LayoutEntry
{
  unsigned int id_;
  string name_;
  bool isInput_;
};
</code>```

The copy constructor looks like this:

```<code>LayoutEntry(const LayoutEntry &other)
        : id_(other.id_),
        name_(other.name_),
        isInput_(other.isInput_)
    {
    }
</code>```

Objects of this class are put inside a map within another class

```<code>class DataLayoutDescription
{
    unsigned int sz_;
    set<LayoutEntry, SortByOffset> impl;

    // HERE!!!
    map<unsigned int, LayoutEntry> mapById;
</code>```

The copy constructor of this class looks like this:

```<code>DataLayoutDescription::DataLayoutDescription(const DataLayoutDescription &other)
    :sz_(other.sz_), impl(other.impl), mapById(other.mapById)
{
}
</code>```

Now the question:

I Get a memory leak for each LayoutEntry when run like printed

If I remove mapById(other.mapById) in the copy constructor of DataLayoutDescription  then there is no memleak

If I remove name_(other.name_), The memory leaks are also gone

Why?

EDIT

For Testing I use BOOST::UnitTest at the end I get a memory leak dump

```<code>C:\wc\05_EAPGit\Debug>EapLibTest.exe --run-test=SharedVectorTest
Running 7 test cases...

*** No errors detected
Detected memory leaks!
Dumping objects ->
{1378} normal block at 0x005815C0, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1377} normal block at 0x00581580, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1376} normal block at 0x00581540, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
</code>```

Possible Reason?
I persist the DataLayoutDescription in a shared memory area using this method

```<code>void DataLayoutDescription::Save(LayoutEntry *les, unsigned int maxEntries) const
{
    int n = std::max(impl.size(), maxEntries);
    int i = 0;
    for (DataLayoutDescription::iterator it = begin(); it != end(); ++it)
    {
        les[i] = *it;  // Source of memory leak here???
        ++i;
    }
}
</code>```

I dereference the iterator ant store a copy of this in the array that is located in the shared memory region. Is there something wrong? The shared memory is deleted on exit.

Furhter Trackdown
The class LayoutEntry is placed in an array within a shared memory area and contains a string. The reason for the memory leak is that the string gets resized. Thus it allocates more memory on the heap. Now I guess that this memroy will not be freed since the original memory is located in the shared memory. Could this be the reason? Next thing I will try to remove the string and replace it with an char array of fixed length.

... after several minutes

This was it. After replacing the string with a fixed array of char the memory leak dissapeared. Hope this helps someone.

答:
It looks like the memory leak that was introduced in Visual Studio 2010 C++ standard library, fixed with SP1. If it's your compiler (without SP1) that's certainly the problem.

See also those answers : STL container leak

ContentLicense: CC BY-SA 3.0

Body:
I have this class

class LayoutEntry
{
  unsigned int id_;
  string name_;
  bool isInput_;
};

The copy constructor looks like this:

LayoutEntry(const LayoutEntry &other)
        : id_(other.id_),
        name_(other.name_),
        isInput_(other.isInput_)
    {
    }

Objects of this class are put inside a map within another class

class DataLayoutDescription
{
    unsigned int sz_;
    set<LayoutEntry, SortByOffset> impl;

    // HERE!!!
    map<unsigned int, LayoutEntry> mapById;

The copy constructor of this class looks like this:

DataLayoutDescription::DataLayoutDescription(const DataLayoutDescription &other)
    :sz_(other.sz_), impl(other.impl), mapById(other.mapById)
{
}

Now the question:

I Get a memory leak for each LayoutEntry when run like printed

If I remove mapById(other.mapById) in the copy constructor of DataLayoutDescription  then there is no memleak

If I remove name_(other.name_), The memory leaks are also gone

Why?

EDIT

For Testing I use BOOST::UnitTest at the end I get a memory leak dump

C:\wc\05_EAPGit\Debug>EapLibTest.exe --run-test=SharedVectorTest
Running 7 test cases...

*** No errors detected
Detected memory leaks!
Dumping objects ->
{1378} normal block at 0x005815C0, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1377} normal block at 0x00581580, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{1376} normal block at 0x00581540, 16 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

Possible Reason?
I persist the DataLayoutDescription in a shared memory area using this method

void DataLayoutDescription::Save(LayoutEntry *les, unsigned int maxEntries) const
{
    int n = std::max(impl.size(), maxEntries);
    int i = 0;
    for (DataLayoutDescription::iterator it = begin(); it != end(); ++it)
    {
        les[i] = *it;  // Source of memory leak here???
        ++i;
    }
}

I dereference the iterator ant store a copy of this in the array that is located in the shared memory region. Is there something wrong? The shared memory is deleted on exit.

Furhter Trackdown
The class LayoutEntry is placed in an array within a shared memory area and contains a string. The reason for the memory leak is that the string gets resized. Thus it allocates more memory on the heap. Now I guess that this memroy will not be freed since the original memory is located in the shared memory. Could this be the reason? Next thing I will try to remove the string and replace it with an char array of fixed length.

... after several minutes

This was it. After replacing the string with a fixed array of char the memory leak dissapeared. Hope this helps someone.


问:
data platform monitoring tools options
We have aws based data pipelines having different components like kinesis lambda firehose s3 dynamodb and emr for spark jobs.
We need to implement monitoring system across all these components mostly monitoring the processing time taken at each point and if any bottlenecks.

Can anybody please guide if they have implemented such monitoring system. I am more interested in building the prometheus and grafana based system

答: For your AWS services you can use CloudWatch and CloudTrail for monitoring. For Apache Spark you can also use the Spark Web UI.</p>

Title: data platform monitoring tools options


问:
an absolute positioned view inside a TouchableOpacity does not show in React Native
When I wrap a view inside a TouchableOpacity as follows, it does not show anymore.</p>

```<code><TouchableOpacity
   onLongPress={() => {
      console.log("LONG PRESS ....");
   }}
>
          <View
            style={{
              ...styles.event,
              left: left,
              top: top,
              height: height,
              width: width,
              borderRadius: 5,
              backgroundColor: chooseColor(event.activityType, event.calendar),
              opacity: event.calendar == 0 ? 1.0 : 0.5
            }}
          />
</TouchableOpacity>
</code>```

答: Don't wrap View with TouchableOpacity. Do it reverse.</p>

Body:
When I wrap a view inside a TouchableOpacity as follows, it does not show anymore.

<TouchableOpacity
   onLongPress={() => {
      console.log("LONG PRESS ....");
   }}
>
          <View
            style={{
              ...styles.event,
              left: left,
              top: top,
              height: height,
              width: width,
              borderRadius: 5,
              backgroundColor: chooseColor(event.activityType, event.calendar),
              opacity: event.calendar == 0 ? 1.0 : 0.5
            }}
          />
</TouchableOpacity>


问:
XML cannot be serialized - parameterless constructor error, even with constructor
I'm trying to serialize an object to xml using XmlSerializer but keep getting this error:

```<code>System.InvalidOperationException: [MySql.Data.MySqlClient.MySqlParameter] cannot be serialized because it does not have a parameterless constructor.
</code>```

I followed the solution to why xml serializable class need a parameterless constructor which seems to have solved the problem for everyone else, but I still get an error. When I add public MyClass() it gives me 'MyClass.MyClass()' must declare a body because it is not marked abstract, extern, or partial, so I add a body and the first error comes back.

Note that originally there aren't any constructors, parameterless or otherwise, so I don't understand why it isn't just automatically creating its own.

What am I doing wrong?

Code added:

MyFile.cs

```<code>public async Task Save(MyClass xmlObj)
{
    XmlSerializer xmlSer = new XmlSerializer(this.GetType()); //I think the problem is likely to be here
    StringWriter strWriter = new StringWriter();

    xmlSer.Serialize(strWriter, xmlObj);
    objToUpdate.ColName = (strWriter.ToString());
    await dbContext.SaveChangesAsync();
}
</code>```

File.cs

```<code>public async Task<IActionResult> SaveData(params...)
{
    await new MyFile<MySqlParameter>(accessParam, dbContext).Save(xmlObj);
}
</code>```

答:
You should have added

```<code>public MyClass(){}
</code>```

to the class. There is a difference between no body and an empty body which is what you want on this constructor.

Body:
I'm trying to serialize an object to xml using XmlSerializer but keep getting this error:

System.InvalidOperationException: [MySql.Data.MySqlClient.MySqlParameter] cannot be serialized because it does not have a parameterless constructor.

I followed the solution to why xml serializable class need a parameterless constructor which seems to have solved the problem for everyone else, but I still get an error. When I add public MyClass() it gives me 'MyClass.MyClass()' must declare a body because it is not marked abstract, extern, or partial, so I add a body and the first error comes back.

Note that originally there aren't any constructors, parameterless or otherwise, so I don't understand why it isn't just automatically creating its own.

What am I doing wrong?

Code added:

MyFile.cs

public async Task Save(MyClass xmlObj)
{
    XmlSerializer xmlSer = new XmlSerializer(this.GetType()); //I think the problem is likely to be here
    StringWriter strWriter = new StringWriter();

    xmlSer.Serialize(strWriter, xmlObj);
    objToUpdate.ColName = (strWriter.ToString());
    await dbContext.SaveChangesAsync();
}

File.cs

public async Task<IActionResult> SaveData(params...)
{
    await new MyFile<MySqlParameter>(accessParam, dbContext).Save(xmlObj);
}

Body:
You should have added

public MyClass(){}

to the class. There is a difference between no body and an empty body which is what you want on this constructor.


问:
Get specific URL in Controller .NET CORE
So this is my controller :

```<code> [HttpGet("Home/Project-Name/Dashboard")]
  public IActionResult Index()
  {
    ViewBag.Current = "Dashboard";
    return View();
  }
</code>```

The question is, how do I get the "Project-Name" Value ?

答:
SOLVED.

Using :

```<code>@using Microsoft.AspNetCore.Http.Extensions;
String url = @Context.Request.GetDisplayUrl();
var uri = new Uri(url);
String url_project = uri.Segments[2].Replace(@"/", "");
</code>```

Note that I use this code in view.

Body:
So this is my controller :

 [HttpGet("Home/Project-Name/Dashboard")]
  public IActionResult Index()
  {
    ViewBag.Current = "Dashboard";
    return View();
  }

The question is, how do I get the "Project-Name" Value ?

Body:
SOLVED.

Using :

@using Microsoft.AspNetCore.Http.Extensions;
String url = @Context.Request.GetDisplayUrl();
var uri = new Uri(url);
String url_project = uri.Segments[2].Replace(@"/", "");

Note that I use this code in view.


问:
Update TFS2017 task to latest version
I am working on a build to run a powershell script on a remote machine, using the VSTS task :

I currently am using TFS2017 on premise, and this is version 1 of that task.
There is a version 3 available on github here :
https://github.com/Microsoft/azure-pipelines-tasks/tree/master/Tasks/PowerShellOnTargetMachinesV3

I am having an issue with this task failing, and I have read elsewhere that this version has a fix for my issue, so I want to update it if possible.
I tried a few ways to do this, but I cannot work out what I am supposed to be doing. You would think there would be an update button in TFS!
Well, there is, but it requests that you provide a .VISX file. Which the repo in GIT does not have.

I've tried running the steps in this other post:
How to update the built-in Microsoft task library in TFS 2017?
But running the command "npm run package -- --version " doesn't generate the VISX.

I tried running :

```<code>npm run package --PowerShellOnTargetMachinesV3 --version 3.1.3
</code>```

That responds with the output:

```<code>5.6.0
</code>```

Which I am not sure what to do with!

I have seen another post that says I need to use the tfs-cli?
I'm very confused.

Any help is appreciated!

答:
Since you are working on TFS on-premise, the task version will not auto update. You need to manually install "PowerShell on Target Machines" task version 3.0

You just need to download the source code and package it as an extension, finally upload and install your extension. There are some steps updated:

Get the package tool (tfx-cli)

You can install or update the TFS Cross Platform Command Line Interface (tfx-cli) using npm, a component of Node.js, from your command line.

npm i -g tfx-cli

Package your extension in a .vsix file

tfx extension create --manifest-globs vss-extension.json

More details please refer this official tutorial: Package, publish extensions.

Title: Update TFS2017 task to latest version

Body:
I am working on a build to run a powershell script on a remote machine, using the VSTS task :

I currently am using TFS2017 on premise, and this is version 1 of that task.
There is a version 3 available on github here :
https://github.com/Microsoft/azure-pipelines-tasks/tree/master/Tasks/PowerShellOnTargetMachinesV3

I am having an issue with this task failing, and I have read elsewhere that this version has a fix for my issue, so I want to update it if possible.
I tried a few ways to do this, but I cannot work out what I am supposed to be doing. You would think there would be an update button in TFS!
Well, there is, but it requests that you provide a .VISX file. Which the repo in GIT does not have.

I've tried running the steps in this other post:
How to update the built-in Microsoft task library in TFS 2017?
But running the command "npm run package -- --version " doesn't generate the VISX.

I tried running :

npm run package --PowerShellOnTargetMachinesV3 --version 3.1.3

That responds with the output:

5.6.0

Which I am not sure what to do with!

I have seen another post that says I need to use the tfs-cli?
I'm very confused.

Any help is appreciated!


问:
DAO .Execute method fails in Access mde
First off, I'm using Access 2000 and DAO.  I have code that executes a simple INSERT INTO query that I call using db.Execute.  This code works fine inside an mdb.  However, if I compile into an mde then I get

error 5 - Invalid procedure call or argument

on this line and the record does not get inserted.  However, if I change from db.Execute to DoCmd.RunSQL using the exact same SQL statement the record is inserted with no problems.  Does anyone know why the DAO Execute method of the DAO database object would suddenly stop working once I compile into an MDE?

Note:  I only get the error if I specify the dbFailOnError option of the .Execute method.  If I leave that option off, I get no error but the record is still not inserted.

EDIT:

This line fails in the MDE (but works fine in the MDB):

```<code>App.db.Execute InsertSQL, dbFailOnError
</code>```

From the immediate window with a breakpoint on the above line of code:

```<code>?InsertSQL
INSERT INTO Changes
(PropertyID, FieldID, [Which], [When], [Before], Reason, ReportChange)
VALUES (1, 2, "M", #2/19/2010 4:51:44 PM#, "Suite 2; 430 W KING ST; ABBOTTSTOWN, PA 17301-9771", "Per Owner", True)
</code>```

(I have an entire class module dedicated to building and executing SQL statements, so it's not really practical to show exactly how I built the InsertSQL string variable.  However, I really don't think that is relevant.)

This line works everywhere:

```<code>DoCmd.RunSQL InsertSQL
</code>```

EDIT: App.db definition (note that there is no reference in my project to ADO, only DAO):

```<code>Public App As New clsApp
</code>```

clsApp class module (relevant lines only):

```<code>Private m_objDB As Database

Public Property Get db() As Database
    Set db = m_objDB
End Property

Private Sub Class_Initialize()
    Set m_objDB = CurrentDb
End Sub

Private Sub Class_Terminate()
    Set m_objDB = Nothing
End Sub
</code>```

If you are curious, I use App.db rather than CurrentDB for two main reasons: 1) slight performance gain by not having to call the CurrentDB function repeatedly (call it once then just refer to the object it returns) and 2) properties of the database object like .RecordsAffected always return relevant information.  Plus, it's faster to type.  And I'm a programmer, so I'm inherently lazy.

EDIT: Let me first apologize to those who have been following this thread and trying to help me.  It seems I may have left out the critical details of my problem.  The App.db.Execute call takes place inside a class module (clsSQL) and it references a global variable named App which is itself an instance of a different class module (clsApp).  I'm guessing the problem is that I am referring to an instance of a class module from within another class module.  Can anyone confirm if calling one class module from within another is something that is supported by MDBs and not MDEs? [It is not an issue.  I was way over-thinking this.  See my answer for the full story.]

答:
Firstly, my sincere apologies to those who tried to help me with this.  As I find so frustrating when others ask questions, I left out the key piece of information because I did not think it was relevant.  Here was the full initialize procedure for my clsApp class module:

```<code>Private Sub Class_Initialize()
    Application.Echo True
    m_bEcho = True

    Set m_objDB = CurrentDb
    m_sUser = GetUserName
    Set m_objStatus = New clsStatus
    m_sPgmName = Application.CurrentProject.Name
    m_sPgmName = Left(m_sPgmName, InStr(m_sPgmName, ".mdb") - 1)
End Sub
</code>```

The key line is that last one.  When I compiled into an ".mde", the string ".mdb" was no longer present in the CurrentProject.Name.  As a result, the call to InStr() returned 0.  And 0 - 1 = -1.  So I was passing a negative number as the Length parameter for the Left() function.  However, the length parameter cannot be negative.  It is most definitely an "Invalid procedure call or argument."

My simple fix was to remove the "mdb" from ".mdb" and just check for the location of the "."  This also works correctly with the ".accdb" and ".accde" 2007 extensions.

Again, my apologies.

Title: DAO .Execute method fails in Access mde

Body:
First off, I'm using Access 2000 and DAO.  I have code that executes a simple INSERT INTO query that I call using db.Execute.  This code works fine inside an mdb.  However, if I compile into an mde then I get

error 5 - Invalid procedure call or argument

on this line and the record does not get inserted.  However, if I change from db.Execute to DoCmd.RunSQL using the exact same SQL statement the record is inserted with no problems.  Does anyone know why the DAO Execute method of the DAO database object would suddenly stop working once I compile into an MDE?

Note:  I only get the error if I specify the dbFailOnError option of the .Execute method.  If I leave that option off, I get no error but the record is still not inserted.

EDIT:

This line fails in the MDE (but works fine in the MDB):

App.db.Execute InsertSQL, dbFailOnError

From the immediate window with a breakpoint on the above line of code:

?InsertSQL
INSERT INTO Changes
(PropertyID, FieldID, [Which], [When], [Before], Reason, ReportChange)
VALUES (1, 2, "M", #2/19/2010 4:51:44 PM#, "Suite 2; 430 W KING ST; ABBOTTSTOWN, PA 17301-9771", "Per Owner", True)

(I have an entire class module dedicated to building and executing SQL statements, so it's not really practical to show exactly how I built the InsertSQL string variable.  However, I really don't think that is relevant.)

This line works everywhere:

DoCmd.RunSQL InsertSQL

EDIT: App.db definition (note that there is no reference in my project to ADO, only DAO):

Public App As New clsApp

clsApp class module (relevant lines only):

Private m_objDB As Database

Public Property Get db() As Database
    Set db = m_objDB
End Property

Private Sub Class_Initialize()
    Set m_objDB = CurrentDb
End Sub

Private Sub Class_Terminate()
    Set m_objDB = Nothing
End Sub

If you are curious, I use App.db rather than CurrentDB for two main reasons: 1) slight performance gain by not having to call the CurrentDB function repeatedly (call it once then just refer to the object it returns) and 2) properties of the database object like .RecordsAffected always return relevant information.  Plus, it's faster to type.  And I'm a programmer, so I'm inherently lazy.

EDIT: Let me first apologize to those who have been following this thread and trying to help me.  It seems I may have left out the critical details of my problem.  The App.db.Execute call takes place inside a class module (clsSQL) and it references a global variable named App which is itself an instance of a different class module (clsApp).  I'm guessing the problem is that I am referring to an instance of a class module from within another class module.  Can anyone confirm if calling one class module from within another is something that is supported by MDBs and not MDEs? [It is not an issue.  I was way over-thinking this.  See my answer for the full story.]

Body:
Firstly, my sincere apologies to those who tried to help me with this.  As I find so frustrating when others ask questions, I left out the key piece of information because I did not think it was relevant.  Here was the full initialize procedure for my clsApp class module:

Private Sub Class_Initialize()
    Application.Echo True
    m_bEcho = True

    Set m_objDB = CurrentDb
    m_sUser = GetUserName
    Set m_objStatus = New clsStatus
    m_sPgmName = Application.CurrentProject.Name
    m_sPgmName = Left(m_sPgmName, InStr(m_sPgmName, ".mdb") - 1)
End Sub

The key line is that last one.  When I compiled into an ".mde", the string ".mdb" was no longer present in the CurrentProject.Name.  As a result, the call to InStr() returned 0.  And 0 - 1 = -1.  So I was passing a negative number as the Length parameter for the Left() function.  However, the length parameter cannot be negative.  It is most definitely an "Invalid procedure call or argument."

My simple fix was to remove the "mdb" from ".mdb" and just check for the location of the "."  This also works correctly with the ".accdb" and ".accde" 2007 extensions.

Again, my apologies.


问:
How to do nested custom validation in Angular 8
I want to check the validation between two different fields  OR condition. Supposed I have two fields age and birth_date. I want to check only one field required either age or birth_date.

I am using Angular 8. My form is nested with Add more features.

答:
You can write custom validation and check your flow.

```<code>this.userFormGroup= this.formBuilder.group({
   birth_date: [''],
   age : [''],
   }, {validator: this.customValidation});
customValidation(formGroup): any {
  const birthField = formGroup.controls['birth_date'].value;
  const ageField = formGroup.controls['age '].value;
  if (birthField && ageField) return null;
  if (birthField) return { ageRequired: true };
  if (ageField) return { birthRequired: true };
 }
}
</code>```

The age is required!

The birth date is required!

```

Body:
You can write custom validation and check your flow.

this.userFormGroup= this.formBuilder.group({
   birth_date: [''],
   age : [''],
   }, {validator: this.customValidation});
customValidation(formGroup): any {
  const birthField = formGroup.controls['birth_date'].value;
  const ageField = formGroup.controls['age '].value;
  if (birthField && ageField) return null;
  if (birthField) return { ageRequired: true };
  if (ageField) return { birthRequired: true };
 }
}

<div *ngIf="!userFormGroup.valid">
  <p *ngIf="userFormGroup.hasError('ageRequired')">The age is required!</p>
  <p *ngIf="userFormGroup.hasError('birthRequired')">The birth date is required!</p>
</div>


问:
Recursively access dict via attributes as well as index access?
I'd like to be able to do something like this:

```<code>from dotDict import dotdictify

life = {'bigBang':
           {'stars':
               {'planets': []}
           }
       }

dotdictify(life)

# This would be the regular way:
life['bigBang']['stars']['planets'] = {'earth': {'singleCellLife': {}}}
# But how can we make this work?
life.bigBang.stars.planets.earth = {'singleCellLife': {}}

#Also creating new child objects if none exist, using the following syntax:
life.bigBang.stars.planets.earth.multiCellLife = {'reptiles':{},'mammals':{}}
</code>```

My motivations are to improve the succinctness of the code, and if possible use similar syntax to Javascript for accessing JSON objects for efficient cross platform development. (I also use Py2JS and similar.)

答:
There is a package doing exactly what you want and also something more and it is called Prodict.

from prodict import Prodict

life_dict = {'bigBang':
                {'stars':
                    {'planets': []}
                }
            }

life = Prodict.from_dict(life_dict)

print(life.bigBang.stars.planets)
# prints []

# you can even add new properties dynamically
life.bigBang.galaxies = []

```

PS: I'm the author of the Prodict.

Body:
I'd like to be able to do something like this:

from dotDict import dotdictify

life = {'bigBang':
           {'stars':
               {'planets': []}
           }
       }

dotdictify(life)

# This would be the regular way:
life['bigBang']['stars']['planets'] = {'earth': {'singleCellLife': {}}}
# But how can we make this work?
life.bigBang.stars.planets.earth = {'singleCellLife': {}}

#Also creating new child objects if none exist, using the following syntax:
life.bigBang.stars.planets.earth.multiCellLife = {'reptiles':{},'mammals':{}}

My motivations are to improve the succinctness of the code, and if possible use similar syntax to Javascript for accessing JSON objects for efficient cross platform development. (I also use Py2JS and similar.)

Body:
There is a package doing exactly what you want and also something more and it is called Prodict.

from prodict import Prodict

life_dict = {'bigBang':
                {'stars':
                    {'planets': []}
                }
            }

life = Prodict.from_dict(life_dict)

print(life.bigBang.stars.planets)
# prints []

# you can even add new properties dynamically
life.bigBang.galaxies = []

PS: I'm the author of the Prodict.


问:
How to create SwipeActionsConfigurationForRowAt in List view - SwiftUI (iOS 13)?

I want to create a list view in SwiftUI where I can show two buttons for different actions when user swipe left. I know there is an option for delete (.onDelete(perform: delete)) but I want to add more actions as I mention in the above image.

I can easily do this in UITalbleView using Swift.

```<code> func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    }

    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

}
</code>```

But my question is : How can I do this in SwiftUI using List View ?

答:
This is quick code I typed up, but it gives a simple example of how to create a custom UITableView solution:

```<code>    RoutineTableView(routines: routineDataSource.routines)
  .trailingSwipeActionsConfiguration {
    let editAction = UIContextualAction(
      style: .normal,
      title: "EDIT"
    ) { (action, sourceView, completionHandler) in

      completionHandler(true)
    }
    editAction.backgroundColor = UIColor.darkGray
    let deleteAction = UIContextualAction(
      style: .destructive,
      title: "DELETE"
    ) { (action, sourceView, completionHandler) in

      completionHandler(true)
    }
    let actions = [deleteAction, editAction]
    let configuration = UISwipeActionsConfiguration(actions: actions)
    return configuration
  }
  .onCellPress {
    print("hi there")
  }
  .navigationBarTitle("Routines")
</code>```

and

```<code>private class CustomDataSource<SectionType: Hashable, ItemType: Hashable>: UITableViewDiffableDataSource<SectionType, ItemType> {
  override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
  }
}

struct RoutineTableView: UIViewRepresentable {

  let routines: [Routine]
  private var onCellPress: (() -> Void)? = nil
  private var trailingSwipeActionsConfiguration: (() -> UISwipeActionsConfiguration)? = nil

  init(routines: [Routine]) {
    self.routines = routines
  }

  func makeUIView(
    context: UIViewRepresentableContext<RoutineTableView>
  ) -> UITableView {
    let tableView = UITableView()
    context.coordinator.update(withTableView: tableView)
    return tableView
  }

  func updateUIView(_ uiView: UITableView, context: UIViewRepresentableContext<RoutineTableView>) {
    context.coordinator.update(routines: routines)
  }

  // MARK: - Coordinator

  func makeCoordinator() -> RoutineTableView.Coordinator {
    return Coordinator(self)
  }

  class Coordinator: NSObject, UITableViewDelegate {

    private enum Section {
      case first
    }

    private let view: RoutineTableView
    private var dataSource: UITableViewDiffableDataSource<Section, Routine>?

    init(_ view: RoutineTableView) {
      self.view = view
      super.init()
    }

    func update(withTableView tableView: UITableView) {
      tableView.register(RoutineTableViewCell.self)
      tableView.delegate = self

      let dataSource = CustomDataSource<Section, Routine>(tableView: tableView) { (tableView, indexPath, routine) -> UITableViewCell? in
        let cell: RoutineTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        cell.configure(withRoutine: routine)
        return cell
      }
      self.dataSource = dataSource
    }

    func update(routines: [Routine]) {
      var snapshot = NSDiffableDataSourceSnapshot<Section, Routine>()
      snapshot.appendSections([.first])
      snapshot.appendItems(routines)
      dataSource?.apply(snapshot, animatingDifferences: true)
    }

    // MARK: - <UITableViewDelegate>

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      view.onCellPress?()
    }

    func tableView(
      _ tableView: UITableView,
      trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
    ) -> UISwipeActionsConfiguration? {
      return view.trailingSwipeActionsConfiguration?()
    }

  }
}

extension RoutineTableView {

  func onCellPress(
    _ onCellPress: @escaping () -> Void
  ) -> RoutineTableView {
    var view = self
    view.onCellPress = onCellPress
    return view
  }

  func trailingSwipeActionsConfiguration(
    _ trailingSwipeActionsConfiguration: @escaping () -> UISwipeActionsConfiguration
  ) -> RoutineTableView {
    var view = self
    view.trailingSwipeActionsConfiguration = trailingSwipeActionsConfiguration
    return view
  }
}
</code>```

Body:
I want to create a list view in SwiftUI where I can show two buttons for different actions when user swipe left. I know there is an option for delete (.onDelete(perform: delete)) but I want to add more actions as I mention in the above image.

I can easily do this in UITalbleView using Swift.

 func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    }

    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

}

But my question is : How can I do this in SwiftUI using List View ?

Body:
This is quick code I typed up, but it gives a simple example of how to create a custom UITableView solution:

    RoutineTableView(routines: routineDataSource.routines)
  .trailingSwipeActionsConfiguration {
    let editAction = UIContextualAction(
      style: .normal,
      title: "EDIT"
    ) { (action, sourceView, completionHandler) in

      completionHandler(true)
    }
    editAction.backgroundColor = UIColor.darkGray
    let deleteAction = UIContextualAction(
      style: .destructive,
      title: "DELETE"
    ) { (action, sourceView, completionHandler) in

      completionHandler(true)
    }
    let actions = [deleteAction, editAction]
    let configuration = UISwipeActionsConfiguration(actions: actions)
    return configuration
  }
  .onCellPress {
    print("hi there")
  }
  .navigationBarTitle("Routines")

and

private class CustomDataSource<SectionType: Hashable, ItemType: Hashable>: UITableViewDiffableDataSource<SectionType, ItemType> {
  override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
  }
}

struct RoutineTableView: UIViewRepresentable {

  let routines: [Routine]
  private var onCellPress: (() -> Void)? = nil
  private var trailingSwipeActionsConfiguration: (() -> UISwipeActionsConfiguration)? = nil

  init(routines: [Routine]) {
    self.routines = routines
  }

  func makeUIView(
    context: UIViewRepresentableContext<RoutineTableView>
  ) -> UITableView {
    let tableView = UITableView()
    context.coordinator.update(withTableView: tableView)
    return tableView
  }

  func updateUIView(_ uiView: UITableView, context: UIViewRepresentableContext<RoutineTableView>) {
    context.coordinator.update(routines: routines)
  }

  // MARK: - Coordinator

  func makeCoordinator() -> RoutineTableView.Coordinator {
    return Coordinator(self)
  }

  class Coordinator: NSObject, UITableViewDelegate {

    private enum Section {
      case first
    }

    private let view: RoutineTableView
    private var dataSource: UITableViewDiffableDataSource<Section, Routine>?

    init(_ view: RoutineTableView) {
      self.view = view
      super.init()
    }

    func update(withTableView tableView: UITableView) {
      tableView.register(RoutineTableViewCell.self)
      tableView.delegate = self

      let dataSource = CustomDataSource<Section, Routine>(tableView: tableView) { (tableView, indexPath, routine) -> UITableViewCell? in
        let cell: RoutineTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        cell.configure(withRoutine: routine)
        return cell
      }
      self.dataSource = dataSource
    }

    func update(routines: [Routine]) {
      var snapshot = NSDiffableDataSourceSnapshot<Section, Routine>()
      snapshot.appendSections([.first])
      snapshot.appendItems(routines)
      dataSource?.apply(snapshot, animatingDifferences: true)
    }

    // MARK: - <UITableViewDelegate>

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      view.onCellPress?()
    }

    func tableView(
      _ tableView: UITableView,
      trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
    ) -> UISwipeActionsConfiguration? {
      return view.trailingSwipeActionsConfiguration?()
    }

  }
}

extension RoutineTableView {

  func onCellPress(
    _ onCellPress: @escaping () -> Void
  ) -> RoutineTableView {
    var view = self
    view.onCellPress = onCellPress
    return view
  }

  func trailingSwipeActionsConfiguration(
    _ trailingSwipeActionsConfiguration: @escaping () -> UISwipeActionsConfiguration
  ) -> RoutineTableView {
    var view = self
    view.trailingSwipeActionsConfiguration = trailingSwipeActionsConfiguration
    return view
  }
}


问:
How to keep the DetailsView of a SfDataGrid expanded?
I have a SfDataGrid and I made a DetailsViewDefinition for that. I also make ExpandAllDetailsView from code to expand all details and I want to keep these open, but right after the first reorder or first regroup these will collapse.

I tried kinda every events (what made sense) to reopen, but only the MouseUp was the closest to the goal, but that was kinda bad because it does not work on header and will reopen on every mouseups, so it was a very bad hack.

I would like to know a good and working way to keep the rowdetail open even after events like reorder/group.

答:
You can achieve your requirement by using SfDataGrid.ExpandAllDetailsView method. For grouping, you can achieve this by SfDataGrid.GroupColumnDescriptions.CollectionChanged event,

```<code>this.dataGrid.GroupColumnDescriptions.CollectionChanged += GroupColumnDescriptions_CollectionChanged;
private void GroupColumnDescriptions_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
dataGrid.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle,
          new Action(() =>
          {
              this.dataGrid.ExpandAllDetailsView();
          }));
 }
</code>```

For sorting you can achieve this by SfDataGrid.SortColumnsChanged event,

```<code>this.dataGrid.SortColumnsChanged += DataGrid_SortColumnsChanged;

private void DataGrid_SortColumnsChanged(object sender, GridSortColumnsChangedEventArgs e)
{
    dataGrid.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle,
         new Action(() =>
         {
             this.dataGrid.ExpandAllDetailsView();

         }));
}
</code>```

Sample

Regards,

Susmitha S

Body:
You can achieve your requirement by using SfDataGrid.ExpandAllDetailsView method. For grouping, you can achieve this by SfDataGrid.GroupColumnDescriptions.CollectionChanged event,

this.dataGrid.GroupColumnDescriptions.CollectionChanged += GroupColumnDescriptions_CollectionChanged;
private void GroupColumnDescriptions_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
dataGrid.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle,
          new Action(() =>
          {
              this.dataGrid.ExpandAllDetailsView();
          }));
 }

For sorting you can achieve this by SfDataGrid.SortColumnsChanged event,

this.dataGrid.SortColumnsChanged += DataGrid_SortColumnsChanged;

private void DataGrid_SortColumnsChanged(object sender, GridSortColumnsChangedEventArgs e)
{
    dataGrid.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle,
         new Action(() =>
         {
             this.dataGrid.ExpandAllDetailsView();

         }));
}

Sample

Regards,

Susmitha S


问:
Capacitor Plugin shows as undefined on android build
Here's a capacitor plugin I found https://github.com/JhonArlex/capacitor_qrcode
and I want it to integrate it to my ionic app, on web serve it works as expected, but when I try on livereload on android, the error screen pops out and says the plugin is undefined..

```<code>import "capacitor_qrcode";
import { Plugins } from "@capacitor/core";

//..

await Plugins.QRCodePlugin.getCodeQR();
// QRCodePlugin is undefined?
</code>```

I'm using Ionic React Capacitor... also would appreciate if you can suggest any other way I could integrate QR code scanning feature on my app thanks!

答:
When using your own plugins you need to register/add it into your android MainActivity.
https://capacitor.ionicframework.com/docs/plugins/android#export-to-capacitor

Like this:

import com.jhon.capacitor_qrcode.QRCodePlugin;

public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
      add(QRCodePlugin.class);
    }});
  }
}
```

Body:
Here's a capacitor plugin I found https://github.com/JhonArlex/capacitor_qrcode
and I want it to integrate it to my ionic app, on web serve it works as expected, but when I try on livereload on android, the error screen pops out and says the plugin is undefined..

import "capacitor_qrcode";
import { Plugins } from "@capacitor/core";

//..

await Plugins.QRCodePlugin.getCodeQR();
// QRCodePlugin is undefined?

I'm using Ionic React Capacitor... also would appreciate if you can suggest any other way I could integrate QR code scanning feature on my app thanks!


问:
Send a notification by Lambda function with AWS Pinpoint
I have an iOS app with a backend build by MobileHub with API Gateway, Lambda, and DynamoDB.
I noticed that the SNS function of MobileHub has been replaced by Pinpoint, and I would like to create a notification system using this new service.

When a user creates a new post through API Gateway, a lambda function will be triggered and I suppose I can send a notification to the subscribers by Pinpoint.
But I cannot find any example or reference doc in the official website of Pinpoint.

Do you have any resource for this scenario or any idea? Thank you very much!

答:
I was struggling a lot getting a lambda function working, so please see this answer as an addition to the answer from Dylan w.

Client

```<code>import PushNotification from '@aws-amplify/pushnotification';
import Analytics from '@aws-amplify/analytics';

PushNotification.onRegister((token) => {

    Analytics.updateEndpoint({
        address: token,
        channelType: 'APNS',
        optOut: 'NONE',
        // Customized userId
        userId: "e236e3ea-bas9-4eae-967e-0eb9bcaca26d" // Example
    })

});
</code>```

Lambda function

```<code>'use strict';

const AWS = require('aws-sdk');

exports.handler = async (event, context) => {

  var pinpoint = new AWS.Pinpoint();

  const sendMessagesParams = {
    ApplicationId: <YOUR_APPLICATION_ID>, // Find it in Pinpoint->All projects
    SendUsersMessageRequest: {
        Users:{<USER_ID>:{}}, // The same userId as set on the client. This way you can "follow" people if they switch device
        MessageConfiguration:{
          APNSMessage:{
            Action:"OPEN_APP",
            Title:"Message received",
            Body:"You have a new message"
        }
      }
    }
  };

  return await new Promise( (resolve, reject) => {

    pinpoint.sendUsersMessages(sendMessagesParams, (sendMessagesErr, sendMessagesData) => {
      if(sendMessagesErr) reject(sendMessagesErr)
      if(sendMessagesData) resolve(sendMessagesData)
    });

  });

};
</code>```

Note that the call to pinpoint is wrapped in a promise. Because pinpoint.sendUserMessages accepts a callback, the execution is continued (async nature of Node), which will shut down the lambda function and you will get no output from the callback function or receive a notification, without awaiting the function to finish.

Body:
I was struggling a lot getting a lambda function working, so please see this answer as an addition to the answer from Dylan w.

Client

import PushNotification from '@aws-amplify/pushnotification';
import Analytics from '@aws-amplify/analytics';

PushNotification.onRegister((token) => {

    Analytics.updateEndpoint({
        address: token,
        channelType: 'APNS',
        optOut: 'NONE',
        // Customized userId
        userId: "e236e3ea-bas9-4eae-967e-0eb9bcaca26d" // Example
    })

});

Lambda function

'use strict';

const AWS = require('aws-sdk');

exports.handler = async (event, context) => {

  var pinpoint = new AWS.Pinpoint();

  const sendMessagesParams = {
    ApplicationId: <YOUR_APPLICATION_ID>, // Find it in Pinpoint->All projects
    SendUsersMessageRequest: {
        Users:{<USER_ID>:{}}, // The same userId as set on the client. This way you can "follow" people if they switch device
        MessageConfiguration:{
          APNSMessage:{
            Action:"OPEN_APP",
            Title:"Message received",
            Body:"You have a new message"
        }
      }
    }
  };

  return await new Promise( (resolve, reject) => {

    pinpoint.sendUsersMessages(sendMessagesParams, (sendMessagesErr, sendMessagesData) => {
      if(sendMessagesErr) reject(sendMessagesErr)
      if(sendMessagesData) resolve(sendMessagesData)
    });

  });

};

Note that the call to pinpoint is wrapped in a promise. Because pinpoint.sendUserMessages accepts a callback, the execution is continued (async nature of Node), which will shut down the lambda function and you will get no output from the callback function or receive a notification, without awaiting the function to finish.


问:
PowerBI Relationship
I have a PowerBI Report that contains information from both an ERP and a CRM, I am trying to create a drill through that will allow users to drill through ERP data to show CRM data. I am having issues trying to structure my table relationships, I think I will need a helper table somewhere. Appreciate any thoughts you may have.

答:
in PowerBI you can now use Many:Many relationship, in your case it should be single direction with CRM Accounts filtering ERP Customers. See more here:

https://learn.microsoft.com/en-us/power-bi/desktop-many-to-many-relationships
and here:

https://www.sqlbi.com/tv/different-types-of-many-to-many-relationships-in-power-bi/

it's effectively the same as creating a helper table as explained in the second link

Title: PowerBI Relationship


问:
join after group by condition in a nested select query
Hi I'm new to sql and I'm trying to solve this query:
find the registration numbers(MATRICOLA) and the surnames(COGNOME) of the employees that have the salary greater than at least 10% than the average salary of their department.

```<code>IMPIEGATO(employees)
DIPARTIMENTO(department)
</code>```

```<code>SELECT *
from (
  SELECT *
  FROM IMPIEGATO imp1,
       DIPARTIMENTO dip1
  where imp1.dipartimento_codice_fk = dip1.codice
), (
  SELECT dip.codice, 1.1*avg(imp.stipendio) AS "STIPENDIO_MEDIO_10"
  FROM IMPIEGATO imp
    JOIN DIPARTIMENTO dip ON dip.CODICE=imp.DIPARTIMENTO_CODICE_FK
  GROUP BY dip.codice
)
</code>```

I can't add this where condition to get just the results I need WHERE dip.codice=dip1.codice.
This is the error I get

ORA-00904: "DIP1"."CODICE": identificativo non valido

  00904. 00000 -  "%s: invalid identifier"

  *Cause:

  *Action:

  Errore alla riga: 255, colonna: 18

答:
You are referring to the CODICE outside these two subqueries with an alias(dip or dip1) given to the DIPARTIMENTO in the subquery. (Scope of the alias is within the subquery only)

Anyway, a better solution is to use the analytical function as following:

```<code>SELECT MATRICOLA, COGNOME
FROM
    ( SELECT
            EMP.MATRICOLA, EMP.COGNOME, EMP.STIPENDIO,
            AVG(EMP.STIPENDIO) OVER(
                PARTITION BY EMP.DIPARTIMENTO_CODICE_FK
            ) AS AVG_SALARY_DEPT
        FROM IMPIEGATO EMP
             JOIN DIPARTIMENTO DEPT ON EMP.DIPARTIMENTO_CODICE_FK = DEPT.CODICE
    )
WHERE STIPENDIO >= 1.1 * AVG_SALARY_DEPT;
</code>```

You can also use your own query with little bit of changes in it. Changes are mentioned in the comments in the following query:

```<code>SELECT t1.MATRICOLA, t1.COGNOME
from (
  SELECT *
  FROM IMPIEGATO imp1,
       DIPARTIMENTO dip1
  where imp1.dipartimento_codice_fk = dip1.codice
) t1 join -- given alias
(
  SELECT dip.codice, 1.1*avg(imp.stipendio) AS "STIPENDIO_MEDIO_10"
  FROM IMPIEGATO imp
    JOIN DIPARTIMENTO dip ON dip.CODICE=imp.DIPARTIMENTO_CODICE_FK
  GROUP BY dip.codice
) t2 on t1.codice = t2.codice -- given alias
                              -- and added the join condition with proper alias(t1, t2)
where t1.stipendio >= t2.STIPENDIO_MEDIO_10 -- added the condition to fetch desired result
</code>```

Cheers!!

Body:
Hi I'm new to sql and I'm trying to solve this query:
find the registration numbers(MATRICOLA) and the surnames(COGNOME) of the employees that have the salary greater than at least 10% than the average salary of their department.

IMPIEGATO(employees)
DIPARTIMENTO(department)

SELECT *
from (
  SELECT *
  FROM IMPIEGATO imp1,
       DIPARTIMENTO dip1
  where imp1.dipartimento_codice_fk = dip1.codice
), (
  SELECT dip.codice, 1.1*avg(imp.stipendio) AS "STIPENDIO_MEDIO_10"
  FROM IMPIEGATO imp
    JOIN DIPARTIMENTO dip ON dip.CODICE=imp.DIPARTIMENTO_CODICE_FK
  GROUP BY dip.codice
)

I can't add this where condition to get just the results I need WHERE dip.codice=dip1.codice.
This is the error I get

ORA-00904: "DIP1"."CODICE": identificativo non valido

  00904. 00000 -  "%s: invalid identifier"

  *Cause:

  *Action:

  Errore alla riga: 255, colonna: 18

Body:
You are referring to the CODICE outside these two subqueries with an alias(dip or dip1) given to the DIPARTIMENTO in the subquery. (Scope of the alias is within the subquery only)

Anyway, a better solution is to use the analytical function as following:

SELECT MATRICOLA, COGNOME
FROM
    ( SELECT
            EMP.MATRICOLA, EMP.COGNOME, EMP.STIPENDIO,
            AVG(EMP.STIPENDIO) OVER(
                PARTITION BY EMP.DIPARTIMENTO_CODICE_FK
            ) AS AVG_SALARY_DEPT
        FROM IMPIEGATO EMP
             JOIN DIPARTIMENTO DEPT ON EMP.DIPARTIMENTO_CODICE_FK = DEPT.CODICE
    )
WHERE STIPENDIO >= 1.1 * AVG_SALARY_DEPT;

You can also use your own query with little bit of changes in it. Changes are mentioned in the comments in the following query:

SELECT t1.MATRICOLA, t1.COGNOME
from (
  SELECT *
  FROM IMPIEGATO imp1,
       DIPARTIMENTO dip1
  where imp1.dipartimento_codice_fk = dip1.codice
) t1 join -- given alias
(
  SELECT dip.codice, 1.1*avg(imp.stipendio) AS "STIPENDIO_MEDIO_10"
  FROM IMPIEGATO imp
    JOIN DIPARTIMENTO dip ON dip.CODICE=imp.DIPARTIMENTO_CODICE_FK
  GROUP BY dip.codice
) t2 on t1.codice = t2.codice -- given alias
                              -- and added the join condition with proper alias(t1, t2)
where t1.stipendio >= t2.STIPENDIO_MEDIO_10 -- added the condition to fetch desired result

Cheers!!


问:
Java alternatives to GradientPaint / GradientPaint is slow
Are there alternatives to using GradientPaint in Java?

Basically at this moment my code is acceptably fast when I fill all rectangles in my application with a solid color.

However as soon as I start to use a GradientPaint, then the performance drops by 1 second for an action.

An action for example is: Clicking on an image, and then the image pops up in big.

I like to keep the look of the GradientPaint as a normal fill just looks horrible... But I do not want to lose the performance. Are there any alternatives to GradientPaint?

I hope my question is not too vague, but it just seems that GradientPaint is too slow. I have tried to manually implement a GradientPaint and the performance is close to the Java implementation, so could be an indication that GradientPaint simply cannot be done more efficiently.

The code that uses GradientPaint:

```<code>private void drawRectangle(final Graphics2D g2d, int width, int height, int x, int y, final int borderSize, final Color color) {
    g2d.setColor(color);
    g2d.fillRect(x, y, width, height);

    //account for border distance
    x += borderSize;
    y += borderSize;
    width -= 2 * borderSize;
    height -= 2 * borderSize;

    int mx = (int)Math.round(x + (width / 2));
    int my = (int)Math.round(y + (height / 2));

    Color colorEdge = alphaColor(color, 192);
    Color colorInside = alphaColor(color, 128);

    Composite oldComposite = g2d.getComposite();

    g2d.setComposite(AlphaComposite.SrcIn);
    g2d.setColor(color);
    GradientPaint paintQ1 = new GradientPaint(x, y, colorEdge, mx, my, colorInside);
    g2d.setPaint(paintQ1);
    g2d.fillRect(x, y, mx - x, my - y);

    GradientPaint paintQ2 = new GradientPaint(x + width - 1, y, colorEdge, mx, my, colorInside);
    g2d.setPaint(paintQ2);
    g2d.fillRect(mx, y, mx - x, my - y);

    GradientPaint paintQ3 = new GradientPaint(x, y + height - 1, colorEdge, mx, my, colorInside);
    g2d.setPaint(paintQ3);
    g2d.fillRect(x, my, mx - x, my - y);

    GradientPaint paintQ4 = new GradientPaint(x + width - 1, y + height - 1, colorEdge, mx, my, colorInside);
    g2d.setPaint(paintQ4);
    g2d.fillRect(mx, my, mx - x, my - y);
    g2d.setComposite(oldComposite);
}

private Color alphaColor(final Color c1, final int alpha) {
    return new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), alpha);
}
</code>```

It is called like just 3 times per image covering a total area of approximately two times 500 by 700 pixels.

Regards.

答:
Answering 6 years late, but for anyone who finds it:

In general, the way Java Paint instances work is that they allocate very large rasters (int or byte arrays) behind the scenes, and these then get discarded fairly quickly and recreated the next time you paint.  It's compounded somewhat by the fact that Java2D is oriented around pushing pixels, and that is not how modern graphics pipelines work.

You can work around this within some limitations:  If you are just doing horizontal or vertical gradients, it can be much more performant to paint the gradient once into a screen-compatible BufferedImage (you can do a fairly small image and tile it vertically or horizontally);  for my needs, performance was improved around 20x.  Here's a project that uses this approach which is usable as a library:  https://github.com/timboudreau/visual-library-tabcontrol/tree/master/colors/src/main/java/com/mastfrog/colors

Of course, if you're doing complex RadialGradientPaints, that's not going to be tilable;  it might be possible to handle tiling at arbitrary angles, but it's non-trivial - set a transform on the graphics so tiling goes at the desired angle, and transform all of the shapes so they will appear oriented normally.

Body:
Are there alternatives to using GradientPaint in Java?

Basically at this moment my code is acceptably fast when I fill all rectangles in my application with a solid color.

However as soon as I start to use a GradientPaint, then the performance drops by 1 second for an action.

An action for example is: Clicking on an image, and then the image pops up in big.

I like to keep the look of the GradientPaint as a normal fill just looks horrible... But I do not want to lose the performance. Are there any alternatives to GradientPaint?

I hope my question is not too vague, but it just seems that GradientPaint is too slow. I have tried to manually implement a GradientPaint and the performance is close to the Java implementation, so could be an indication that GradientPaint simply cannot be done more efficiently.

The code that uses GradientPaint:

private void drawRectangle(final Graphics2D g2d, int width, int height, int x, int y, final int borderSize, final Color color) {
    g2d.setColor(color);
    g2d.fillRect(x, y, width, height);

    //account for border distance
    x += borderSize;
    y += borderSize;
    width -= 2 * borderSize;
    height -= 2 * borderSize;

    int mx = (int)Math.round(x + (width / 2));
    int my = (int)Math.round(y + (height / 2));

    Color colorEdge = alphaColor(color, 192);
    Color colorInside = alphaColor(color, 128);

    Composite oldComposite = g2d.getComposite();

    g2d.setComposite(AlphaComposite.SrcIn);
    g2d.setColor(color);
    GradientPaint paintQ1 = new GradientPaint(x, y, colorEdge, mx, my, colorInside);
    g2d.setPaint(paintQ1);
    g2d.fillRect(x, y, mx - x, my - y);

    GradientPaint paintQ2 = new GradientPaint(x + width - 1, y, colorEdge, mx, my, colorInside);
    g2d.setPaint(paintQ2);
    g2d.fillRect(mx, y, mx - x, my - y);

    GradientPaint paintQ3 = new GradientPaint(x, y + height - 1, colorEdge, mx, my, colorInside);
    g2d.setPaint(paintQ3);
    g2d.fillRect(x, my, mx - x, my - y);

    GradientPaint paintQ4 = new GradientPaint(x + width - 1, y + height - 1, colorEdge, mx, my, colorInside);
    g2d.setPaint(paintQ4);
    g2d.fillRect(mx, my, mx - x, my - y);
    g2d.setComposite(oldComposite);
}

private Color alphaColor(final Color c1, final int alpha) {
    return new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), alpha);
}

It is called like just 3 times per image covering a total area of approximately two times 500 by 700 pixels.

Regards.