问:
How to add all missing combination in a dataframe
I have a dataframe of around 15000 rows, something like as below,

```<code>dataframe =
date        |  value  |  count  |  dayofWeek
01/01/2021  |  250    |   1     |    0
01/01/2021  |  235    |   2     |    0
01/01/2021  |  244    |   3     |    0
..
..
01/01/2021  |  255    |  25     |    0
02/01/2021  |  225    |   1     |    1
02/01/2021  |  230    |   2     |    1
..
..
02/01/2021  |  275    |   20    |    1
03/01/2021  |  265    |   1     |    2
..
..
</code>```

The dataframe has some missing data for the count.As for each date, there should be 25 count, if the count number is not present, we want to add the data with value-0 , and dayofWeek as per the date. There will be always atleast 10 count present for a specific date.

I don't know where to start as I am new to pandas. Can someone help.

Body:
I have a dataframe of around 15000 rows, something like as below,

dataframe =
date        |  value  |  count  |  dayofWeek
01/01/2021  |  250    |   1     |    0
01/01/2021  |  235    |   2     |    0
01/01/2021  |  244    |   3     |    0
..
..
01/01/2021  |  255    |  25     |    0
02/01/2021  |  225    |   1     |    1
02/01/2021  |  230    |   2     |    1
..
..
02/01/2021  |  275    |   20    |    1
03/01/2021  |  265    |   1     |    2
..
..

The dataframe has some missing data for the count.As for each date, there should be 25 count, if the count number is not present, we want to add the data with value-0 , and dayofWeek as per the date. There will be always atleast 10 count present for a specific date.

I don't know where to start as I am new to pandas. Can someone help.

Body:
Create the complementary dataframe them merge it to your original dataframe

N = 5  # In your case 25

# First find the missing count for each date
cnt = df['date'].value_counts().loc[lambda x: x < N] \
               .apply(lambda x: range(x+1, N+1)).explode()

# Create the dataframe
dfc = pd.DataFrame({'date': cnt.index, 'value': 0, 'count': cnt.values,
                    'dayofWeek': pd.to_datetime(cnt.index, dayfirst=True).dayofweek})

# Concatenate them:
out = pd.concat([df, dfc]).sort_values(['date', 'count']).reset_index(drop=True)

Output:

>>> out
          date  value count  dayofWeek
0   01/01/2021    250     1          4
1   01/01/2021    235     2          4
2   01/01/2021    244     3          4
3   01/01/2021    244     4          4
4   01/01/2021    244     5          4
5   02/01/2021    225     1          5
6   02/01/2021    230     2          5
7   02/01/2021    275     3          5
8   02/01/2021      0     4          5  # <- Added
9   02/01/2021      0     5          5  # <- Added
10  03/01/2021    265     1          6
11  03/01/2021      0     2          6  # <- Added
12  03/01/2021      0     3          6  # <- Added
13  03/01/2021      0     4          6  # <- Added
14  03/01/2021      0     5          6  # <- Added

Setup MRE

data = {'date': ['01/01/2021']*5 + ['02/01/2021']*3 + ['03/01/2021'],
        'value': [250, 235, 244, 244, 244, 225, 230, 275, 265],
        'count': [1, 2, 3, 4, 5, 1, 2, 3, 1],
        'dayofWeek': [4, 4, 4, 4, 4, 5, 5, 5, 6]}
df = pd.DataFrame(data)
print(df)

# Output
         date  value  count  dayofWeek
0  01/01/2021    250      1          4
1  01/01/2021    235      2          4
2  01/01/2021    244      3          4
3  01/01/2021    244      4          4
4  01/01/2021    244      5          4  # <- Full, do nothing
5  02/01/2021    225      1          5
6  02/01/2021    230      2          5
7  02/01/2021    275      3          5  # <- Missing 4 and 5
8  03/01/2021    265      1          6  # <- Missing from 2 to 5


来源: stackexchange

问:
Adding CPTGraphHostingView as a subview
There isn't a lot of questions about this and none of them were answered in a way that could solve my problem, still sorry if I'm asking something that was asked already.

My problem is that I'd like to use core plot to draw a graph inside a view. So I add the view on IB in my appviewcontroller.xib , but thenI can't find how to link that specific zone I just defined on IB to the file's owner.

A bit of precision: I managed to use core plot in another application, when it was the main view, but now that I want to add it to an existing application, so an existing view, it doesn't work...

And to add the new zone, I just went into IB, and dragged a view from the objects library onto my appviewcontroller.xib.

So how do I link that particular view to the code I wrote for it ?

Thanks for any help !

答:
U have to add uiview created to self.view,then add graph hosting view to it...
Try this</p>

```<code>- (void)loadView {
 self.view =view1;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    CPGraphHostingView *hostingView = [[CPGraphHostingView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    hostingView.backgroundColor=[UIColor whiteColor];
    graph = [[CPXYGraph alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

    hostingView.hostedGraph = graph;
    [view1 addSubview:hostingView];
</code>```

ContentLicense: CC BY-SA 3.0

Title: Adding CPTGraphHostingView as a subview

Body:
U have to add uiview created to self.view,then add graph hosting view to it...
Try this

- (void)loadView {
 self.view =view1;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    CPGraphHostingView *hostingView = [[CPGraphHostingView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    hostingView.backgroundColor=[UIColor whiteColor];
    graph = [[CPXYGraph alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

    hostingView.hostedGraph = graph;
    [view1 addSubview:hostingView];


问:
gyp ERR! build error gyp ERR! stack Error: `make` failed with exit code: 2 when pushing on heroku
When pushing my rails project on Heroku i get:

remote:        gyp ERR! build error

remote:        gyp ERR! stack Error: make failed with exit code: 2

remote:        gyp ERR! stack     at ChildProcess.onExit (/tmp/build_47b2dcad/node_modules/node-gyp/lib/build.js:262:23)
remote:        gyp ERR! stack     at ChildProcess.emit (node:events:390:28)

remote:        gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
remote:        gyp ERR! System Linux 4.4.0-1097-aws

remote:        gyp ERR! command "/tmp/build_47b2dcad/bin/node" "/tmp/build_47b2dcad/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="

remote:        gyp ERR! cwd /tmp/build_47b2dcad/node_modules/node-sass

remote:        gyp ERR! node -v v16.13.1

remote:        gyp ERR! node-gyp -v v3.8.0

remote:        gyp ERR! not ok

remote:        Build failed with error code: 1

remote:

remote:  !

remote:  !     Precompiling assets failed.

remote:  !

remote:  !     Push rejected, failed to compile Ruby app.

does somebody know how to help me?

答:
Had the same problem with node v16 and nodes-sass. (Was using v14 on development machine)

Perhaps this answer will help

Heroku fails during build with Error: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (93)

ContentLicense: CC BY-SA 4.0


问:
popular free-to-use api doesn't seem to work
I'm trying to use this api in my pet project,
 but when I test it on docs page - POST request "create User"
 it always sends back 401: Unauthorized
The question is: how I can create a new user?

I think this free-to-use api is very popular:
api link:

https://nestjs-boilerplate-test.herokuapp.com/docs/#/

答:
It is happening because you are not authorized to use the api.

You need a TOKEN or an API KEY to be able to make request to that API server.


问:
Using AWK to substitute
First time attempting to tinker with AWK and use it to take input from a file like the following:

data.csv

James,Jones,30,Mr,Main St

Melissa,Greene,200,Mrs,Wall St

Robert,Krupp,410,Mr,Random St

and process it into a LaTeX Template

data.tex

```<code>\newcommand{\customertitle}{XYZ} %ggf. \
\newcommand{\customerName}{Max Sample} % Name \
\newcommand{\customerStreet}{Str} % Street \
\newcommand{\customerZIP}{12345} % ZIP
</code>```

First I tried to replace the customer name this way

```<code>awk 'BEGIN{FS=","}{print $1 " " $2 }' data.csv | xargs -I{} sed "s/Max Sample/{}/" data.tex > names
</code>```

which gave me a merged file.. and therefore I subsequently attempted to render the file as single .tex files by inserting a keyword "#TEST" at the end of the original file, so I could use it as a Record Separator to get me back to single files with the following command:

```<code>awk 'BEGIN {FS=RS="#TEST"} {i=1}{ while (i <= NF) {print $i >>"final"NR".tex"; i++}}' names
</code>```

Even though that worked for this one field, for multiple fields it doesn't seem to be a proper solution as is though. (title, street, zip code)

That's why I'm now attempting to get it working with the gsub action in AWK.

Tried those different approaches. Based on what I could find regarding it thus far, that's what I came up with:

```<code>awk 'BEGIN {FS=","}NR==FNR{a[FNR]=$4;next}{gsub ("XYZ",a[FNR]);print}' data.csv data.tex
</code>```

which replaces XYZ with  nothing

```<code>awk 'BEGIN {FS=","}NR==FNR{a[FNR]=$4;next}RS="#TEST"{for (i in a) {gsub("XYZ",i);print}}' data.csv data.tex \
</code>```

which counts four times to 7

Tried those also with the merged file, ie. the "names" output from the first command and didn't get it to work.

What am I missing? Can the gsub command not replace a string with an array? Is a loop required?

I'm stuck, hope someone can help out here

答:
I feel like doing replaces is unnecessary and would probably approach it like this:

awk -F, -v po='\\newcommand{\\%s}{%s} %s \n' '{
    printf po, "customertitle", $4, "%ggf. \\"
    printf po, "customerName", $1" "$2, "% Name \\"
    printf po, "customerStreet", $NF, "% Street \\"
    printf po, "customerZip", $3, "% Zip"
}' data.csv
```
<p>output:</p>
```\newcommand{\customertitle}{Mr} %ggf. \
\newcommand{\customerName}{James Jones} % Name \
\newcommand{\customerStreet}{Main St} % Street \
\newcommand{\customerZip}{30} % Zip
\newcommand{\customertitle}{Mrs} %ggf. \
\newcommand{\customerName}{Melissa Greene} % Name \
\newcommand{\customerStreet}{Wall St} % Street \
\newcommand{\customerZip}{200} % Zip
\newcommand{\customertitle}{Mr} %ggf. \
\newcommand{\customerName}{Robert Krupp} % Name \
\newcommand{\customerStreet}{Random St} % Street \
\newcommand{\customerZip}{410} % Zip
```

Title: Using AWK to substitute

Body:
First time attempting to tinker with AWK and use it to take input from a file like the following:

data.csv

James,Jones,30,Mr,Main St

Melissa,Greene,200,Mrs,Wall St

Robert,Krupp,410,Mr,Random St

and process it into a LaTeX Template

data.tex

\newcommand{\customertitle}{XYZ} %ggf. \
\newcommand{\customerName}{Max Sample} % Name \
\newcommand{\customerStreet}{Str} % Street \
\newcommand{\customerZIP}{12345} % ZIP

First I tried to replace the customer name this way

awk 'BEGIN{FS=","}{print $1 " " $2 }' data.csv | xargs -I{} sed "s/Max Sample/{}/" data.tex > names

which gave me a merged file.. and therefore I subsequently attempted to render the file as single .tex files by inserting a keyword "#TEST" at the end of the original file, so I could use it as a Record Separator to get me back to single files with the following command:

awk 'BEGIN {FS=RS="#TEST"} {i=1}{ while (i <= NF) {print $i >>"final"NR".tex"; i++}}' names

Even though that worked for this one field, for multiple fields it doesn't seem to be a proper solution as is though. (title, street, zip code)

That's why I'm now attempting to get it working with the gsub action in AWK.

Tried those different approaches. Based on what I could find regarding it thus far, that's what I came up with:

awk 'BEGIN {FS=","}NR==FNR{a[FNR]=$4;next}{gsub ("XYZ",a[FNR]);print}' data.csv data.tex

which replaces XYZ with  nothing

awk 'BEGIN {FS=","}NR==FNR{a[FNR]=$4;next}RS="#TEST"{for (i in a) {gsub("XYZ",i);print}}' data.csv data.tex \

which counts four times to 7

Tried those also with the merged file, ie. the "names" output from the first command and didn't get it to work.

What am I missing? Can the gsub command not replace a string with an array? Is a loop required?

I'm stuck, hope someone can help out here

Body:
I feel like doing replaces is unnecessary and would probably approach it like this:

awk -F, -v po='\\newcommand{\\%s}{%s} %s \n' '{
    printf po, "customertitle", $4, "%ggf. \\"
    printf po, "customerName", $1" "$2, "% Name \\"
    printf po, "customerStreet", $NF, "% Street \\"
    printf po, "customerZip", $3, "% Zip"
}' data.csv

output:

\newcommand{\customertitle}{Mr} %ggf. \
\newcommand{\customerName}{James Jones} % Name \
\newcommand{\customerStreet}{Main St} % Street \
\newcommand{\customerZip}{30} % Zip
\newcommand{\customertitle}{Mrs} %ggf. \
\newcommand{\customerName}{Melissa Greene} % Name \
\newcommand{\customerStreet}{Wall St} % Street \
\newcommand{\customerZip}{200} % Zip
\newcommand{\customertitle}{Mr} %ggf. \
\newcommand{\customerName}{Robert Krupp} % Name \
\newcommand{\customerStreet}{Random St} % Street \
\newcommand{\customerZip}{410} % Zip


问:
invalid identifier while parsing json
I am compiling a dbt base model. Currently I get this error below. Line 6 looks the same as other lines above. Might a small syntax error that I could not spot.

```<code>15:40:22  Database Error in model base_datacenter_handling_unit (models/l10_staging_datacenter/base_unit.sql)
15:40:22    000904 (42000): SQL compilation error: error line 6 at position 3
15:40:22    invalid identifier 'VALUE'
15:40:22    compiled SQL at target/run/dbt/models/l10_staging_datacenter/base_unit.sql
</code>```

This is how my file looks like:

```<code>SELECT
    JSON_DATA:"key"::text AS KEY
    , value:"description"::text AS DESCRIPTION
  , value:"globalHandlingUnitId"::text AS GLOBAL_HANDLING_UNIT_ID
  , value:"tareWeight"::NUMBER(38,0) AS TARTE_WEIGHT
  , value:"tareWeight_unit"::text AS TARTE_WEIGHT_UNIT
  , value:"width"::NUMBER(38,0) AS WIDTH
  , value:"width_unit"::text AS WIDTH_UNIT
  , value:"length"::NUMBER(38,0) AS LENGTH
    , value:"validFrom"::TIMESTAMP_NTZ AS VALID_FROM_TS_UTC
    , value:"validTo"::TIMESTAMP_NTZ AS VALID_TO_TS_UTC
    , value:"lastModified"::TIMESTAMP_NTZ AS LAST_MODIFIED_TS_UTC
  , value:"status"::text AS STATUS
    , md5(KEY::STRING || MASTERCLIENT_ID) AS HANDLING_UNIT_KEY --different logic than in POSTGRESDWH!
    ,MASTERCLIENT_ID
    ,{{ extract_masterclientname_clause('META_FILENAME') }} AS MASTERCLIENT_NAME
    ,META_ROW_NUM
  ,META_FILENAME
  ,META_LOAD_TS_UTC
  ,META_FILE_TS_UTC
  ,CASE WHEN {{table_dedup_clause('HANDLING_UNIT_KEY')}}
    THEN True
    ELSE False
  END AS IS_RECORD_CURRENT
FROM {{ source('INGEST_DATACENTER', 'HANDLING_UNIT') }} src
QUALIFY {{table_dedup_clause('HANDLING_UNIT_KEY')}}
</code>```

It could also be because of the STRING type md5(KEY::STRING || MASTERCLIENT_ID)  I am using with md5 but I have another file, which is based on the same pattern but it does not throw an error tho:

```<code>SELECT
    JSON_DATA:"issueId"::NUMBER(38,0) AS ISSUE_ID
    , value:"slaName"::text AS SLA_NAME
    , value:"slaTimeLeft"::NUMBER(38,0) AS SLA_TIME_USED_SECONDS
    , md5(ISSUE_ID::STRING || SLA_NAME) AS ISSUE_SLA_ID
    ,MASTERCLIENT_ID
    ,{{ extract_masterclientname_clause('META_FILENAME') }} AS MASTERCLIENT_NAME
    ,META_ROW_NUM
  ,META_FILENAME
  ,META_LOAD_TS_UTC
  ,META_FILE_TS_UTC
,CASE WHEN {{table_dedup_clause('ISSUE_SLA_ID')}}
    THEN True
    ELSE False
  END AS IS_RECORD_CURRENT
FROM {{ source('INGEST_EMS', 'ISSUES') }} src
    , lateral flatten ( input => JSON_DATA:slas)
QUALIFY {{table_dedup_clause('ISSUE_SLA_ID')}}
</code>```

I don't see any significant difference between the two

答:
value is the output columns of a FLATTEN which you have in your second SQL. But not your first.

This is where putting an alias of every table, and using it on EVERY usage, you would see something like

```<code>SELECT t.json_data:"key",
   f.value:"json_prop_name"
FROM table AS t;
</code>```

and be like, where does f come from...

Title: invalid identifier while parsing json

Body:
I am compiling a dbt base model. Currently I get this error below. Line 6 looks the same as other lines above. Might a small syntax error that I could not spot.

15:40:22  Database Error in model base_datacenter_handling_unit (models/l10_staging_datacenter/base_unit.sql)
15:40:22    000904 (42000): SQL compilation error: error line 6 at position 3
15:40:22    invalid identifier 'VALUE'
15:40:22    compiled SQL at target/run/dbt/models/l10_staging_datacenter/base_unit.sql

This is how my file looks like:

SELECT
    JSON_DATA:"key"::text AS KEY
    , value:"description"::text AS DESCRIPTION
  , value:"globalHandlingUnitId"::text AS GLOBAL_HANDLING_UNIT_ID
  , value:"tareWeight"::NUMBER(38,0) AS TARTE_WEIGHT
  , value:"tareWeight_unit"::text AS TARTE_WEIGHT_UNIT
  , value:"width"::NUMBER(38,0) AS WIDTH
  , value:"width_unit"::text AS WIDTH_UNIT
  , value:"length"::NUMBER(38,0) AS LENGTH
    , value:"validFrom"::TIMESTAMP_NTZ AS VALID_FROM_TS_UTC
    , value:"validTo"::TIMESTAMP_NTZ AS VALID_TO_TS_UTC
    , value:"lastModified"::TIMESTAMP_NTZ AS LAST_MODIFIED_TS_UTC
  , value:"status"::text AS STATUS
    , md5(KEY::STRING || MASTERCLIENT_ID) AS HANDLING_UNIT_KEY --different logic than in POSTGRESDWH!
    ,MASTERCLIENT_ID
    ,{{ extract_masterclientname_clause('META_FILENAME') }} AS MASTERCLIENT_NAME
    ,META_ROW_NUM
  ,META_FILENAME
  ,META_LOAD_TS_UTC
  ,META_FILE_TS_UTC
  ,CASE WHEN {{table_dedup_clause('HANDLING_UNIT_KEY')}}
    THEN True
    ELSE False
  END AS IS_RECORD_CURRENT
FROM {{ source('INGEST_DATACENTER', 'HANDLING_UNIT') }} src
QUALIFY {{table_dedup_clause('HANDLING_UNIT_KEY')}}

It could also be because of the STRING type md5(KEY::STRING || MASTERCLIENT_ID)  I am using with md5 but I have another file, which is based on the same pattern but it does not throw an error tho:

SELECT
    JSON_DATA:"issueId"::NUMBER(38,0) AS ISSUE_ID
    , value:"slaName"::text AS SLA_NAME
    , value:"slaTimeLeft"::NUMBER(38,0) AS SLA_TIME_USED_SECONDS
    , md5(ISSUE_ID::STRING || SLA_NAME) AS ISSUE_SLA_ID
    ,MASTERCLIENT_ID
    ,{{ extract_masterclientname_clause('META_FILENAME') }} AS MASTERCLIENT_NAME
    ,META_ROW_NUM
  ,META_FILENAME
  ,META_LOAD_TS_UTC
  ,META_FILE_TS_UTC
,CASE WHEN {{table_dedup_clause('ISSUE_SLA_ID')}}
    THEN True
    ELSE False
  END AS IS_RECORD_CURRENT
FROM {{ source('INGEST_EMS', 'ISSUES') }} src
    , lateral flatten ( input => JSON_DATA:slas)
QUALIFY {{table_dedup_clause('ISSUE_SLA_ID')}}

I don't see any significant difference between the two

Body:
value is the output columns of a FLATTEN which you have in your second SQL. But not your first.

This is where putting an alias of every table, and using it on EVERY usage, you would see something like

SELECT t.json_data:"key",
   f.value:"json_prop_name"
FROM table AS t;

and be like, where does f come from...


问:
How to write a select Query inside a CASE condition in MS SQL
I have an Sql Query. It does not have any compilation error but in runtime it shows

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

```<code> SELECT a.UserID FROM USERGROUPS a WHERE a.GroupID IN
                      (CASE WHEN @group_id IS NULL THEN (select groupid from usergroups) ELSE
                       CASE WHEN @group_id=0 THEN (select groupid from usergroups  where userid = @userid)ELSE
                      @group_id END END )
</code>```

Thanks in advance.

答:
according to the MSDN

[Case] evaluates a list of conditions and returns one of multiple possible
  result expressions.

basically you can use a SELECT within a CASE, but it only has to return one single result and not a list (which is something that can only be evaluated at runtime, that's why your query results formally correct but fails when you launch it)

If you tell us some more about what you're trying to do, maybe I can help you rewrite your query

Body:
I have an Sql Query. It does not have any compilation error but in runtime it shows

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

 SELECT a.UserID FROM USERGROUPS a WHERE a.GroupID IN
                      (CASE WHEN @group_id IS NULL THEN (select groupid from usergroups) ELSE
                       CASE WHEN @group_id=0 THEN (select groupid from usergroups  where userid = @userid)ELSE
                      @group_id END END )

Thanks in advance.


问:
How to save an ArrayList of Buttons in SharedPreferences
I'd like to save a list of buttons in SharedPreferences but it doesn't work.
The error message that occurs is "java.lang.IllegalArgumentException: class android.graphics.drawable.InsetDrawable declares multiple JSON fields named mState"

```<code>
public boolean writeToSharedPreferences(Context context, ArrayList<Button> arrayList) {

    String file = "list";
    SharedPreferences mPrefs = context.getSharedPreferences(file, Context.MODE_PRIVATE);

    SharedPreferences.Editor prefsEditor = mPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(arrayList);
    prefsEditor.putString("list", json);
    prefsEditor.commit();

    return true;
}

public ArrayList<Button> readFromSharedPreferences(Context context) {

    String file = "list";
    SharedPreferences mPrefs = context.getSharedPreferences(file, Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = mPrefs.getString("list", "");
    Type type = new TypeToken<List<Button>>(){}.getType();
    ArrayList<Button> arrayList= gson.fromJson(json, type);
    return arrayList;
}

</code>```

Can someone help me pls?

答:
You can't.

Buttons are an interactive UI element.  They have behaviors and code (what happens on click) associated with them.  You can't save a Button to shared preferences any more than you can print one out on your printer: what you get would not be a Button, just an image of one that couldn't be pressed.

Consider what you're actually trying to save: is it some information about the state of the system?  Some text?  Save that to shared preferences, then rebuild your UI from that data when you read it back out.

Body:
I'd like to save a list of buttons in SharedPreferences but it doesn't work.
The error message that occurs is "java.lang.IllegalArgumentException: class android.graphics.drawable.InsetDrawable declares multiple JSON fields named mState"

public boolean writeToSharedPreferences(Context context, ArrayList<Button> arrayList) {

    String file = "list";
    SharedPreferences mPrefs = context.getSharedPreferences(file, Context.MODE_PRIVATE);

    SharedPreferences.Editor prefsEditor = mPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(arrayList);
    prefsEditor.putString("list", json);
    prefsEditor.commit();

    return true;
}

public ArrayList<Button> readFromSharedPreferences(Context context) {

    String file = "list";
    SharedPreferences mPrefs = context.getSharedPreferences(file, Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = mPrefs.getString("list", "");
    Type type = new TypeToken<List<Button>>(){}.getType();
    ArrayList<Button> arrayList= gson.fromJson(json, type);
    return arrayList;
}

Can someone help me pls?


问:
How to create a Kotlin Decimal Formatter
I would like to create a decimal formatter that would display up to 2 decimal digits, with a given separator.

For example with separator ","

```<code>input -> output
3.0   -> "3"
3.1   -> "3,1"
3.14  -> "3,14"
3.141 -> "3,14"
3.149 -> "3,15"
</code>```

I would like to do this in Kotlin, I guess I must use DecimalFormat but don't understand how to do so. Could you please help me?

答:
You indeed might use java.text.NumberFormat to achieve your goal. The following should work is quite close to your example Swift code.

// you can change the separators by providing a Locale
val nf = java.text.NumberFormat
    .getInstance(java.util.Locale.GERMAN)
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 2

// you may want to change the rounding mode
nf.roundingMode = java.math.RoundingMode.DOWN

println(nf.format(0)) // 0
println(nf.format(1)) // 1
println(nf.format(1.2)) // 1,2
println(nf.format(1.23)) // 1,23
println(nf.format(1.234)) // 1,23
println(nf.format(12.345)) // 12,34
```

Body:
I would like to create a decimal formatter that would display up to 2 decimal digits, with a given separator.

For example with separator ","

input -> output
3.0   -> "3"
3.1   -> "3,1"
3.14  -> "3,14"
3.141 -> "3,14"
3.149 -> "3,15"

I would like to do this in Kotlin, I guess I must use DecimalFormat but don't understand how to do so. Could you please help me?


问:
How do I check if there are duplicates in a flat list?
For example, given the list ['one', 'two', 'one'], the algorithm should return True, whereas given ['one', 'two', 'three'] it should return False.

答:
Another solution is to use slicing, which will also work with strings and other enumerable things.</p>
```<code>def has_duplicates(x):
    for idx, item in enumerate(x):
        if item in x[(idx + 1):]:
            return True
    return False

>>> has_duplicates(["a", "b", "c"])
False
>>> has_duplicates(["a", "b", "b", "c"])
True
>>> has_duplicates("abc")
False
>>> has_duplicates("abbc")
True
</code>```

Body:
Another solution is to use slicing, which will also work with strings and other enumerable things.

def has_duplicates(x):
    for idx, item in enumerate(x):
        if item in x[(idx + 1):]:
            return True
    return False

>>> has_duplicates(["a", "b", "c"])
False
>>> has_duplicates(["a", "b", "b", "c"])
True
>>> has_duplicates("abc")
False
>>> has_duplicates("abbc")
True


问:
Java reflection not working properly
I have a code like this

```<code>final Method method = XYZClass.class.getDeclaredMethod(METHOD_NAME, new Class[] {List.class, List.class});
 method.setAccessible(true);
final List<Integer> output = (List<Integer>) method.invoke(METHOD_NAME, new Object[] {inputRecords, foo});
</code>```

inputRecords is a List of object and foo is an object.

I am getting object is not an instance of declaring class.??

答:
You're trying to invoke the method on your method name (i.e. a string). You should be invoking it on a reference to an instance of XYZClass:

```<code>XYZClass xyz = ...;
final List<Integer> output = (List<Integer>) method.invoke(xyz,
                                     new Object[] {inputRecords, foo});
</code>```

If it's a static method, use null as the first argument.

Title: Java reflection not working properly

Body:
I have a code like this

final Method method = XYZClass.class.getDeclaredMethod(METHOD_NAME, new Class[] {List.class, List.class});
 method.setAccessible(true);
final List<Integer> output = (List<Integer>) method.invoke(METHOD_NAME, new Object[] {inputRecords, foo});

inputRecords is a List of object and foo is an object.

I am getting object is not an instance of declaring class.??

Body:
You're trying to invoke the method on your method name (i.e. a string). You should be invoking it on a reference to an instance of XYZClass:

XYZClass xyz = ...;
final List<Integer> output = (List<Integer>) method.invoke(xyz,
                                     new Object[] {inputRecords, foo});

If it's a static method, use null as the first argument.


问:
Build System CTA's/Callback function not working
I am working on a build/design system. and everything works fine. The only issue is when I publish my package and attempt to use the callback function. It doesn't properly return the data that is necessary for me to go to the next screen.

I attempted to get a reproducible example for you in CodeSandbox, however, there were some minor implications/errors that wouldn't allow me to get to the specific error I am talking to you about now. That seems to have its own issues.

So, how do you reproduce this error? Well, our package as of right now is public. As said above you can't import into CodeSandbox as it gives other errors on React versions (as said, I will deal with that later..). The package name is @sandboxcommerceeng/react the scss package you might need is @sandboxcommerceeng/scss. Go ahead and import into a CSS file. @import '@sandboxcommerceeng/scss/lib/global.css'. Then in the @sandboxcommerceeng/react package, import ECommercePlatformModal. The code below will give you a reproducible error. Platforms type, is also exported by @sandboxcommerceeng/react

```<code>const [showEcommerceModal, setShowEcommerceModal] = React.useState<boolean>(false);
const [url, setUrl] = React.useState<string>('');
const [selectedPlatform, setSelectedPlatform] = React.useState<keyof Platforms>();

<ECommercePlatformModal
  selectedPlatform={selectedPlatform}
  onSelectPlatform={(platform: keyof Platforms | undefined) =>
    setSelectedPlatform(platform)
  }
  showModal={showEcommerceModal}
  onCancel={() => setShowEcommerceModal(false)}
  okButtonProps={{ onClick: () => console.log(url) }} // ✴
  urlValidated={true}
  onUrlChange={(e: React.ChangeEvent<HTMLInputElement>) => {
    setUrl(e.target.value);
  }}
  url={url}
/>
</code>```

✴: I am unable to get the URL from the state using a callback. I've tried just referencing a callback function separately and then logging the URL from there. I've also tried pasting in the URL from the callback. Nothing is working.

End Goal

The end goal here is to have it so that I am able to apply my package into my React application and have the package functionality, i.e. the javascript code implemented in the package itself, work as expected. Expectation for this particular component, is to be able to console.log the url and have it show in the package from the callback function okButtonProp{{onClick: () => console.log(url)}}

Please let me know if there is anything else you need from me.

答:
After debugging, the issue did lay within the build system itself. Using React.memo on a button component was the culprit. The memoization wasn't working as intended due to the fact that none of the props were actually changing on the component, therefore it wasn't re-rendering the button component with the new function and variables being passed down to it.

I went ahead and removed the memoization from the memoized component, as I couldn't see a way to fit memoization in this instance.

Body:
I am working on a build/design system. and everything works fine. The only issue is when I publish my package and attempt to use the callback function. It doesn't properly return the data that is necessary for me to go to the next screen.

I attempted to get a reproducible example for you in CodeSandbox, however, there were some minor implications/errors that wouldn't allow me to get to the specific error I am talking to you about now. That seems to have its own issues.

So, how do you reproduce this error? Well, our package as of right now is public. As said above you can't import into CodeSandbox as it gives other errors on React versions (as said, I will deal with that later..). The package name is @sandboxcommerceeng/react the scss package you might need is @sandboxcommerceeng/scss. Go ahead and import into a CSS file. @import '@sandboxcommerceeng/scss/lib/global.css'. Then in the @sandboxcommerceeng/react package, import ECommercePlatformModal. The code below will give you a reproducible error. Platforms type, is also exported by @sandboxcommerceeng/react

const [showEcommerceModal, setShowEcommerceModal] = React.useState<boolean>(false);
const [url, setUrl] = React.useState<string>('');
const [selectedPlatform, setSelectedPlatform] = React.useState<keyof Platforms>();

<ECommercePlatformModal
  selectedPlatform={selectedPlatform}
  onSelectPlatform={(platform: keyof Platforms | undefined) =>
    setSelectedPlatform(platform)
  }
  showModal={showEcommerceModal}
  onCancel={() => setShowEcommerceModal(false)}
  okButtonProps={{ onClick: () => console.log(url) }} // ✴
  urlValidated={true}
  onUrlChange={(e: React.ChangeEvent<HTMLInputElement>) => {
    setUrl(e.target.value);
  }}
  url={url}
/>

✴: I am unable to get the URL from the state using a callback. I've tried just referencing a callback function separately and then logging the URL from there. I've also tried pasting in the URL from the callback. Nothing is working.

End Goal

The end goal here is to have it so that I am able to apply my package into my React application and have the package functionality, i.e. the javascript code implemented in the package itself, work as expected. Expectation for this particular component, is to be able to console.log the url and have it show in the package from the callback function okButtonProp{{onClick: () => console.log(url)}}

Please let me know if there is anything else you need from me.


问:
Where to add/remove interceptors while different components are calling apis using an axiosinstance
I have axios instance initialized at the start of application. Under Login.js I am able to get the token and want to add it to the header using interceptors, for most subsequent api calls e.g. when using under AddSampleTable.js . (A few of them will require to go without Authorization header too e.g. ForgotPassword.js)

Currently I have to do this for every single api call in each component. My current code is as follows

axios.js

```<code>import axios from 'axios';

 const baseURL = process.env.REACT_APP_BASE_URL;

 let headers = {};

//this never executes since we havent logged in yet

//if(localStorage.token) {
  //headers.Authorization = `Bearer ${localStorage.token}`;
//}
const token = localStorage.getItem('token');

const axiosInstance = axios.create({

    baseURL: baseURL,
    headers: {'Authorization': token? `Bearer ${token}`: null},
});

export default axiosInstance;
</code>```

Login.js

```<code> import axiosInstance from '../../helpers/axios';

  const printValues = e =>{
  e.preventDefault();
 axiosInstance.post('/auth', data)
 .then(res =>{
  console.log("writing token");
  dispatch(jwtTokenRecieved(res.data.token));
  localStorage.setItem('token',res.data.token);

  const config = {
    headers:{
      Authorization:'Bearer '+res.data.token
    }
  }
  axiosInstance.get('/User/GetUserByID/0', config)
.then(res =>{
    dispatch(isLoggedUser(res.data));
  })
  .catch(err =>{
    console.log(err);
  })
</code>```

AddSampleTable.js

This is where I want to use the instance and token should be present by default but currently I am extracting for each api call from localstorage

```<code>import axiosInstance from '../../helpers/axios';
export default function AddSamplesTable(){
const jwtToken = useSelector(state => state?.token?.data || '');

const retrieveSampleData = () =>{

const config = {
  headers:{
    Authorization:'Bearer '+ jwtToken,
    'Content-Type': 'application/json'
  }
}
axiosInstance.get('/batch/'+CoCData.id, config)
    .then(function (response) {
      setSamples(response.data.samples);
    })
    .catch(function (error) {
      console.log(error);
    });
}

}
</code>```

Note I am also using reducers and actions to set token into the localStorage as you see in (in addition to saving it via setItem)

```<code>dispatch(jwtTokenRecieved(res.data.token));
</code>```

Update: I have tried using interceptors in axios.js after create function as follows

```<code>axiosInstance.interceptors.request.use(
config => {
console.log(config)
  const token = JSON.parse(localStorage.getItem('token'));
  config.headers.Authorization =  token ? `Bearer ${token}`: null;

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

but when a new user logs in, the existing token value does not get updated with the new token and I get

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'status')

答:
An opinionated answer here, but I would argue in favour of splitting your React app's code into two areas:

VIEWS

By all means use the React style, where each source file contains only functions, and follow React best practice.

GENERAL CODE / API CALLS

Classes often work better here, in terms of encapsulating code and data together in a single instance. Pass an ApiClient or LoginClient instance around as props where  needed. API calls from views will then always be a clean one liner, with zero code duplication.

EXAMPLE CODE

See this Curity code example. Note also that security related data is stored only in memory, which is often better from a security viewpoint. Tokens in local storage have greater XSS risks.

Body:
I have axios instance initialized at the start of application. Under Login.js I am able to get the token and want to add it to the header using interceptors, for most subsequent api calls e.g. when using under AddSampleTable.js . (A few of them will require to go without Authorization header too e.g. ForgotPassword.js)

Currently I have to do this for every single api call in each component. My current code is as follows

axios.js

import axios from 'axios';

 const baseURL = process.env.REACT_APP_BASE_URL;

 let headers = {};

//this never executes since we havent logged in yet

//if(localStorage.token) {
  //headers.Authorization = `Bearer ${localStorage.token}`;
//}
const token = localStorage.getItem('token');

const axiosInstance = axios.create({

    baseURL: baseURL,
    headers: {'Authorization': token? `Bearer ${token}`: null},
});

export default axiosInstance;

Login.js

 import axiosInstance from '../../helpers/axios';

  const printValues = e =>{
  e.preventDefault();
 axiosInstance.post('/auth', data)
 .then(res =>{
  console.log("writing token");
  dispatch(jwtTokenRecieved(res.data.token));
  localStorage.setItem('token',res.data.token);

  const config = {
    headers:{
      Authorization:'Bearer '+res.data.token
    }
  }
  axiosInstance.get('/User/GetUserByID/0', config)
.then(res =>{
    dispatch(isLoggedUser(res.data));
  })
  .catch(err =>{
    console.log(err);
  })

AddSampleTable.js

This is where I want to use the instance and token should be present by default but currently I am extracting for each api call from localstorage

import axiosInstance from '../../helpers/axios';
export default function AddSamplesTable(){
const jwtToken = useSelector(state => state?.token?.data || '');

const retrieveSampleData = () =>{

const config = {
  headers:{
    Authorization:'Bearer '+ jwtToken,
    'Content-Type': 'application/json'
  }
}
axiosInstance.get('/batch/'+CoCData.id, config)
    .then(function (response) {
      setSamples(response.data.samples);
    })
    .catch(function (error) {
      console.log(error);
    });
}

}

Note I am also using reducers and actions to set token into the localStorage as you see in (in addition to saving it via setItem)

dispatch(jwtTokenRecieved(res.data.token));

Update: I have tried using interceptors in axios.js after create function as follows

axiosInstance.interceptors.request.use(
config => {
console.log(config)
  const token = JSON.parse(localStorage.getItem('token'));
  config.headers.Authorization =  token ? `Bearer ${token}`: null;

  return config;
    }
);

but when a new user logs in, the existing token value does not get updated with the new token and I get

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'status')


问:
Spring Integration: Inbound File Adapter drops files when service restarts
We're using the S3InboundFileSynchronizingMessageSource feature of Spring Integration to locally sync and then send messages for any files retrieved from an S3 bucket.

Before syncing, we apply a couple of S3PersistentAcceptOnceFileListFilter filters (to check the file's TimeModified and Hash/ETag) to make sure we only sync "new" files.

Note: We use the JdbcMetadataStore table to persist the record of the files that have previously made it through the filters (using a different REGION for each filter).

Finally, for the S3InboundFileSynchronizingMessageSource local filter, we have a <s>S3PersistentAcceptOnceFileListFilter</s> FileSystemPersistentAcceptOnceFileListFilter -- again on TimeModified and again persisted but in a different region.

The issue is: if the service is restarted after the file has made it through the 1st filter but before the message source successfully sent the message along, we essentially drop the file and never actually process it.

What are we doing wrong? How can we avoid this "dropped file" issue?

答:
I assume you use a FileSystemPersistentAcceptOnceFileListFilter for the localFilter since S3PersistentAcceptOnceFileListFilter is not going to work there.

Let see how you use those filters in the configuration! I wonder if switching to the ChainFileListFilter for your remote files helps you somehow.

See docs: https://docs.spring.io/spring-integration/docs/current/reference/html/file.html#file-reading

EDIT

if the service is restarted after the file has made it through the 1st filter but before the message source successfully sent the message along

I think Gary is right: you need a transaction around that polling operation which includes filter logic as well.

See docs: https://docs.spring.io/spring-integration/docs/current/reference/html/jdbc.html#jdbc-metadata-store

This way the TX is not going to be committed until the message for a file leaves the polling channel adapter. Therefore after restart you simply will be able to synchronize the rolled back files again. Just because they are not present in the store for filtering.


问:
Xamarin "The executable was signed with invalid entitlements"
I want to test my created iOS app on my iPhone. The build was successful but while xamarin studio tries to transfer the file via usb to my iPhone i got the following error:

```<code>VerifyingApplication: 70%
  PercentComplete: 40
  Status: VerifyingApplication
 ApplicationVerificationFailed: Failed to verify code signature of /private/var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.yNZx88/extracted/<APPName>.app : 0xe8008016 (The executable was signed with invalid entitlements.)
error MT1006: Could not install the application '/Users/<NAME>/Projects/<APPName>/<APPName>/bin/iPhone/Debug/device-builds/iphone8.2-10.2.1/<APPNamr>.app' on the device '<DEVICEName>': Your code signing/provisioning profiles are not correctly configured. Probably you have an entitlement not supported by your current provisioning profile, or your device is not part of the current provisioning profile. Please check the iOS Device Log for details (error: 0xe8008016).
--- inner exception
Xamarin.Installation.FailedInstallException: Your code signing/provisioning profiles are not correctly configured. Probably you have an entitlement not supported by your current provisioning profile, or your device is not part of the current provisioning profile. Please check the iOS Device Log for details (error: 0xe8008016)

[...]

Application could not be uploaded to the device.
</code>```

I'm new to xamarin and don't know what to do. A apple developer account is available and the certificate and provisioning Profile are created. The phone is added to device list and a identifier is are created.

Can anyone help me?

答:
In my case the app was running fine on my iPhone 12 Pro but when I tried to run it on an old iPad Air I got this error.  It turns out that I have more than one identifier in https://developer.apple.com/account/resources/identifiers/list and I had configured the iPad with the wrong one.

Once I created a profile for the iPad in https://developer.apple.com/account/resources/profiles/list with the other identifier the error went away.

So to sum it up

make sure that an identifier in https://developer.apple.com/account/resources/identifiers/list is configured for the app you are running.  The App ID should match the Bundle Identifier in Info.plist.

make sure your device is registered in https://developer.apple.com/account/resources/devices/list.  Your device should be added here automatically when connected to a mac running Xcode but it can be added manually by copying the UDID from Xcode Window/Devices and Simulators.

make sure there is a profile in https://developer.apple.com/account/resources/profiles/list that pairs the identifier and device from above

Body:
I want to test my created iOS app on my iPhone. The build was successful but while xamarin studio tries to transfer the file via usb to my iPhone i got the following error:

VerifyingApplication: 70%
  PercentComplete: 40
  Status: VerifyingApplication
 ApplicationVerificationFailed: Failed to verify code signature of /private/var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.yNZx88/extracted/<APPName>.app : 0xe8008016 (The executable was signed with invalid entitlements.)
error MT1006: Could not install the application '/Users/<NAME>/Projects/<APPName>/<APPName>/bin/iPhone/Debug/device-builds/iphone8.2-10.2.1/<APPNamr>.app' on the device '<DEVICEName>': Your code signing/provisioning profiles are not correctly configured. Probably you have an entitlement not supported by your current provisioning profile, or your device is not part of the current provisioning profile. Please check the iOS Device Log for details (error: 0xe8008016).
--- inner exception
Xamarin.Installation.FailedInstallException: Your code signing/provisioning profiles are not correctly configured. Probably you have an entitlement not supported by your current provisioning profile, or your device is not part of the current provisioning profile. Please check the iOS Device Log for details (error: 0xe8008016)

[...]

Application could not be uploaded to the device.

I'm new to xamarin and don't know what to do. A apple developer account is available and the certificate and provisioning Profile are created. The phone is added to device list and a identifier is are created.

Can anyone help me?


问:
No sound from emulator
After upgrading Android studio to Bumblebee (Windows) I get no sound from emulators in PC laptop speakers running Visual Studio Code but have sound in Bluetooth headphones. Any suggestion appreciated!</p>

答: As often before the problem was my inexperience. The emulator sound can be turn on in  Windows  Advanced sound options, by default it is off.

Title: No sound from emulator


问:
Create a self-signed certificate in Java for AWS IoT
I have a root CA certificate along with its private key (CAcert.pem and CApvtkey.key).

The root CA certificate has been registered on the AWS IoT core. This will be used to self-sign and validate other certificates for authentication.

I am trying to create certificates signed by my root CA certificate using Java, but not much luck.

The AWS IoT Java SDK provides functions to generate certificates, and to register/activate them on AWS, but I can't figure out how to sign them with my root CA certificate and activate them.

What I have is this only :

```<code>  //Previous code sets up thing name etc...

  CreateThingResult resp1 = client.createThing(thingRequest);

  CreateKeysAndCertificateRequest req = new CreateKeysAndCertificateRequest();
  req.setSetAsActive(true);
  CreateKeysAndCertificateResult resp2 = client.createKeysAndCertificate(req);

  client.attachThingPrincipal(new AttachThingPrincipalRequest().
            withPrincipal(resp2.getCertificateArn()).withThingName("Java-App_Thing"));
</code>```

Would anybody have an idea how I can create my certificates which will be signed by my CA certificate?

答:
Thanks!!!
above steps are working for me and code requires below dependency,

```<code><dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>iot</artifactId>
    <version>2.17.121</version>
</dependency>
</code>```

Also here I used another library for the same process.
Steps are,

Register the RootCA with Verification certificate in AWS IoT core

Create the thing and attach device certificate and policy to connect programatically

So now in detail:

Register the RootCA with Verification certificate in AWS IoT core

Follow the link
https://docs.aws.amazon.com/iot/latest/developerguide/register-CA-cert.html

Create the thing and attach device certificate and policy to connect programatically

Below steps needed to do the process programatically,

Dependencies needed:

```<code><dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-iot-device-sdk-java</artifactId>
    <version>1.3.9</version>
</dependency>

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-core</artifactId>
    <version>1.12.150</version>
</dependency>

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-iot</artifactId>
    <version>1.12.150</version>
</dependency>
</code>```

Aws config class:

```<code>public class AwsConfig {

    @Bean
    public AWSIot getIotClient() {
        return AWSIotClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("users_aws_access_key", "users_aws_secret_key")))
                .withRegion("users_aws_region").build();
    }
}
</code>```

Service class:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.amazonaws.services.iot.model.AttachPolicyRequest;
import com.amazonaws.services.iot.model.AttachPolicyResult;
import com.amazonaws.services.iot.model.AttachThingPrincipalRequest;
import com.amazonaws.services.iot.model.AttachThingPrincipalResult;
import com.amazonaws.services.iot.model.CertificateStatus;
import com.amazonaws.services.iot.model.CreateThingRequest;
import com.amazonaws.services.iot.model.CreateThingResult;
import com.amazonaws.services.iot.model.DescribeThingRequest;
import com.amazonaws.services.iot.model.DescribeThingResult;
import com.amazonaws.services.iot.model.RegisterCertificateRequest;
import com.amazonaws.services.iot.model.RegisterCertificateResult;
import com.amazonaws.services.iot.model.ResourceNotFoundException;

@Service
public class RegisterService {

    @Autowired
    private AwsConfig iotClient;

    public String RegisterDevice() {

        // check if thing Already exists
        if (!describeThing("Unique Id of Device")) {

            // Thing Creation
            CreateThingResult response = iotClient.getIotClient()
                    .createThing(new CreateThingRequest().withThingName("Unique Id of Device/Thing"));

            // Register and activate the Public Key of the device
            RegisterCertificateResult registerCert = iotClient.getIotClient()
                    .registerCertificate(new RegisterCertificateRequest().withCaCertificatePem("CA Pem as String")
                            .withCertificatePem("Device Public Key in Pem as String").withStatus(CertificateStatus.ACTIVE));

            // Attach the Cert to the thing
            AttachThingPrincipalResult attachThingPrincipalResult = iotClient.getIotClient().attachThingPrincipal(
                    new AttachThingPrincipalRequest()
                        .withThingName("Unique Id of Device/Thing").withPrincipal(registerCert.getCertificateArn()));

            // Attach policies to the thing so it can connect
            AttachPolicyResult policyResult = iotClient.getIotClient()
                    .attachPolicy(new AttachPolicyRequest()
                        .withPolicyName("policy_that_allow_device_connections").withTarget(registerCert.getCertificateArn()));

            return "Thing Created Successfully";
        }

        // Thing exists
        return "Thing Already Exists on IoT Console";
    }

    private boolean describeThing(String thingName) {
        if (thingName == null) {
            return false;
        }
        try {
            describeThingResponse(thingName);
            return true;
        } catch (ResourceNotFoundException e) {
            // e.printStackTrace();
            return false;
        }
    }

    private DescribeThingResult describeThingResponse(String thingName) {
        DescribeThingRequest describeThingRequest = new DescribeThingRequest();
        describeThingRequest.setThingName(thingName);
        return iotClient.getIotClient().describeThing(describeThingRequest);
    }

}
</code>```

Body:
I have a root CA certificate along with its private key (CAcert.pem and CApvtkey.key).

The root CA certificate has been registered on the AWS IoT core. This will be used to self-sign and validate other certificates for authentication.

I am trying to create certificates signed by my root CA certificate using Java, but not much luck.

The AWS IoT Java SDK provides functions to generate certificates, and to register/activate them on AWS, but I can't figure out how to sign them with my root CA certificate and activate them.

What I have is this only :

  //Previous code sets up thing name etc...

  CreateThingResult resp1 = client.createThing(thingRequest);

  CreateKeysAndCertificateRequest req = new CreateKeysAndCertificateRequest();
  req.setSetAsActive(true);
  CreateKeysAndCertificateResult resp2 = client.createKeysAndCertificate(req);

  client.attachThingPrincipal(new AttachThingPrincipalRequest().
            withPrincipal(resp2.getCertificateArn()).withThingName("Java-App_Thing"));

Would anybody have an idea how I can create my certificates which will be signed by my CA certificate?

Body:
Thanks!!!
above steps are working for me and code requires below dependency,

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>iot</artifactId>
    <version>2.17.121</version>
</dependency>

Also here I used another library for the same process.
Steps are,

Register the RootCA with Verification certificate in AWS IoT core

Create the thing and attach device certificate and policy to connect programatically

So now in detail:

Register the RootCA with Verification certificate in AWS IoT core

Follow the link
https://docs.aws.amazon.com/iot/latest/developerguide/register-CA-cert.html

Create the thing and attach device certificate and policy to connect programatically

Below steps needed to do the process programatically,

Dependencies needed:

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-iot-device-sdk-java</artifactId>
    <version>1.3.9</version>
</dependency>

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-core</artifactId>
    <version>1.12.150</version>
</dependency>

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-iot</artifactId>
    <version>1.12.150</version>
</dependency>

Aws config class:

public class AwsConfig {

    @Bean
    public AWSIot getIotClient() {
        return AWSIotClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("users_aws_access_key", "users_aws_secret_key")))
                .withRegion("users_aws_region").build();
    }
}

Service class:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.amazonaws.services.iot.model.AttachPolicyRequest;
import com.amazonaws.services.iot.model.AttachPolicyResult;
import com.amazonaws.services.iot.model.AttachThingPrincipalRequest;
import com.amazonaws.services.iot.model.AttachThingPrincipalResult;
import com.amazonaws.services.iot.model.CertificateStatus;
import com.amazonaws.services.iot.model.CreateThingRequest;
import com.amazonaws.services.iot.model.CreateThingResult;
import com.amazonaws.services.iot.model.DescribeThingRequest;
import com.amazonaws.services.iot.model.DescribeThingResult;
import com.amazonaws.services.iot.model.RegisterCertificateRequest;
import com.amazonaws.services.iot.model.RegisterCertificateResult;
import com.amazonaws.services.iot.model.ResourceNotFoundException;

@Service
public class RegisterService {

    @Autowired
    private AwsConfig iotClient;

    public String RegisterDevice() {

        // check if thing Already exists
        if (!describeThing("Unique Id of Device")) {

            // Thing Creation
            CreateThingResult response = iotClient.getIotClient()
                    .createThing(new CreateThingRequest().withThingName("Unique Id of Device/Thing"));

            // Register and activate the Public Key of the device
            RegisterCertificateResult registerCert = iotClient.getIotClient()
                    .registerCertificate(new RegisterCertificateRequest().withCaCertificatePem("CA Pem as String")
                            .withCertificatePem("Device Public Key in Pem as String").withStatus(CertificateStatus.ACTIVE));

            // Attach the Cert to the thing
            AttachThingPrincipalResult attachThingPrincipalResult = iotClient.getIotClient().attachThingPrincipal(
                    new AttachThingPrincipalRequest()
                        .withThingName("Unique Id of Device/Thing").withPrincipal(registerCert.getCertificateArn()));

            // Attach policies to the thing so it can connect
            AttachPolicyResult policyResult = iotClient.getIotClient()
                    .attachPolicy(new AttachPolicyRequest()
                        .withPolicyName("policy_that_allow_device_connections").withTarget(registerCert.getCertificateArn()));

            return "Thing Created Successfully";
        }

        // Thing exists
        return "Thing Already Exists on IoT Console";
    }

    private boolean describeThing(String thingName) {
        if (thingName == null) {
            return false;
        }
        try {
            describeThingResponse(thingName);
            return true;
        } catch (ResourceNotFoundException e) {
            // e.printStackTrace();
            return false;
        }
    }

    private DescribeThingResult describeThingResponse(String thingName) {
        DescribeThingRequest describeThingRequest = new DescribeThingRequest();
        describeThingRequest.setThingName(thingName);
        return iotClient.getIotClient().describeThing(describeThingRequest);
    }

}


问:
Pointer to **column_array of 2d dynamic array
I have been working on a matrix library project similar to the vector library and am currently stuck at iterators. I have been trying to implement a column iterator for quite some time without the use of other libraries (besides iostream and fstream) and my workaround was to have a **columnVector that contains the references of a specified column when colBegin(i) or colEnd(i) is called. The implementation works but I can't manage to make it work aesthetically without going in myMatrix.columnVector as I want it to be encapsulated, rather I want to call matrix::iterator it = myMatrix.colBegin(i) and to iterate with addition and subtraction but my iterator subclass has only a 1d pointer (for the row iterator, hope I can use it for the column iterator as well).
Do you have an idea how to make a column iterator for a dynamically allocated 2d array?

Example of code (trying to keep it as short as possible):

```<code>using ll = unsigned long long;

template <typename Type> class matrix
{
// Iterator
public:
    class iterator
    {
    protected:
        Type* pointer;

    public:
        iterator() : pointer(nullptr) {}
        iterator(Type* ptr);

        Type& operator * ();
        ...
    };

private:
    ll numberOfColumns, numberOfRows;
    Type** data;

public:    // temporary, wish for it to be private
    Type** columnVector;

public:
    matrix() :  numberOfColumns(NULL), numberOfRows(NULL), data(nullptr), columnVector(nullptr) {}
    matrix(const ll, const ll);
    ~matrix();

    Type*& operator [] (const ll value);

    Type** colBegin(const ll index);
    Type** colEnd(const ll index);
    ...
};

// Thought the constructor might be important since it allocates memory for columnVector as well
template <typename Type> matrix<Type> ::matrix(const ll _numberOfColumns, const ll _numberOfRows)
{
    // Copy _numberOfColumns and _numberOfRows into this
    numberOfColumns = _numberOfColumns;
    numberOfRows = _numberOfRows;

    // Allocates memory for data matrix
    other.data = (Type**) new Type * [numberOfColumns];
    for (size_t i = 0; i < numberOfColumns; i++)
        other.data[i] = (Type*) new Type[numberOfRows];

    // Fills data matrix with 0
    for (size_t i = 0; i < other.numberOfColumns; i++)
        for (size_t j = 0; j < other.numberOfRows; j++)
            other.data[i][j] = 0;

    // Allocation of space for columnVector
    columnVector = new Type * [numberOfRows];
}

template <typename Type> Type** matrix<Type> ::colBegin(const ll index)
{
    for (size_t i = 0; i < numberOfRows; i++)
        columnVector[i] = &data[i][index];
    return columnVector;
}

template <typename Type> Type** matrix<Type> ::colEnd(const ll index)
{
    for (size_t i = 0; i < numberOfRows; i++)
        columnVector[i] = &data[i][index];
    return (columnVector + numberOfRows);
}
</code>```

答:
You don't even need an iterator. Each column is represented with an array. To iterate this array you need to know its beginning and the address of the element after the last one. So the Type* can represent you the iterator:

template <typename Type> class matrix
{
public:
    using column_iterator = Type*;
};
```
<p>So the <code>colBegin</code>/<code>colEnd</code> methods should look like that:</p>
<pre class="lang-cpp prettyprint-override"><code>template<typename Type>
matrix<Type>::column_iterator matrix<Type>::colBegin(const ll index) {
    return data[index];
}

template<typename Type>
matrix<Type>::column_iterator matrix<Type>::colEnd(const ll index) {
    return data[index] + numberOfRows;
}
</code>```

If you find that the code above iterates throught the row (which is not the case, as your contructor clearly describes data[i] as a column), you may define a class that represents an iterator:

class row_iterator {
public:
    row_iterator(Type** data,
                 size_t rowIndex,
                 size_t columnIndex)
      : m_data(data), m_rowIndex(rowIndex), m_columnIndex(columnIndex) {
    }
    bool operator == (const row_iterator &other) const {
        return other.data == m_data &&
               other.m_rowIndex == m_rowIndex &&
               other.m_columnIndex == m_columnIndex;
    }
    row_iterator& operator ++() {
        ++m_columnIndex;
        return *this;
    }
    row_iterator& operator ++(int) {
        row_iterator temp = *this;
        ++*this;
        return temp;
    }
    Type& operator *() const {
        return m_data[m_columnIndex][m_rowIndex];
    }
    // other operators
private:
    Type** m_data;
    size_t m_rowIndex;
    size_t m_columnIndex;
};
```
<p>To use this iterator with the container you need to define:</p>
<pre class="lang-cpp prettyprint-override"><code>    row_iterator rowBegin(size_t rowIndex) {
        return row_iterator(data, rowIndex, 0);
    }
    row_iterator rowEnd(size_t rowIndex) {
        return row_iterator(rowIndex, rowIndex, numberOfColumns);
    }
</code>```

Body:
I have been working on a matrix library project similar to the vector library and am currently stuck at iterators. I have been trying to implement a column iterator for quite some time without the use of other libraries (besides iostream and fstream) and my workaround was to have a **columnVector that contains the references of a specified column when colBegin(i) or colEnd(i) is called. The implementation works but I can't manage to make it work aesthetically without going in myMatrix.columnVector as I want it to be encapsulated, rather I want to call matrix::iterator it = myMatrix.colBegin(i) and to iterate with addition and subtraction but my iterator subclass has only a 1d pointer (for the row iterator, hope I can use it for the column iterator as well).
Do you have an idea how to make a column iterator for a dynamically allocated 2d array?

Example of code (trying to keep it as short as possible):

using ll = unsigned long long;

template <typename Type> class matrix
{
// Iterator
public:
    class iterator
    {
    protected:
        Type* pointer;

    public:
        iterator() : pointer(nullptr) {}
        iterator(Type* ptr);

        Type& operator * ();
        ...
    };

private:
    ll numberOfColumns, numberOfRows;
    Type** data;

public:    // temporary, wish for it to be private
    Type** columnVector;

public:
    matrix() :  numberOfColumns(NULL), numberOfRows(NULL), data(nullptr), columnVector(nullptr) {}
    matrix(const ll, const ll);
    ~matrix();

    Type*& operator [] (const ll value);

    Type** colBegin(const ll index);
    Type** colEnd(const ll index);
    ...
};

// Thought the constructor might be important since it allocates memory for columnVector as well
template <typename Type> matrix<Type> ::matrix(const ll _numberOfColumns, const ll _numberOfRows)
{
    // Copy _numberOfColumns and _numberOfRows into this
    numberOfColumns = _numberOfColumns;
    numberOfRows = _numberOfRows;

    // Allocates memory for data matrix
    other.data = (Type**) new Type * [numberOfColumns];
    for (size_t i = 0; i < numberOfColumns; i++)
        other.data[i] = (Type*) new Type[numberOfRows];

    // Fills data matrix with 0
    for (size_t i = 0; i < other.numberOfColumns; i++)
        for (size_t j = 0; j < other.numberOfRows; j++)
            other.data[i][j] = 0;

    // Allocation of space for columnVector
    columnVector = new Type * [numberOfRows];
}

template <typename Type> Type** matrix<Type> ::colBegin(const ll index)
{
    for (size_t i = 0; i < numberOfRows; i++)
        columnVector[i] = &data[i][index];
    return columnVector;
}

template <typename Type> Type** matrix<Type> ::colEnd(const ll index)
{
    for (size_t i = 0; i < numberOfRows; i++)
        columnVector[i] = &data[i][index];
    return (columnVector + numberOfRows);
}

Body:
You don't even need an iterator. Each column is represented with an array. To iterate this array you need to know its beginning and the address of the element after the last one. So the Type* can represent you the iterator:

template <typename Type> class matrix
{
public:
    using column_iterator = Type*;
};

So the colBegin/colEnd methods should look like that:

template<typename Type>
matrix<Type>::column_iterator matrix<Type>::colBegin(const ll index) {
    return data[index];
}

template<typename Type>
matrix<Type>::column_iterator matrix<Type>::colEnd(const ll index) {
    return data[index] + numberOfRows;
}

If you find that the code above iterates throught the row (which is not the case, as your contructor clearly describes data[i] as a column), you may define a class that represents an iterator:

class row_iterator {
public:
    row_iterator(Type** data,
                 size_t rowIndex,
                 size_t columnIndex)
      : m_data(data), m_rowIndex(rowIndex), m_columnIndex(columnIndex) {
    }
    bool operator == (const row_iterator &other) const {
        return other.data == m_data &&
               other.m_rowIndex == m_rowIndex &&
               other.m_columnIndex == m_columnIndex;
    }
    row_iterator& operator ++() {
        ++m_columnIndex;
        return *this;
    }
    row_iterator& operator ++(int) {
        row_iterator temp = *this;
        ++*this;
        return temp;
    }
    Type& operator *() const {
        return m_data[m_columnIndex][m_rowIndex];
    }
    // other operators
private:
    Type** m_data;
    size_t m_rowIndex;
    size_t m_columnIndex;
};

To use this iterator with the container you need to define:

    row_iterator rowBegin(size_t rowIndex) {
        return row_iterator(data, rowIndex, 0);
    }
    row_iterator rowEnd(size_t rowIndex) {
        return row_iterator(rowIndex, rowIndex, numberOfColumns);
    }


问:
How to retrieve minimum transaction/update time for all table on QLDB
In the doc, we can retrieve history by date, but how to retrieve minimum date for all tables on that ledger?

I tried this:

```<code>SELECT MIN(h.metadata.txTime) FROM history(Clients) AS h
</code>```

but it gives error: <UNKNOWN>: at line <UNKNOWN>, column <UNKNOWN>: <UNKNOWN>; Expected number: 2021-08-04T12:24:07.921Z it seems MIN function only can receives number but there's no way to convert timestamp to epoch/unix timestamp?

also

```<code>SELECT MIN(TO_STRING(h.metadata.txTime,'yyyyMMddHHmmss.SSS')) FROM history(Clients) AS h
</code>```

<UNKNOWN>: at line <UNKNOWN>, column <UNKNOWN>: <UNKNOWN>; Expected number: "20210804122407.921"

(tried postgresql cast style ::float also didn't work)

EDIT: nevermind, there's CAST

```<code>SELECT MIN(CAST(TO_STRING(h.metadata.txTime,'yyyyMMddHHmmss.SSS') AS float)) FROM history(Clients) AS h
</code>```

this one works, but hopefully the float is accurate enough to represent timestamp.

back to the question, how to retrieve from all table?

```<code>Table1 | minTxTime
Table2 | minTxTime
Table3 | minTxTime
</code>```

答:
There are two steps to this:

To get the list of tables in your ledger.

```<code>select tableId from information_schema.user_tables
</code>```

will return a result set of tableIds of all your tables in your ledger, both active and inactive. If you only want active tables, you can add a where clause to the above query:

```<code>select tableId from information_schema.user_tables tables where tables.status = 'ACTIVE'
</code>```

To get your min txTime for each of the table
You can then use the above result and feed it into your other history query.

You can do it programmatically through a driver. Here's the pseudocode:

```<code>result = transaction {
  tables = execute("select tableId from information_schema.user_tables u where u.status = 'ACTIVE'")
  tables.map( t ->
    execute("SELECT MIN(CAST(TO_STRING(h.metadata.txTime,'yyyyMMddHHmmss.SSS') AS float)) FROM history(t)")
  )
}
</code>```

EDIT: Here's a functioning NodeJS code

```<code>import { QldbDriver } from 'amazon-qldb-driver-nodejs';

const ledgerName = "my-test-ledger-1"
const serviceConfigOptions = {region: "us-east-2"};
const qldbDriver = new QldbDriver(ledgerName, serviceConfigOptions);

async function getTables() {
    return new Promise((resolve, reject) => {
        qldbDriver.getTableNames()
        .then((res) => {
            resolve(res);
        })
        .catch((err) => {
            console.log(err);
            reject(err);
        })
    })
}

async function minTxTime(table) {
    return new Promise((resolve, reject) => {
        qldbDriver.executeLambda(async (txn) => {
            const results = (await txn.execute("SELECT MIN(CAST(TO_STRING(h.metadata.txTime,'yyyyMMddHHmmss.SSS') AS float)) as minTxTime FROM history("+table+") as h")).getResultList();
            resolve(results);
        })
        .catch((err) => {
            console.log(err);
            reject(err);
        })
    });
}

async function main() {
    try {
        var tables = await getTables();
        for(var t in tables) {
            var res = await minTxTime(tables[t]);
            console.log(res);
        }
    }
    catch (error) {
        console.error(error);
    }
}

main()
</code>```

Body:
In the doc, we can retrieve history by date, but how to retrieve minimum date for all tables on that ledger?

I tried this:

SELECT MIN(h.metadata.txTime) FROM history(Clients) AS h

but it gives error: <UNKNOWN>: at line <UNKNOWN>, column <UNKNOWN>: <UNKNOWN>; Expected number: 2021-08-04T12:24:07.921Z it seems MIN function only can receives number but there's no way to convert timestamp to epoch/unix timestamp?

also

SELECT MIN(TO_STRING(h.metadata.txTime,'yyyyMMddHHmmss.SSS')) FROM history(Clients) AS h

<UNKNOWN>: at line <UNKNOWN>, column <UNKNOWN>: <UNKNOWN>; Expected number: "20210804122407.921"

(tried postgresql cast style ::float also didn't work)

EDIT: nevermind, there's CAST

SELECT MIN(CAST(TO_STRING(h.metadata.txTime,'yyyyMMddHHmmss.SSS') AS float)) FROM history(Clients) AS h

this one works, but hopefully the float is accurate enough to represent timestamp.

back to the question, how to retrieve from all table?

Table1 | minTxTime
Table2 | minTxTime
Table3 | minTxTime

Body:
There are two steps to this:

To get the list of tables in your ledger.

select tableId from information_schema.user_tables

will return a result set of tableIds of all your tables in your ledger, both active and inactive. If you only want active tables, you can add a where clause to the above query:

select tableId from information_schema.user_tables tables where tables.status = 'ACTIVE'

To get your min txTime for each of the table
You can then use the above result and feed it into your other history query.

You can do it programmatically through a driver. Here's the pseudocode:

result = transaction {
  tables = execute("select tableId from information_schema.user_tables u where u.status = 'ACTIVE'")
  tables.map( t ->
    execute("SELECT MIN(CAST(TO_STRING(h.metadata.txTime,'yyyyMMddHHmmss.SSS') AS float)) FROM history(t)")
  )
}

EDIT: Here's a functioning NodeJS code

import { QldbDriver } from 'amazon-qldb-driver-nodejs';

const ledgerName = "my-test-ledger-1"
const serviceConfigOptions = {region: "us-east-2"};
const qldbDriver = new QldbDriver(ledgerName, serviceConfigOptions);

async function getTables() {
    return new Promise((resolve, reject) => {
        qldbDriver.getTableNames()
        .then((res) => {
            resolve(res);
        })
        .catch((err) => {
            console.log(err);
            reject(err);
        })
    })
}

async function minTxTime(table) {
    return new Promise((resolve, reject) => {
        qldbDriver.executeLambda(async (txn) => {
            const results = (await txn.execute("SELECT MIN(CAST(TO_STRING(h.metadata.txTime,'yyyyMMddHHmmss.SSS') AS float)) as minTxTime FROM history("+table+") as h")).getResultList();
            resolve(results);
        })
        .catch((err) => {
            console.log(err);
            reject(err);
        })
    });
}

async function main() {
    try {
        var tables = await getTables();
        for(var t in tables) {
            var res = await minTxTime(tables[t]);
            console.log(res);
        }
    }
    catch (error) {
        console.error(error);
    }
}

main()


问:
links not working anymore: e.g. https://unpkg.com/vue@3.2.30/dist/vue.min.js
the CDN-link from unpkg isn't working anymore. Other older versions do not work either.

https://unpkg.com/vue@3.2.30/dist/vue.min.js

Which link can I use instead?

THX

```<code><script src="https://unpkg.com/vue@3.2.30/dist/vue.global.prod.js"></script>
<!-- <script src="//unpkg.com/vue@latest/dist/vue.min.js"></script> -->

<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<script src="https://unpkg.com/vue-router"></script>

<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</code>```

these are my sources to load that always worked. How do I replace them?

答:
For Vue 3, the production minified files have .prod.js as their file extension. But it looks like you actually need Vue 2 because you were using the CDN links without a fixed version specifier:

                               ^^^ ⛔ defaults to latest

                               ^^^^^^^^^^ ⛔ no longer Vue 2
```
<p>Vue recently updated <code>vue@latest</code> to version 3. Similarly, <code>vue-router@latest</code> was also updated to version 4, which is only compatible with Vue 3.</p>
<p>To stick with Vue 2 compatible packages, use the following version specifiers in the CDN URLs:</p>
<pre class="lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>

<script src="https://unpkg.com/vue-router@3.5.3/dist/vue-router.min.js"></script>

<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>

</code>```

To avoid these unexpected failures from latest tag updates in the future, you should always use specific fixed versions for CDN links in production.

new Vue({
  data: {
    counter: 0,
  },
}).$mount('#app')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router@3.5.3/dist/vue-router.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
<script src="https://unpkg.com/axios@0.25.0/dist/axios.min.js"></script>

<div id="app">
  <div>counter: {{ counter }}</div>
  <button @click="counter++">+</button>
</div></code>```

Body:
the CDN-link from unpkg isn't working anymore. Other older versions do not work either.

https://unpkg.com/vue@3.2.30/dist/vue.min.js

Which link can I use instead?

THX

these are my sources to load that always worked. How do I replace them?

Body:
For Vue 3, the production minified files have .prod.js as their file extension. But it looks like you actually need Vue 2 because you were using the CDN links without a fixed version specifier:

<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
                               ^^^ ⛔ defaults to latest
<script src="https://unpkg.com/vue@latest/dist/vue.min.js"></script>
                               ^^^^^^^^^^ ⛔ no longer Vue 2

Vue recently updated vue@latest to version 3. Similarly, vue-router@latest was also updated to version 4, which is only compatible with Vue 3.

To stick with Vue 2 compatible packages, use the following version specifiers in the CDN URLs:

<script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>

<script src="https://unpkg.com/vue-router@3.5.3/dist/vue-router.min.js"></script>

<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>

To avoid these unexpected failures from latest tag updates in the future, you should always use specific fixed versions for CDN links in production.

new Vue({
  data: {
    counter: 0,
  },
}).$mount('#app')

<script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router@3.5.3/dist/vue-router.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
<script src="https://unpkg.com/axios@0.25.0/dist/axios.min.js"></script>

<div id="app">
  <div>counter: {{ counter }}</div>
  <button @click="counter++">+</button>
</div>


问:
How to build Json 'body' of http call to API
I am trying to contact a GraphQL API and retrieve the data in Flutter

I have a working call in postman giving me the data back.

I have been referred to an example of a working http call but can't get the body to work. I used an encoded version in my postman call but have been advised to un-encode the "data-raw" of my Postman call and pass Json into the query.

I have the main query and then the variable which is the lat/long

A) Is this the correct approach, using pure Json as opposed to encoded like in my postman call (Example below)

```<code>    {"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n    id\n...
</code>```

B) How can I get the query and variable into the Map data = if this is the correct thing to do?

Here is where I am at, using un-encoded Json in Map data = which isn't being accepted and the $lat $long aren't transferred into query from variables

```<code>Future<http.Response> showMicroMob () async {

  var url ='https://flow-api.fluctuo.com/v1?access_token=my_token';

  Map data = {
    'query': query ($lat: Float!, $lng: Float!) {
  vehicles (lat: $lat, lng: $lng) {
    id
    type
    publicId
    provider {
      slug
    }
    lat
    lng
    propulsion
    battery
    attributes
    ... on Station {
      isVirtual
      availableVehicles
      availableStands
      stationVehicleDetails {
        vehicleType
        propulsion
        availableVehicles
      }
      vehicles {
        id
        publicId
        type
        propulsion
        battery
      }
    }
  }
}
    'variables': {"lat":51.492591,"lng":-0.157221}
  };

  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(Uri.parse(url),
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}
</code>```

Original example

```<code>Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}
</code>```

Update of call

If I shift variable up to make a complete String it no longer recognises the $lat $long fields or the actual lat/long numbers as values and makes them orange text. When I move variables down like in my postman request it of course throws errors, but the numbers are recognised as such ($Lat/$Long still not able to take the value. Tried just hard placing lat/ling figures in and returned

```<code>    flutter: 400 flutter: Bad Request
</code>```

Should I try passing the variables in another way?

```<code>Future<http.Response> showMicroMob () async {

  var url ='https://flow-api.fluctuo.com/v1?access_token=x';

  var response = await http.post(Uri.parse(url),
      headers: {"Content-Type": "application/json"},
      body: utf8.encode(r'{"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n    id\n    lat\n    lng\n    type\n    publicId\n    attributes\n    propulsion\n    battery\n    provider {\n      name\n      slug\n      website\n      discountCode\n      app {\n        android\n        ios\n        __typename\n      }\n      deepLink {\n        android\n        ios\n        __typename\n      }\n      stationVehicleTypes\n      __typename\n    }\n    pricing {\n      currency\n      unlock\n      perKm {\n        start\n        interval\n        price\n        __typename\n      }\n      perMin {\n        start\n        interval\n        price\n        __typename\n      }\n      perMinPause {\n        start\n        interval\n        price\n        __typename\n      }\n      includeVat\n      __typename\n    }\n    ... on Station {\n      availableVehicles\n      availableStands\n      isVirtual\n      stationVehicleDetails {\n        vehicleType\n        propulsion\n        availableVehicles\n        __typename\n      }\n      __typename\n    }\n    ... on Car {\n      carClass\n      carModel\n      __typename\n    }\n    __typename\n  }\n}\n"
      ,"variables":{"lat":51.492591,"lng":-0.157221}}'));

  print("${response.statusCode}");
  print("${response.body}");
  return response;
}
</code>```

答:
You had a bunch of typos in your raw string. The following works, and answers your earlier question about how to build via JSON (as an alternative).</p>
```<code>import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  {
    var url = 'https://flow-api.fluctuo.com/v1'
        '?access_token=eOy6L54RIbbswB8O0gQgk3lChcCu2wco';

    final encodedQuery1 = r'''{
  "query": "query ($lat: Float!, $lng: Float!) {vehicles(lat: $lat, lng: $lng) {  id  lat   lng   type   publicId   attributes  propulsion  battery  provider {   name  slug     website      discountCode     app {      android      ios      __typename     }     deepLink {        android      ios       __typename      }      stationVehicleTypes      __typename    }    pricing {      currency      unlock      perKm {        start        interval        price        __typename      }      perMin {        start        interval        price        __typename      }      perMinPause {        start        interval        price        __typename      }      includeVat      __typename    }    ... on Station {      availableVehicles      availableStands      isVirtual      stationVehicleDetails {        vehicleType        propulsion        availableVehicles        __typename      }      __typename    }    ... on Car {      carClass      carModel      __typename    }    __typename  }}  ",
  "variables": {
    "lat": 51.492591,
    "lng": -0.157221
  }
}
''';

    // ALTERNATIVE way to build the json
    final lat = 51.492591;
    final long = -0.157221;
    final gqlQuery =
        r'query ($lat: Float!, $lng: Float!) {vehicles(lat: $lat, lng: $lng) {  id  lat   lng   type   publicId   attributes  propulsion  battery  provider {   name  slug     website      discountCode     app {      android      ios      __typename     }     deepLink {        android      ios       __typename      }      stationVehicleTypes      __typename    }    pricing {      currency      unlock      perKm {        start        interval        price        __typename      }      perMin {        start        interval        price        __typename      }      perMinPause {        start        interval        price        __typename      }      includeVat      __typename    }    ... on Station {      availableVehicles      availableStands      isVirtual      stationVehicleDetails {        vehicleType        propulsion        availableVehicles        __typename      }      __typename    }    ... on Car {      carClass      carModel      __typename    }    __typename  }}';
    final encodedQuery2 = json.encode({
      'query': gqlQuery,
      'variables': {'lat': lat, 'lng': long},
    });
    // END of alternative

    var response = await http.post(
      Uri.parse(url),
      headers: {'Content-Type': 'application/json'},
      body: utf8.encode(encodedQuery1), // to use the alternative replace 1 w/ 2
    );

    print('${response.statusCode}');
    print('${response.body}');
  }
}
</code>```

Body:
I am trying to contact a GraphQL API and retrieve the data in Flutter

I have a working call in postman giving me the data back.

I have been referred to an example of a working http call but can't get the body to work. I used an encoded version in my postman call but have been advised to un-encode the "data-raw" of my Postman call and pass Json into the query.

I have the main query and then the variable which is the lat/long

A) Is this the correct approach, using pure Json as opposed to encoded like in my postman call (Example below)

    {"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n    id\n...

B) How can I get the query and variable into the Map data = if this is the correct thing to do?

Here is where I am at, using un-encoded Json in Map data = which isn't being accepted and the $lat $long aren't transferred into query from variables

Future<http.Response> showMicroMob () async {

  var url ='https://flow-api.fluctuo.com/v1?access_token=my_token';

  Map data = {
    'query': query ($lat: Float!, $lng: Float!) {
  vehicles (lat: $lat, lng: $lng) {
    id
    type
    publicId
    provider {
      slug
    }
    lat
    lng
    propulsion
    battery
    attributes
    ... on Station {
      isVirtual
      availableVehicles
      availableStands
      stationVehicleDetails {
        vehicleType
        propulsion
        availableVehicles
      }
      vehicles {
        id
        publicId
        type
        propulsion
        battery
      }
    }
  }
}
    'variables': {"lat":51.492591,"lng":-0.157221}
  };

  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(Uri.parse(url),
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}

Original example

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}

Update of call

If I shift variable up to make a complete String it no longer recognises the $lat $long fields or the actual lat/long numbers as values and makes them orange text. When I move variables down like in my postman request it of course throws errors, but the numbers are recognised as such ($Lat/$Long still not able to take the value. Tried just hard placing lat/ling figures in and returned

    flutter: 400 flutter: Bad Request

Should I try passing the variables in another way?

Future<http.Response> showMicroMob () async {

  var url ='https://flow-api.fluctuo.com/v1?access_token=x';

  var response = await http.post(Uri.parse(url),
      headers: {"Content-Type": "application/json"},
      body: utf8.encode(r'{"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n    id\n    lat\n    lng\n    type\n    publicId\n    attributes\n    propulsion\n    battery\n    provider {\n      name\n      slug\n      website\n      discountCode\n      app {\n        android\n        ios\n        __typename\n      }\n      deepLink {\n        android\n        ios\n        __typename\n      }\n      stationVehicleTypes\n      __typename\n    }\n    pricing {\n      currency\n      unlock\n      perKm {\n        start\n        interval\n        price\n        __typename\n      }\n      perMin {\n        start\n        interval\n        price\n        __typename\n      }\n      perMinPause {\n        start\n        interval\n        price\n        __typename\n      }\n      includeVat\n      __typename\n    }\n    ... on Station {\n      availableVehicles\n      availableStands\n      isVirtual\n      stationVehicleDetails {\n        vehicleType\n        propulsion\n        availableVehicles\n        __typename\n      }\n      __typename\n    }\n    ... on Car {\n      carClass\n      carModel\n      __typename\n    }\n    __typename\n  }\n}\n"
      ,"variables":{"lat":51.492591,"lng":-0.157221}}'));

  print("${response.statusCode}");
  print("${response.body}");
  return response;
}

Body:
You had a bunch of typos in your raw string. The following works, and answers your earlier question about how to build via JSON (as an alternative).

import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  {
    var url = 'https://flow-api.fluctuo.com/v1'
        '?access_token=eOy6L54RIbbswB8O0gQgk3lChcCu2wco';

    final encodedQuery1 = r'''{
  "query": "query ($lat: Float!, $lng: Float!) {vehicles(lat: $lat, lng: $lng) {  id  lat   lng   type   publicId   attributes  propulsion  battery  provider {   name  slug     website      discountCode     app {      android      ios      __typename     }     deepLink {        android      ios       __typename      }      stationVehicleTypes      __typename    }    pricing {      currency      unlock      perKm {        start        interval        price        __typename      }      perMin {        start        interval        price        __typename      }      perMinPause {        start        interval        price        __typename      }      includeVat      __typename    }    ... on Station {      availableVehicles      availableStands      isVirtual      stationVehicleDetails {        vehicleType        propulsion        availableVehicles        __typename      }      __typename    }    ... on Car {      carClass      carModel      __typename    }    __typename  }}  ",
  "variables": {
    "lat": 51.492591,
    "lng": -0.157221
  }
}
''';

    // ALTERNATIVE way to build the json
    final lat = 51.492591;
    final long = -0.157221;
    final gqlQuery =
        r'query ($lat: Float!, $lng: Float!) {vehicles(lat: $lat, lng: $lng) {  id  lat   lng   type   publicId   attributes  propulsion  battery  provider {   name  slug     website      discountCode     app {      android      ios      __typename     }     deepLink {        android      ios       __typename      }      stationVehicleTypes      __typename    }    pricing {      currency      unlock      perKm {        start        interval        price        __typename      }      perMin {        start        interval        price        __typename      }      perMinPause {        start        interval        price        __typename      }      includeVat      __typename    }    ... on Station {      availableVehicles      availableStands      isVirtual      stationVehicleDetails {        vehicleType        propulsion        availableVehicles        __typename      }      __typename    }    ... on Car {      carClass      carModel      __typename    }    __typename  }}';
    final encodedQuery2 = json.encode({
      'query': gqlQuery,
      'variables': {'lat': lat, 'lng': long},
    });
    // END of alternative

    var response = await http.post(
      Uri.parse(url),
      headers: {'Content-Type': 'application/json'},
      body: utf8.encode(encodedQuery1), // to use the alternative replace 1 w/ 2
    );

    print('${response.statusCode}');
    print('${response.body}');
  }
}


问:
Azure ServiceBusQueue function not firing locally
I just cannot seem to figure out why this function will not fire.

There is an active message in my service bus queue.

My local.settings.json file has the correct queue name and bus connection string which are referenced correctly in the main function class.

I've checked my code agaisn't the example in the MS docs and it looks correct.

When I run it in debug, the CLI picks up the correct function then logs host lock acquired, but does nothing else.

I have tried...

Adding ;TransportType=AmqpWebSockets to the connection string

Explicitly typing the queue name in the main function class instead of the json settings file

Sending a new message onto the queue

Refreshing the queue

But it just will not work and I'm wondering what else to try?

Running the following...

.NET core - 3.1

Azure core tools - 3.0

Function version - 3.3.1

Nugets...

Azure.Messaging.ServiceBus - 7.5.1

Microsoft.Azure.WebJobs.Extensions.ServiceBus - 5.2.0 (I'm using the new ServiceBusReceivedMessage type)

Microsoft.NET.Sdk.Functions - 3.0.13

I haven't reached the stage to publish yet, still just getting it running locally first.

Thanks

```<code> public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task Run([ServiceBusTrigger("MessageQueueName", Connection = "ServiceBusConnectionString")] ServiceBusReceivedMessage message, ILogger logger)
        {
            var bus = new AzureBus(Environment.GetEnvironmentVariable("ServiceBusConnectionString", EnvironmentVariableTarget.Process)).SendOnly();
            var endpoint = new Endpoint(bus, logger);

            logger.LogInformation($"Message received from bus - {message}");

            await endpoint.Start();
            await bus.Handle(message);
        }
    }
</code>```

答:
could you share your code snippet for the main class? It should look something like this:

```<code>  public static async System.Threading.Tasks.Task RunAsync([ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")]
    Message myQueueItem, string lockToken, Microsoft.Azure.ServiceBus.Core.MessageReceiver messageReceiver, ILogger log)
</code>```

if using MessageReceiver you need to handle DeadLetter/Completing the message yourself

EDIT: make sure you have the storage emulator running aswell

Body:
I just cannot seem to figure out why this function will not fire.

There is an active message in my service bus queue.

My local.settings.json file has the correct queue name and bus connection string which are referenced correctly in the main function class.

I've checked my code agaisn't the example in the MS docs and it looks correct.

When I run it in debug, the CLI picks up the correct function then logs host lock acquired, but does nothing else.

I have tried...

Adding ;TransportType=AmqpWebSockets to the connection string

Explicitly typing the queue name in the main function class instead of the json settings file

Sending a new message onto the queue

Refreshing the queue

But it just will not work and I'm wondering what else to try?

Running the following...

.NET core - 3.1

Azure core tools - 3.0

Function version - 3.3.1

Nugets...

Azure.Messaging.ServiceBus - 7.5.1

Microsoft.Azure.WebJobs.Extensions.ServiceBus - 5.2.0 (I'm using the new ServiceBusReceivedMessage type)

Microsoft.NET.Sdk.Functions - 3.0.13

I haven't reached the stage to publish yet, still just getting it running locally first.

Thanks

 public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task Run([ServiceBusTrigger("MessageQueueName", Connection = "ServiceBusConnectionString")] ServiceBusReceivedMessage message, ILogger logger)
        {
            var bus = new AzureBus(Environment.GetEnvironmentVariable("ServiceBusConnectionString", EnvironmentVariableTarget.Process)).SendOnly();
            var endpoint = new Endpoint(bus, logger);

            logger.LogInformation($"Message received from bus - {message}");

            await endpoint.Start();
            await bus.Handle(message);
        }
    }

Body:
could you share your code snippet for the main class? It should look something like this:

  public static async System.Threading.Tasks.Task RunAsync([ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")]
    Message myQueueItem, string lockToken, Microsoft.Azure.ServiceBus.Core.MessageReceiver messageReceiver, ILogger log)

if using MessageReceiver you need to handle DeadLetter/Completing the message yourself

EDIT: make sure you have the storage emulator running aswell