问:
SAP Cloud SDK for Javascript: Filter on Expanded Entities
I know I am reopening an old one (Perform filter on expanded entity with SAP Cloud SDK), but it was a while ago and was referencing the Java version of the API used to consume an S/4 HANA service.

I'm testing the Javascript version of the API against the SuccessFactors OData API, which is indeed able to perform filters on expanded entities, like so:

```<code><API_HOST>/odata/v2/PerPerson?$filter=personalInfoNav/firstName eq 'MARCO'&$expand=personalInfoNav&$select=personalInfoNav/firstName, personalInfoNav/lastName&$top=20
</code>```

Translated into the SDK, it would be (TypeScript):

```<code>const personList: Array<PerPerson> =
    await PerPerson.requestBuilder().getAll().top(20)
        .select(
            PerPerson.DATE_OF_BIRTH,
            PerPerson.PERSONAL_INFO_NAV.select(
                PerPersonal.PERSON_ID_EXTERNAL,
                PerPersonal.FIRST_NAME,
                PerPersonal.LAST_NAME,
                PerPersonal.GENDER
            )
        ).filter(PerPersonal.FIRST_NAME.equals('MARCO'))
         .execute({ destinationName: this.configService.get<string>('ACTIVE_DESTINATION') });
</code>```

But this code does not compile because of the incompatibility of types for the filter function, which here expects a "PerPerson" type and not "PerPersonal".
I was not able to find anything about this.

Considering that the plain OData query works perfectly, anyone has been able to make this work?

答:
Update:

I didn't initially understand that Successfactors offered this functionality on top of the protocol. There are two possible workarounds I can think of:

use new Filter, e.g.:

```<code>PerPerson.requestBuilder().getAll().top(20)
  .select(
   ...
  ).filter(
    new Filter('personalInfoNav/firstName', 'eq', 'MARCO')
  )
...
</code>```

If this doesn't work, you can call build on the request builder instead of execute, which gives you the ODataRequest object from which you can get the URL, which you'd then have to manipulate manually. Then you should be able to use the executeHttpRequest function to execute this custom request object against a destination.

Let me know if one of these work for you!

Original answer:

filtering on expanded entities on OData v2 is only possible if the relationship between the two entities is 1:1. In the case the code would look like this:

```<code>PerPerson.requestBuilder().getAll().top(20)
  .select(
    PerPerson.DATE_OF_BIRTH,
    PerPerson.PERSONAL_INFO_NAV.select(
      PerPersonal.PERSON_ID_EXTERNAL,
      PerPersonal.FIRST_NAME,
      PerPersonal.LAST_NAME,
      PerPersonal.GENDER
    )
  ).filter(
    PerPerson.PERSONAL_INFO_NAV.filter(
      PerPersonal.FIRST_NAME.equals('MARCO')
  ))
...
</code>```

If, however, the relationship is 1:n, filtering is not possible.

Hope that helps!

Body:
I know I am reopening an old one (Perform filter on expanded entity with SAP Cloud SDK), but it was a while ago and was referencing the Java version of the API used to consume an S/4 HANA service.

I'm testing the Javascript version of the API against the SuccessFactors OData API, which is indeed able to perform filters on expanded entities, like so:

<API_HOST>/odata/v2/PerPerson?$filter=personalInfoNav/firstName eq 'MARCO'&$expand=personalInfoNav&$select=personalInfoNav/firstName, personalInfoNav/lastName&$top=20

Translated into the SDK, it would be (TypeScript):

const personList: Array<PerPerson> =
    await PerPerson.requestBuilder().getAll().top(20)
        .select(
            PerPerson.DATE_OF_BIRTH,
            PerPerson.PERSONAL_INFO_NAV.select(
                PerPersonal.PERSON_ID_EXTERNAL,
                PerPersonal.FIRST_NAME,
                PerPersonal.LAST_NAME,
                PerPersonal.GENDER
            )
        ).filter(PerPersonal.FIRST_NAME.equals('MARCO'))
         .execute({ destinationName: this.configService.get<string>('ACTIVE_DESTINATION') });

But this code does not compile because of the incompatibility of types for the filter function, which here expects a "PerPerson" type and not "PerPersonal".
I was not able to find anything about this.

Considering that the plain OData query works perfectly, anyone has been able to make this work?

Body:
Update:

I didn't initially understand that Successfactors offered this functionality on top of the protocol. There are two possible workarounds I can think of:

use new Filter, e.g.:

PerPerson.requestBuilder().getAll().top(20)
  .select(
   ...
  ).filter(
    new Filter('personalInfoNav/firstName', 'eq', 'MARCO')
  )
...

If this doesn't work, you can call build on the request builder instead of execute, which gives you the ODataRequest object from which you can get the URL, which you'd then have to manipulate manually. Then you should be able to use the executeHttpRequest function to execute this custom request object against a destination.

Let me know if one of these work for you!

Original answer:

filtering on expanded entities on OData v2 is only possible if the relationship between the two entities is 1:1. In the case the code would look like this:

PerPerson.requestBuilder().getAll().top(20)
  .select(
    PerPerson.DATE_OF_BIRTH,
    PerPerson.PERSONAL_INFO_NAV.select(
      PerPersonal.PERSON_ID_EXTERNAL,
      PerPersonal.FIRST_NAME,
      PerPersonal.LAST_NAME,
      PerPersonal.GENDER
    )
  ).filter(
    PerPerson.PERSONAL_INFO_NAV.filter(
      PerPersonal.FIRST_NAME.equals('MARCO')
  ))
...

If, however, the relationship is 1:n, filtering is not possible.

Hope that helps!


来源: stackexchange

问:
How do I return a sys_refcursor from oracle SP in java?
I have a stored procedure (SP) in oracle:

```<code>CREATE OR REPLACE
PROCEDURE "SP_SEL_LOGIN_INFO" (
p_username IN varchar2,
p_ResultSet OUT sys_refcursor
) AS

begin

OPEN p_ResultSet FOR
SELECT * FROM user_accounts
WHERE p_username = username;

end;
</code>```

In my java class I have the following lines of code to call the SP:

```<code>currentCon = connectionpackage.ConnectionManager.getConnection(dbSource);
CallableStatement stmt = currentCon.prepareCall("{call SP_SEL_LOGIN_INFO(?, ?)}");
stmt.setString(1, username);
stmt.registerOutParameter(2, OracleTypes.CURSOR); //REF CURSOR
stmt.execute();
rs = stmt.getCursor(2);
</code>```

That is what I have found online to call a SP and return a cursor.  When I try to compile I get the following two errors:

error: cannot find symbol stmt.registerOutParameter(2, OracleTypes.CURSOR); AND error: cannot find symbol rs = stmt.getCursor(2); Where it says it cannot find OracleTypes and getCursor.

I tried importing import oracle.jdbc.driver.*; or import oracle.jdbc.*; and got the errors error: package oracle.jdbc does not exist import oracle.jdbc.driver.*; and error: package oracle.jdbc does not exist import oracle.jdbc.*; respectively.

I also have the ojdbc14.jar file in the proper folder and can connect using a query string.  It is just when trying to use the SP that it is giving me trouble.

The SP is one we use on our current CF website, so I would like to just reuse it as is.  Could someone please shed some light on why this may not be working?  Or if there is an alternative bit of code to use to return a cursor from an Oracle SP?  Thanks.

答:
You can also try like this:

```<code>rs = (ResultSet) stmt.getObject(2);
while (rs.next()) {
     String field1 = rs.getString(1);
     System.out.println(field1);
}
</code>```

it's running properly on my side

ContentLicense: CC BY-SA 3.0

Body:
I have a stored procedure (SP) in oracle:

CREATE OR REPLACE
PROCEDURE "SP_SEL_LOGIN_INFO" (
p_username IN varchar2,
p_ResultSet OUT sys_refcursor
) AS

begin

OPEN p_ResultSet FOR
SELECT * FROM user_accounts
WHERE p_username = username;

end;

In my java class I have the following lines of code to call the SP:

currentCon = connectionpackage.ConnectionManager.getConnection(dbSource);
CallableStatement stmt = currentCon.prepareCall("{call SP_SEL_LOGIN_INFO(?, ?)}");
stmt.setString(1, username);
stmt.registerOutParameter(2, OracleTypes.CURSOR); //REF CURSOR
stmt.execute();
rs = stmt.getCursor(2);

That is what I have found online to call a SP and return a cursor.  When I try to compile I get the following two errors:

error: cannot find symbol stmt.registerOutParameter(2, OracleTypes.CURSOR); AND error: cannot find symbol rs = stmt.getCursor(2); Where it says it cannot find OracleTypes and getCursor.

I tried importing import oracle.jdbc.driver.*; or import oracle.jdbc.*; and got the errors error: package oracle.jdbc does not exist import oracle.jdbc.driver.*; and error: package oracle.jdbc does not exist import oracle.jdbc.*; respectively.

I also have the ojdbc14.jar file in the proper folder and can connect using a query string.  It is just when trying to use the SP that it is giving me trouble.

The SP is one we use on our current CF website, so I would like to just reuse it as is.  Could someone please shed some light on why this may not be working?  Or if there is an alternative bit of code to use to return a cursor from an Oracle SP?  Thanks.

Body:
You can also try like this:

rs = (ResultSet) stmt.getObject(2);
while (rs.next()) {
     String field1 = rs.getString(1);
     System.out.println(field1);
}

it's running properly on my side

ContentLicense: CC BY-SA 4.0


问:
Calculate table size to determinate exceeds allowed maximum of 8060 bytes
When I create a new table with so many columns with nvarchar type

```<code>create table testcolumnsize
(
a001    nvarchar(4000),
a002    nvarchar(4000),
--.....
a400    nvarchar(4000),
)
</code>```

I received a warning message that told

Warning: The table "testcolumnsize" has been created, but its maximum row size exceeds the allowed maximum of 8060 bytes. INSERT or UPDATE to this table will fail if the resulting row exceeds the size limit

How can I calculate the created table's size according to it's columns data type to determinate whether it's size exceeds the allowed maximum of 8060 bytes

For example

```<code>create table testcolumnsize
(
cint int,
cbigint bigint,
cfloat float,
cdatetime datetime,
--.....
)
</code>```

答:
According to links I found, it's possible through a query.

If you're interested in individual rows, then one link provides the following code:

```<code>-- Declaring variables
declare @table nvarchar(128);
declare @idcol nvarchar(128);
declare @sql nvarchar(max);

--initialize those two values
set @table = '[Person].[AddressType]'
set @idcol = 'AddressTypeID, Name'
set @sql = 'select ' + @idcol + ' , (0'

-- This select statement collects all columns of a table and calculate datalength
select @sql = @sql + ' + isnull(datalength(' + name + '), 1)'
from sys.columns where object_id = object_id(@table)
set @sql = @sql + ') as RowSize from ' + @table + ' order by rowsize desc'

-- Execute sql query
exec (@sql)
</code>```

The core of the functionality appears to revolve around the datalength function, which appears to return the size in bytes that a certain column uses for a given row.
This should give you the ability to detect whether a certain row exceeds the 8060 bytes limit.

The same can apparently be accomplished using sys.dm_db_index_physical_stats.

There are proponents also of the INFORMATION_SCHEMA.COLUMNS and its CHARACTER_MAXIMUM_LENGTH and CHARACTER_OCTET_LENGTH columns if you want to calculate the size of a "prospect" row.

See the following links for reference:

https://www.c-sharpcorner.com/blogs/calculate-row-size-of-a-table-in-sqlserver1

Determine row size for table

https://www.mssqltips.com/sqlservertutorial/183/informationschemacolumns/

Body:
When I create a new table with so many columns with nvarchar type

create table testcolumnsize
(
a001    nvarchar(4000),
a002    nvarchar(4000),
--.....
a400    nvarchar(4000),
)

I received a warning message that told

Warning: The table "testcolumnsize" has been created, but its maximum row size exceeds the allowed maximum of 8060 bytes. INSERT or UPDATE to this table will fail if the resulting row exceeds the size limit

How can I calculate the created table's size according to it's columns data type to determinate whether it's size exceeds the allowed maximum of 8060 bytes

For example

create table testcolumnsize
(
cint int,
cbigint bigint,
cfloat float,
cdatetime datetime,
--.....
)

Body:
According to links I found, it's possible through a query.

If you're interested in individual rows, then one link provides the following code:

-- Declaring variables
declare @table nvarchar(128);
declare @idcol nvarchar(128);
declare @sql nvarchar(max);

--initialize those two values
set @table = '[Person].[AddressType]'
set @idcol = 'AddressTypeID, Name'
set @sql = 'select ' + @idcol + ' , (0'

-- This select statement collects all columns of a table and calculate datalength
select @sql = @sql + ' + isnull(datalength(' + name + '), 1)'
from sys.columns where object_id = object_id(@table)
set @sql = @sql + ') as RowSize from ' + @table + ' order by rowsize desc'

-- Execute sql query
exec (@sql)

The core of the functionality appears to revolve around the datalength function, which appears to return the size in bytes that a certain column uses for a given row.
This should give you the ability to detect whether a certain row exceeds the 8060 bytes limit.

The same can apparently be accomplished using sys.dm_db_index_physical_stats.

There are proponents also of the INFORMATION_SCHEMA.COLUMNS and its CHARACTER_MAXIMUM_LENGTH and CHARACTER_OCTET_LENGTH columns if you want to calculate the size of a "prospect" row.

See the following links for reference:

https://www.c-sharpcorner.com/blogs/calculate-row-size-of-a-table-in-sqlserver1

Determine row size for table

https://www.mssqltips.com/sqlservertutorial/183/informationschemacolumns/


问:
Angular 8 @output EventEmitter not letting an Object to be emitted
How would I emit an Object instead of primitive data types?

I have a object const amount = { currenty: 'USD', total: '10.25' };
which I wanted to emmit to the parent component.

```<code>export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}
</code>```

in the emitter function

this.childEventEmitter.emit(amount); // not working

error: Argument of type { currenty: 'USD', total: '10.25' } not assignable to paraments of type string

答:
I am answering my own question after I found this solution "Type 'EventEmitter' is not generic" ERROR in angular

The issue was I was importing EventEmitter from Protractor instead of @angular/core;
Thank you for all the comments.

Body:
How would I emit an Object instead of primitive data types?

I have a object const amount = { currenty: 'USD', total: '10.25' };
which I wanted to emmit to the parent component.

export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}

in the emitter function

this.childEventEmitter.emit(amount); // not working

error: Argument of type { currenty: 'USD', total: '10.25' } not assignable to paraments of type string


问:
How to reset PipeReader to be able to re-read request body in ASP.NET Core
I have some ASP.NET Core middleware (an AuthorizationHandler) that needs to access the body of the request to perform an authorization check. I use the new pipelines APIs to access the request body. The code looks like this:

```<code>PipeReader bodyReader = httpContext.Request.BodyReader;

ReadResult readResult = await bodyReader.ReadAsync();
ReadOnlySequence<byte> readResultBuffer = readResult.Buffer;

var utf8JsonReader = new Utf8JsonReader(bytes);
while (utf8JsonReader.Read()) { ... }
</code>```

When this code has run, the body stream is read. The controller that I want to call throws a validation error because it doesn't see a request body because it was already read.

So how do I reset the PipeReader so that the request body can be re-read?

I know that when you do not use BodyReader but Body, you can use EnableBuffering to enable request re-reads. However, when using pipelines, this no longer works (or I'm doing something else wrong).

答:
I've worked on reading and resetting the request body in a controller's OnActionExecuting method. This is what worked for me:

```<code>httpContext.Request.Body.Position = 0;
</code>```

Maybe this does also work in a pipeline?

Body:
I have some ASP.NET Core middleware (an AuthorizationHandler) that needs to access the body of the request to perform an authorization check. I use the new pipelines APIs to access the request body. The code looks like this:

PipeReader bodyReader = httpContext.Request.BodyReader;

ReadResult readResult = await bodyReader.ReadAsync();
ReadOnlySequence<byte> readResultBuffer = readResult.Buffer;

var utf8JsonReader = new Utf8JsonReader(bytes);
while (utf8JsonReader.Read()) { ... }

When this code has run, the body stream is read. The controller that I want to call throws a validation error because it doesn't see a request body because it was already read.

So how do I reset the PipeReader so that the request body can be re-read?

I know that when you do not use BodyReader but Body, you can use EnableBuffering to enable request re-reads. However, when using pipelines, this no longer works (or I'm doing something else wrong).

Body:
I've worked on reading and resetting the request body in a controller's OnActionExecuting method. This is what worked for me:

httpContext.Request.Body.Position = 0;

Maybe this does also work in a pipeline?


问:
Logout for an app which having multiple storyboards swift 5 (Going back to root view controller)
How to go back to rootview controller in swift 5 where scenedelegate is available instead of Appdelegate

```<code>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
//        guard let _ = (scene as? UIWindowScene) else { return }
        if let windowScene = scene as? UIWindowScene {
            self.window = UIWindow(windowScene: windowScene)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController =
                storyboard.instantiateViewController(withIdentifier: "first_page")
            self.window!.rootViewController = initialViewController
            self.window!.makeKeyAndVisible()
        }
    }
</code>```

this is my scenedelegate code need to dismiss/popback to my first page.

i am having the first page in
Main.storyboard but my logout function is in another storyboard called Home.storyboard

tried

```<code>self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
</code>```

and

```<code>self.navigationController?.popToRootViewController(animated: true)
</code>```

But not working i have only one navigation controller that is for the first viewcontroller

答:
You can try to use topController for dismiss/popback or present/push:</p>

```<code>    if var topController = UIApplication.shared.keyWindow?.rootViewController  {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
    }
</code>```

Body:
How to go back to rootview controller in swift 5 where scenedelegate is available instead of Appdelegate

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
//        guard let _ = (scene as? UIWindowScene) else { return }
        if let windowScene = scene as? UIWindowScene {
            self.window = UIWindow(windowScene: windowScene)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController =
                storyboard.instantiateViewController(withIdentifier: "first_page")
            self.window!.rootViewController = initialViewController
            self.window!.makeKeyAndVisible()
        }
    }

this is my scenedelegate code need to dismiss/popback to my first page.

i am having the first page in
Main.storyboard but my logout function is in another storyboard called Home.storyboard

tried

self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)

and

self.navigationController?.popToRootViewController(animated: true)

But not working i have only one navigation controller that is for the first viewcontroller

Body:
You can try to use topController for dismiss/popback or present/push:

    if var topController = UIApplication.shared.keyWindow?.rootViewController  {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
    }


问:
Breaking down array of objects into separate variables for database storage (React,express,sql server)
I have a stored array of objects within my reactjs application which when console logged looks like this.

```<code>0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}
</code>```

this consists of answer, question and state (state of the answered question not state as in react components)

What I would like to do is pass these through to express so that I can upload them into my SQL database using the npm package mssql. However as these are all stored into the array I'm not sure how to split these up.

Ideally I would love to pass the whole object through to SQL and just store the whole thing in the database e.g (pseudo code)

```<code>insert into table where answer = answer and question = question and state = state
</code>```

Essentially to use this with SQL how would I break these down to be used with my back end or can I pass the whole object with a specific SQL stored procedure.

```<code>create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

</code>```

EDIT

Stored procedure

```<code>create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer,
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))
end;
</code>```

How it is passed through to the sql query from express npm

```<code>app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

</code>```

This is the console.info(results)

```<code>[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]
</code>```

error

```<code>RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.
</code>```

答:
I can't tell much about how to write it in express, but what you need is an SQL query like

```<code>INSERT INTO `table_name`
(answer, question, created_at, updated_at)
VALUES
${sql_insert_values}
</code>```

sql_insert_values will be an array of strings with comma-separated value.
Each string will represent one field and will have comma-separated values for each column.

Do add ON DUPLICATE KEY UPDATE value = VALUES(value) if you have some unique key or index on some field.

Feel free to ask if you have doubts.

PS:
Values sent to SQL will be in format:

["(question value in string, answer value in string, date-time, date-time)", "()", "()"]. Here's a simpler example of the query:

```<code>INSERT INTO tbl_name (a,b,c)
VALUES(1,2,3), (4,5,6), (7,8,9);
</code>```

Refer this for more: https://dev.mysql.com/doc/refman/8.0/en/insert.html

Body:
I have a stored array of objects within my reactjs application which when console logged looks like this.

0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}

this consists of answer, question and state (state of the answered question not state as in react components)

What I would like to do is pass these through to express so that I can upload them into my SQL database using the npm package mssql. However as these are all stored into the array I'm not sure how to split these up.

Ideally I would love to pass the whole object through to SQL and just store the whole thing in the database e.g (pseudo code)

insert into table where answer = answer and question = question and state = state

Essentially to use this with SQL how would I break these down to be used with my back end or can I pass the whole object with a specific SQL stored procedure.

create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

EDIT

Stored procedure

create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer,
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))
end;

How it is passed through to the sql query from express npm

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

This is the console.info(results)

[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]

error

RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.

Body:
I can't tell much about how to write it in express, but what you need is an SQL query like

INSERT INTO `table_name`
(answer, question, created_at, updated_at)
VALUES
${sql_insert_values}

sql_insert_values will be an array of strings with comma-separated value.
Each string will represent one field and will have comma-separated values for each column.

Do add ON DUPLICATE KEY UPDATE value = VALUES(value) if you have some unique key or index on some field.

Feel free to ask if you have doubts.

PS:
Values sent to SQL will be in format:

["(question value in string, answer value in string, date-time, date-time)", "()", "()"]. Here's a simpler example of the query:

INSERT INTO tbl_name (a,b,c)
VALUES(1,2,3), (4,5,6), (7,8,9);

Refer this for more: https://dev.mysql.com/doc/refman/8.0/en/insert.html


问:
Circular dependency when installing numpy
I am trying to install numpy in my virtualenv but I face circular dependencies as follow:

```<code>(test) [hadoop@ip-192-168-26-8 test]$ python -m pip install numpy
Collecting numpy
  Using cached https://files.pythonhosted.org/packages/62/20/4d43e141b5bc426ba38274933ef8e76e85c7adea2c321ecf9ebf7421cedf/numpy-1.18.1-cp36-cp36m-manylinux1_x86_64.whl
ERROR: tensorboard 2.1.0 requires grpcio>=1.24.3, which is not installed.
ERROR: tensorboard 2.1.0 requires markdown>=2.6.8, which is not installed.
ERROR: tensorboard 2.1.0 requires protobuf>=3.6.0, which is not installed.
ERROR: tensorboard 2.1.0 requires werkzeug>=0.11.15, which is not installed.
Installing collected packages: numpy
Successfully installed numpy-1.18.1
</code>```

then when I try to install grpcio

```<code>(test) [hadoop@ip-192-168-26-8 test]$ python -m pip install grpcio
Collecting grpcio
  Using cached https://files.pythonhosted.org/packages/17/8f/f79c5c174bebece41f824dd7b1ba98da45dc2d4c373b38ac6a7f6a5acb5e/grpcio-1.26.0-cp36-cp36m-manylinux2010_x86_64.whl
Requirement already satisfied: six>=1.5.2 in ./lib/python3.6/dist-packages (from grpcio) (1.14.0)
ERROR: tensorboard 2.1.0 requires markdown>=2.6.8, which is not installed.
ERROR: tensorboard 2.1.0 requires numpy>=1.12.0, which is not installed.
ERROR: tensorboard 2.1.0 requires protobuf>=3.6.0, which is not installed.
ERROR: tensorboard 2.1.0 requires werkzeug>=0.11.15, which is not installed.
Installing collected packages: grpcio
Successfully installed grpcio-1.26.0
</code>```

I am not even sure why it gives me incorrect prompt Successfully installed grpcio-1.26.0, as they are not being added to my pip when I use list command.

答:
Do you mind uninstalling numpy with below:

```<code>pip uninstall numpy
</code>```

And install it again with --no-cache-dir option:

```<code>pip install numpy --no-cache-dir
</code>```

Also, see that pip is upgraded.

Body:
I am trying to install numpy in my virtualenv but I face circular dependencies as follow:

(test) [hadoop@ip-192-168-26-8 test]$ python -m pip install numpy
Collecting numpy
  Using cached https://files.pythonhosted.org/packages/62/20/4d43e141b5bc426ba38274933ef8e76e85c7adea2c321ecf9ebf7421cedf/numpy-1.18.1-cp36-cp36m-manylinux1_x86_64.whl
ERROR: tensorboard 2.1.0 requires grpcio>=1.24.3, which is not installed.
ERROR: tensorboard 2.1.0 requires markdown>=2.6.8, which is not installed.
ERROR: tensorboard 2.1.0 requires protobuf>=3.6.0, which is not installed.
ERROR: tensorboard 2.1.0 requires werkzeug>=0.11.15, which is not installed.
Installing collected packages: numpy
Successfully installed numpy-1.18.1

then when I try to install grpcio

(test) [hadoop@ip-192-168-26-8 test]$ python -m pip install grpcio
Collecting grpcio
  Using cached https://files.pythonhosted.org/packages/17/8f/f79c5c174bebece41f824dd7b1ba98da45dc2d4c373b38ac6a7f6a5acb5e/grpcio-1.26.0-cp36-cp36m-manylinux2010_x86_64.whl
Requirement already satisfied: six>=1.5.2 in ./lib/python3.6/dist-packages (from grpcio) (1.14.0)
ERROR: tensorboard 2.1.0 requires markdown>=2.6.8, which is not installed.
ERROR: tensorboard 2.1.0 requires numpy>=1.12.0, which is not installed.
ERROR: tensorboard 2.1.0 requires protobuf>=3.6.0, which is not installed.
ERROR: tensorboard 2.1.0 requires werkzeug>=0.11.15, which is not installed.
Installing collected packages: grpcio
Successfully installed grpcio-1.26.0

I am not even sure why it gives me incorrect prompt Successfully installed grpcio-1.26.0, as they are not being added to my pip when I use list command.

Body:
Do you mind uninstalling numpy with below:

pip uninstall numpy

And install it again with --no-cache-dir option:

pip install numpy --no-cache-dir

Also, see that pip is upgraded.


问:
Solution for draw a shortest path to navigate between many markers
I'm working on google maps and I need to draw the shortest path to navigate and visit all markers selected by the user.

I make my algorithm to solve that but the solution takes a long time and many codding, I need to know If there is any API or method to solve that quickly.

答:
If you are already using Google API, maybe consider using Google Directions API.
You can provide it with a start and end locations and up to 20+ locations and the API will calculate the best route.

You can find more info here.

Hope this helps.

Body:
If you are already using Google API, maybe consider using Google Directions API.
You can provide it with a start and end locations and up to 20+ locations and the API will calculate the best route.

You can find more info <a href="https://cloud.google.com/maps-platform/routes/?utm_source=google&utm_medium=cpc&utm_campaign=FY18-Q2-global-demandgen-paidsearchonnetworkhouseads-cs-maps_contactsal_saf&utm_content=text-ad-none-none-DEV_c-CRE_397052992493-ADGP_Hybrid%20%7C%20AW%20SEM%20%7C%20SKWS%20~%20Routes%20%7C%20BMM%20%7C%20Directions%20API-KWID_43700049595992169-kwd-445998650286-userloc_1008006&utm_term=KW_%2Bdirections%20%2Bapi-ST_%2Bdirections%20%2Bapi&gclid=Cj0KCQiAs67yBRC7ARIsAF49CdXs7Ct2Em8Hw1749wVBwQcwFUZonYgx-VBmsdyO1zLvtD3fsyH_a_oaAtgBEALw_wcB" rel="nofollow noreferrer">here.

Hope this helps.


问:
Laravel get value from 2 column with relationship one to one
I have 2 tables and have relationship one to one. Second table use a FK from first one, and I want to display a list with all values .

```<code>public function index(Request $request)
{
   $listOfPersons = new Person();
   $listOfRegisters = new  Register();

   $listOfRegisters->listOfPersons()->associate();
   return $listOfRegisters;
}
</code>```

In Register Model

```<code>public function people(){
    return $this->hasOne(Person::class);
}
</code>```

In Person Model

```<code>public function register(){
    return $this->hasOne(Register::class);
}
</code>```

答:
If you just want a list with all pairs of values, it should be enough with this code:

```<code>public function index(Request $request)
{
    $registers = Register::all();
    $list = [];
    foreach($registers as $register){
        array_push($list,['register'=> $register, 'person'=>$register->people]);
    }
    return $list;
}
</code>```

But remember you can just have the list of registers and access the person via the relationship. Moreover, you should change the hasOne relationship to belongsTo in register.

I hope that helps.

Body:
I have 2 tables and have relationship one to one. Second table use a FK from first one, and I want to display a list with all values .

public function index(Request $request)
{
   $listOfPersons = new Person();
   $listOfRegisters = new  Register();

   $listOfRegisters->listOfPersons()->associate();
   return $listOfRegisters;
}

In Register Model

public function people(){
    return $this->hasOne(Person::class);
}

In Person Model

public function register(){
    return $this->hasOne(Register::class);
}

Body:
If you just want a list with all pairs of values, it should be enough with this code:

public function index(Request $request)
{
    $registers = Register::all();
    $list = [];
    foreach($registers as $register){
        array_push($list,['register'=> $register, 'person'=>$register->people]);
    }
    return $list;
}

But remember you can just have the list of registers and access the person via the relationship. Moreover, you should change the hasOne relationship to belongsTo in register.

I hope that helps.


问:
Update json and insert in specific postion
I have an json as:

```<code>{
    "count":500,
    "type":"table",
    "data1": {
        "name":"test123",
        "comments":"test123",
        "id":"123"
    },
    "data2":{
        "env":"dev",
        "status":"new"
    }
}
</code>```

I want to update this existing one and add an extra element to the data2 part so that the output is as below:

```<code>{
    "count":500,
    "type":"table",
    "data1": {
        "name":"test123",
        "comments":"test123",
        "id":"123"
    },
    "data2":{
        "env":"dev",
        "status":"new",
        "priority":"none"
    }
}
</code>```

See  "priority":"none" been added above.

I tried using data.Insert but this takes in position and the data.

How can I loop through and add this to the data2 part of my object.

Thanks

--Update

```<code> public string metaData { get; set; }

 //getting data from db
 var myData = await this.getDataAsync(id);

// myData.metaData contains the above json
</code>```

I am trying to insert another element to above.

I am not sure how to parse and add it to a particular postion with the code I am using

I have read we can deserialize the object and then add it using .Add but again I have my string above which is holding this
 how can i update this

答:
You can easily achieve it using Newtonsoft.Json.Linq. Parse the json to JObject, get the data2 property and add priority

var parsedObject = JObject.Parse(json);
var data2 = parsedObject["data2"];
data2["priority"] = "none";
var result = parsedObject.ToString();
```

<p>You'll get the following output</p>

```{
  "count": 500,
  "type": "table",
  "data1": {
    "name": "test123",
    "comments": "test123",
    "id": "123"
  },
  "data2": {
    "env": "dev",
    "status": "new",
    "priority": "none"
  }
}
```

Body:
I have an json as:

{
    "count":500,
    "type":"table",
    "data1": {
        "name":"test123",
        "comments":"test123",
        "id":"123"
    },
    "data2":{
        "env":"dev",
        "status":"new"
    }
}

I want to update this existing one and add an extra element to the data2 part so that the output is as below:

{
    "count":500,
    "type":"table",
    "data1": {
        "name":"test123",
        "comments":"test123",
        "id":"123"
    },
    "data2":{
        "env":"dev",
        "status":"new",
        "priority":"none"
    }
}

See  "priority":"none" been added above.

I tried using data.Insert but this takes in position and the data.

How can I loop through and add this to the data2 part of my object.

Thanks

--Update

 public string metaData { get; set; }

 //getting data from db
 var myData = await this.getDataAsync(id);

// myData.metaData contains the above json

I am trying to insert another element to above.

I am not sure how to parse and add it to a particular postion with the code I am using

I have read we can deserialize the object and then add it using .Add but again I have my string above which is holding this
 how can i update this

Body:
You can easily achieve it using Newtonsoft.Json.Linq. Parse the json to JObject, get the data2 property and add priority

var parsedObject = JObject.Parse(json);
var data2 = parsedObject["data2"];
data2["priority"] = "none";
var result = parsedObject.ToString();

You'll get the following output

{
  "count": 500,
  "type": "table",
  "data1": {
    "name": "test123",
    "comments": "test123",
    "id": "123"
  },
  "data2": {
    "env": "dev",
    "status": "new",
    "priority": "none"
  }
}


问:
R row-wise sampling with upside down normal distribution
I have a data frame DF that looks like this:

```<code>Min Max
10  80
20  90
40  120
</code>```

I want to append a new Random column with a randomly generated number between the min and max values per row. The sampling of the number shall be derived from an upside down normal distribution and exclude the middle values like illustrated below

The below prototype code with single variables seem to work but I'm stuck with how to apply this row-wise.

```<code>min <- 1
max <- 20
q <- min + (max-min)*rbeta(10000, 0.5, 0.5)
q <- q[!(q > 5 & q < 15)][1:10000]
hist(q)
</code>```

答:
You could try this iterative approach. Use the variables lower and upper to define the excluded middle range.

Start by creating a column of NA values. For each iteration of the loop, all NA values in the column are overwritten with samples from your distribution. The samples that are within the excluded zone are then overwritten with NA and the loop repeats until no NA values are left in the column.

DF    <- data.frame(Min = c(10, 20, 40), Max = c(80, 90, 120))
lower <- 5
upper <- 15

DF$sample <- rep(NA, nrow(DF));
while(any(is.na(DF$sample)))
{
  i <- which(is.na(DF$sample));
  DF$sample[i] <- DF$Min[i] + (DF$Max[i] - DF$Min[i]) * rbeta(length(i), 0.5, 0.5);
  DF$sample[DF$sample > lower & DF$sample < upper] <- NA;
}

DF
#>   Min Max   sample
#> 1  10  80 31.88867
#> 2  20  90 33.26248
#> 3  40 120 80.08321
```

Created on 2020-02-18 by the reprex package (v0.3.0)

Body:
I have a data frame DF that looks like this:

Min Max
10  80
20  90
40  120

I want to append a new Random column with a randomly generated number between the min and max values per row. The sampling of the number shall be derived from an upside down normal distribution and exclude the middle values like illustrated below

The below prototype code with single variables seem to work but I'm stuck with how to apply this row-wise.

min <- 1
max <- 20
q <- min + (max-min)*rbeta(10000, 0.5, 0.5)
q <- q[!(q > 5 & q < 15)][1:10000]
hist(q)

Body:
You could try this iterative approach. Use the variables lower and upper to define the excluded middle range.

Start by creating a column of NA values. For each iteration of the loop, all NA values in the column are overwritten with samples from your distribution. The samples that are within the excluded zone are then overwritten with NA and the loop repeats until no NA values are left in the column.

DF    <- data.frame(Min = c(10, 20, 40), Max = c(80, 90, 120))
lower <- 5
upper <- 15

DF$sample <- rep(NA, nrow(DF));
while(any(is.na(DF$sample)))
{
  i <- which(is.na(DF$sample));
  DF$sample[i] <- DF$Min[i] + (DF$Max[i] - DF$Min[i]) * rbeta(length(i), 0.5, 0.5);
  DF$sample[DF$sample > lower & DF$sample < upper] <- NA;
}

DF
#>   Min Max   sample
#> 1  10  80 31.88867
#> 2  20  90 33.26248
#> 3  40 120 80.08321

Created on 2020-02-18 by the reprex package (v0.3.0)


问:
NestJS can't resolve dependencies of the JWT_MODULE_OPTIONS (Same problem, different solution)
This is not duplicate! I saw same problem here, but solution not helped.

My NestJS instance is not starting because of this problem:

```<code>Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.
</code>```

My auth.module.ts:

```<code>@Module({
  imports: [
    TypeOrmModule.forFeature([User, Token]),
    DatabaseModule,
    UserModule,
    ConfigModule,
    PassportModule,
    JwtModule.registerAsync({
      imports: [ConfigModule], // Missing this
      useFactory: async (configService: ConfigService) => ({
        signOptions: {
          expiresIn: configService.get<string>('JWT_EXPIRATION'),
        },
        secretOrPrivateKey: configService.get<string>('JWT_SECRET'),
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
</code>```

and this is my app.module.ts (Entry Module):

```<code>@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: '.development.env',
    }),
    AuthModule,
    UserModule,
    DatabaseModule,
  ],
})
export class AppModule {}
</code>```

I am importing module correctly by imports: [ConfigModule], but still I am getting error, that injection failed, because module is not imported.

My ConfigModule is 100% imported into app as my log say: ConfigModule dependencies initialized

What am I doing wrong?

答: The issue, assuming you are using the @nestjs/config module, was a bug in the module's code for version < 0.2.3. In the latest version there was a fix to the issue. If you upgrade to 0.2.3 with npm i @nestjs/config@latest it should run fine.

Body:
This is not duplicate! I saw same problem here, but solution not helped.

My NestJS instance is not starting because of this problem:

Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.

My auth.module.ts:

@Module({
  imports: [
    TypeOrmModule.forFeature([User, Token]),
    DatabaseModule,
    UserModule,
    ConfigModule,
    PassportModule,
    JwtModule.registerAsync({
      imports: [ConfigModule], // Missing this
      useFactory: async (configService: ConfigService) => ({
        signOptions: {
          expiresIn: configService.get<string>('JWT_EXPIRATION'),
        },
        secretOrPrivateKey: configService.get<string>('JWT_SECRET'),
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy],
})
export class AuthModule {}

and this is my app.module.ts (Entry Module):

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: '.development.env',
    }),
    AuthModule,
    UserModule,
    DatabaseModule,
  ],
})
export class AppModule {}

I am importing module correctly by imports: [ConfigModule], but still I am getting error, that injection failed, because module is not imported.

My ConfigModule is 100% imported into app as my log say: ConfigModule dependencies initialized

What am I doing wrong?


问:
How to create buttons of diffrent sizes in a toolbar control (Win32 API)
I want to insert buttons of diffrent sizes in a toolbar.
Lets say for example 2 buttons. One have a size of 32x16, the Other 16x16.
I used Two Image Lists. Each image list has it's own image size (1st 32x16 - 2nd 16x16).
But the problem is, when I compile the code i get the images loaded correctly but the buttons have the same width(32).

code:

```<code>//(1) Create the Toolbar ImageList
HIMAGELIST hImageListLarge = ImageList_Create(32, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
if (!hImageListLarge)
    return false;

HIMAGELIST hImageListSmall = ImageList_Create(16, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
if (!hImageListSmall)
    return false;

//(2) Fill the Image List
if (ImageList_Add(hImageListLarge,
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO)),
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO_MASK))) == -1)
    return false;

if (ImageList_Add(hImageListSmall,
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP)),
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP_MASK))) == -1)
    return false;

//(3) Create the Toolbar window
m_hToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, nullptr,
    WS_CHILD | TBSTYLE_WRAPABLE | TBSTYLE_AUTOSIZE | TBSTYLE_LIST | TBSTYLE_TOOLTIPS ,
    0, 0, 0, 0, m_hWnd, nullptr, m_hInstance, nullptr);

if (m_hToolbar == nullptr)
    return false;

//(4) Sets the Image list for the Toolbar
SendMessage(m_hToolbar, CCM_SETVERSION, 5, 0);
SendMessage(m_hToolbar, TB_SETIMAGELIST, 0, (LPARAM)hImageListLarge);
SendMessage(m_hToolbar, TB_SETIMAGELIST, 1, (LPARAM)hImageListSmall);

//(5) Initialize the TBBUTTON structures for each button
m_tbButtons[0].fsStyle = BTNS_SEP;

m_tbButtons[1].iBitmap = MAKELONG(0, 0);
m_tbButtons[1].idCommand = ID_CONNECTIONS_CONNECT_TO;
m_tbButtons[1].fsState = TBSTATE_ENABLED;
m_tbButtons[1].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE;
m_tbButtons[1].iString = (INT_PTR)TEXT("Connect to");

m_tbButtons[2].iBitmap = MAKELONG(0, 1);
m_tbButtons[2].idCommand = ID_HELP_ABOUT;
m_tbButtons[2].fsState = TBSTATE_ENABLED;
m_tbButtons[2].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE ;
m_tbButtons[2].iString = (INT_PTR)TEXT("Help");

//(6) Add buttons to the toolbar
SendMessage(m_hToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
SendMessage(m_hToolbar, TB_ADDBUTTONS, 3, (LPARAM)m_tbButtons);

//(7) auto Resize the toolbar
SendMessage(m_hToolbar, TB_AUTOSIZE, 0, 0);
SendMessage(m_hToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
ShowWindow(m_hToolbar, SW_SHOW);

//(8) Modify the size of the separator that will hold the combobox
TBBUTTONINFO tbbi;
tbbi.cbSize = sizeof(tbbi);
tbbi.dwMask = TBIF_SIZE | TBIF_BYINDEX;
tbbi.cx = 500;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)0, (LPARAM)& tbbi);

tbbi.cx = 32;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)1, (LPARAM)& tbbi);

tbbi.cx = 16;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)2, (LPARAM)& tbbi);

//(9) Get the Rectangle occupied by the separator
RECT rcSep;
SendMessage(m_hToolbar, TB_GETITEMRECT, (WPARAM)0, (LPARAM)& rcSep);

//(10) Create the hosts comboBox
m_hComboHosts = CreateWindow(WC_COMBOBOXW, nullptr, WS_CHILD | CBS_DROPDOWN | WS_VISIBLE,
    rcSep.left, rcSep.top, rcSep.right - rcSep.left, rcSep.bottom - rcSep.top, m_hToolbar,
    (HMENU)IDC_COMBO_HOSTS, m_hInstance, nullptr);

if (!m_hComboHosts)
    return false;

return true;
</code>```

答:
I used the first TB_SETBUTTONINFO message to modify the size of a button (Separator).
To make it large enough for holding a comboBox control:

```<code>//(8) Modify the size of the separator that will hold the combobox
TBBUTTONINFO tbbi;
tbbi.cbSize = sizeof(tbbi);
tbbi.dwMask = TBIF_SIZE | TBIF_BYINDEX;
tbbi.cx = 500;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)0, (LPARAM)& tbbi);
</code>```

This is the code for creating the ComboBox:

```<code>//(9) Get the Rectangle occupied by the separator
RECT rcSep;
SendMessage(m_hToolbar, TB_GETITEMRECT, (WPARAM)0, (LPARAM)& rcSep);

//(10) Create the hosts comboBox
m_hComboHosts = CreateWindow(WC_COMBOBOXW, nullptr, WS_CHILD | CBS_DROPDOWN | WS_VISIBLE,
    rcSep.left, rcSep.top, rcSep.right - rcSep.left, rcSep.bottom - rcSep.top, m_hToolbar,
    (HMENU)IDC_COMBO_HOSTS, m_hInstance, nullptr);
</code>```

This is working as expected.

But when I try to add two other buttons (32x16 - 16x16), I get always the same width of the first Imagelist (32).

But when I swap the image list indexes, I get (16 for both).

I am using the new Visual styles ComCtl32.lib

Body:
I want to insert buttons of diffrent sizes in a toolbar.
Lets say for example 2 buttons. One have a size of 32x16, the Other 16x16.
I used Two Image Lists. Each image list has it's own image size (1st 32x16 - 2nd 16x16).
But the problem is, when I compile the code i get the images loaded correctly but the buttons have the same width(32).

code:

//(1) Create the Toolbar ImageList
HIMAGELIST hImageListLarge = ImageList_Create(32, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
if (!hImageListLarge)
    return false;

HIMAGELIST hImageListSmall = ImageList_Create(16, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
if (!hImageListSmall)
    return false;

//(2) Fill the Image List
if (ImageList_Add(hImageListLarge,
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO)),
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO_MASK))) == -1)
    return false;

if (ImageList_Add(hImageListSmall,
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP)),
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP_MASK))) == -1)
    return false;

//(3) Create the Toolbar window
m_hToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, nullptr,
    WS_CHILD | TBSTYLE_WRAPABLE | TBSTYLE_AUTOSIZE | TBSTYLE_LIST | TBSTYLE_TOOLTIPS ,
    0, 0, 0, 0, m_hWnd, nullptr, m_hInstance, nullptr);

if (m_hToolbar == nullptr)
    return false;

//(4) Sets the Image list for the Toolbar
SendMessage(m_hToolbar, CCM_SETVERSION, 5, 0);
SendMessage(m_hToolbar, TB_SETIMAGELIST, 0, (LPARAM)hImageListLarge);
SendMessage(m_hToolbar, TB_SETIMAGELIST, 1, (LPARAM)hImageListSmall);

//(5) Initialize the TBBUTTON structures for each button
m_tbButtons[0].fsStyle = BTNS_SEP;

m_tbButtons[1].iBitmap = MAKELONG(0, 0);
m_tbButtons[1].idCommand = ID_CONNECTIONS_CONNECT_TO;
m_tbButtons[1].fsState = TBSTATE_ENABLED;
m_tbButtons[1].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE;
m_tbButtons[1].iString = (INT_PTR)TEXT("Connect to");

m_tbButtons[2].iBitmap = MAKELONG(0, 1);
m_tbButtons[2].idCommand = ID_HELP_ABOUT;
m_tbButtons[2].fsState = TBSTATE_ENABLED;
m_tbButtons[2].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE ;
m_tbButtons[2].iString = (INT_PTR)TEXT("Help");

//(6) Add buttons to the toolbar
SendMessage(m_hToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
SendMessage(m_hToolbar, TB_ADDBUTTONS, 3, (LPARAM)m_tbButtons);

//(7) auto Resize the toolbar
SendMessage(m_hToolbar, TB_AUTOSIZE, 0, 0);
SendMessage(m_hToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
ShowWindow(m_hToolbar, SW_SHOW);

//(8) Modify the size of the separator that will hold the combobox
TBBUTTONINFO tbbi;
tbbi.cbSize = sizeof(tbbi);
tbbi.dwMask = TBIF_SIZE | TBIF_BYINDEX;
tbbi.cx = 500;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)0, (LPARAM)& tbbi);

tbbi.cx = 32;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)1, (LPARAM)& tbbi);

tbbi.cx = 16;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)2, (LPARAM)& tbbi);

//(9) Get the Rectangle occupied by the separator
RECT rcSep;
SendMessage(m_hToolbar, TB_GETITEMRECT, (WPARAM)0, (LPARAM)& rcSep);

//(10) Create the hosts comboBox
m_hComboHosts = CreateWindow(WC_COMBOBOXW, nullptr, WS_CHILD | CBS_DROPDOWN | WS_VISIBLE,
    rcSep.left, rcSep.top, rcSep.right - rcSep.left, rcSep.bottom - rcSep.top, m_hToolbar,
    (HMENU)IDC_COMBO_HOSTS, m_hInstance, nullptr);

if (!m_hComboHosts)
    return false;

return true;

Body:
I used the first TB_SETBUTTONINFO message to modify the size of a button (Separator).
To make it large enough for holding a comboBox control:

//(8) Modify the size of the separator that will hold the combobox
TBBUTTONINFO tbbi;
tbbi.cbSize = sizeof(tbbi);
tbbi.dwMask = TBIF_SIZE | TBIF_BYINDEX;
tbbi.cx = 500;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)0, (LPARAM)& tbbi);

This is the code for creating the ComboBox:

//(9) Get the Rectangle occupied by the separator
RECT rcSep;
SendMessage(m_hToolbar, TB_GETITEMRECT, (WPARAM)0, (LPARAM)& rcSep);

//(10) Create the hosts comboBox
m_hComboHosts = CreateWindow(WC_COMBOBOXW, nullptr, WS_CHILD | CBS_DROPDOWN | WS_VISIBLE,
    rcSep.left, rcSep.top, rcSep.right - rcSep.left, rcSep.bottom - rcSep.top, m_hToolbar,
    (HMENU)IDC_COMBO_HOSTS, m_hInstance, nullptr);

This is working as expected.

But when I try to add two other buttons (32x16 - 16x16), I get always the same width of the first Imagelist (32).

But when I swap the image list indexes, I get (16 for both).

I am using the new Visual styles ComCtl32.lib


问:
How works returning an object by reference
As i understand it is my reference SomeClass &ref=b; After that b = ref; Then c = b; SomeClass &ref2=c; then c=ref2 . But am I calling the operator = witch i have reloaded  when b=ref or c = ref2 ? Something like that a.operator=(ref) ? </p>

```<code>class SomeClass
{
public:
    SomeClass()
    {
        a = 5;
    }
    SomeClass(int l_a)
    {
        a = l_a;
    }

    SomeClass& operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
        return *this;
    }

    int a;
};

int main()
{
    SomeClass a;
    SomeClass b(1);
    SomeClass с(6);
    с = b = a;

}
</code>```

答:
If you had:

```<code>void operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
    }
</code>```

Then your assignments operations would be limited to:

```<code>b = a;
c = b;
</code>```

By returning the reference you can chain assignments as in:

```<code>c = b = a;
// c.operator = (b.operator = (a));

//1: b.operator= ("ref a")
//2: c.operator= ("ref b")
</code>```

Body:
As i understand it is my reference SomeClass &ref=b; After that b = ref; Then c = b; SomeClass &ref2=c; then c=ref2 . But am I calling the operator = witch i have reloaded  when b=ref or c = ref2 ? Something like that a.operator=(ref) ?

class SomeClass
{
public:
    SomeClass()
    {
        a = 5;
    }
    SomeClass(int l_a)
    {
        a = l_a;
    }

    SomeClass& operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
        return *this;
    }

    int a;
};

int main()
{
    SomeClass a;
    SomeClass b(1);
    SomeClass с(6);
    с = b = a;

}

Body:
If you had:

void operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
    }

Then your assignments operations would be limited to:

b = a;
c = b;

By returning the reference you can chain assignments as in:

c = b = a;
// c.operator = (b.operator = (a));

//1: b.operator= ("ref a")
//2: c.operator= ("ref b")


答:
You could do it with 1 line of code using python-benedict, it's a dict subclass with many features and it's open-source on GitHub (I am the author).

Installation: pip install python-benedict

from benedict import benedict as bdict

data_input= [
    {'9940542': {'Invalid Adjust(Platform Fee)': '-1.00'}},
    {'9940542': {'Invalid Adjust(Media Fee)': '-2.00'}},
    {'10315065': {'Invalid Adjust(Platform Fee)': '-1.00'}},
    {'10315065': {'Invalid Adjust(Media Fee)': '-3.00'}},
    {'11211744': {'Invalid Adjust(Platform Fee)': '-290.00'}},
    {'11211744': {'Invalid Adjust(Media Fee)': '-3403.00'}},
    {'11309685': {'Invalid Adjust(Platform Fee)': '-57.00'}},
    {'11309685': {'Invalid Adjust(Media Fee)': '-670.00'}},
    {'12103490': {'Media Fee': '709472.00'}},
    {'12103490': {'Platform Fee': '22703.00'}},
    {'12103490': {'Invalid Adjust(Platform Fee)': '-30.00'}},
    {'12103490': {'TrueView Budget Adjust (Platofrm Fee)': '-301.00'}},
    {'12103490': {'Invalid Adjust(Media Fee)': '-348.00'}},
    {'12103490': {'TrueView Budget Adjust (Media Fee)': '-9376.00'}},
    {'12160150': {'Media Fee': '549173.00'}},
    {'12160150': {'Platform Fee': '17573.00'}}
]

data_output = bdict()
data_output.merge(*data_input)
print(data_output.dump())
```

Title: Merge List of nested dictionaries

Body:
I have 3 lists as below, which are extracted from a PDF file,

adID = ['9940542', '9940542', '10315065', '10315065', '11211744', '11211744', '11309685', '11309685', '12103490', '12103490', '12103490', '12103490', '12103490', '12103490', '12160150', '12160150']

description = ['Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Media Fee', 'Platform Fee', 'Invalid Adjust(Platform Fee)', 'TrueView Budget Adjust (Platofrm Fee)', 'Invalid Adjust(Media Fee)', 'TrueView Budget Adjust (Media Fee)', 'Media Fee', 'Platform Fee']

spendItem = ['-1.00', '-2.00', '-1.00', '-3.00', '-290.00', '-3403.00', '-57.00', '-670.00', '709472.00', '22703.00', '-30.00', '-301.00', '-348.00', '-9376.00', '549173.00', '17573.00']

And I've converted these lists into a list of dictionaries as below

total= [{'9940542': {'Invalid Adjust(Platform Fee)': '-1.00'}},
        {'9940542': {'Invalid Adjust(Media Fee)': '-2.00'}},
        {'10315065': {'Invalid Adjust(Platform Fee)': '-1.00'}},
        {'10315065': {'Invalid Adjust(Media Fee)': '-3.00'}},
        {'11211744': {'Invalid Adjust(Platform Fee)': '-290.00'}},
        {'11211744': {'Invalid Adjust(Media Fee)': '-3403.00'}},
        {'11309685': {'Invalid Adjust(Platform Fee)': '-57.00'}},
        {'11309685': {'Invalid Adjust(Media Fee)': '-670.00'}},
        {'12103490': {'Media Fee': '709472.00'}},
        {'12103490': {'Platform Fee': '22703.00'}},
        {'12103490': {'Invalid Adjust(Platform Fee)': '-30.00'}},
        {'12103490': {'TrueView Budget Adjust (Platofrm Fee)': '-301.00'}},
        {'12103490': {'Invalid Adjust(Media Fee)': '-348.00'}},
        {'12103490': {'TrueView Budget Adjust (Media Fee)': '-9376.00'}},
        {'12160150': {'Media Fee': '549173.00'}},
        {'12160150': {'Platform Fee': '17573.00'}}]

Is there any way to iterate over this list to merge keys and values based on adID. Such as

Expected_result= {'12103490': {'Invalid Adjust(Platform Fee)': '-30.00',TrueView Budget Adjust (Platofrm Fee)': '-301.00','Invalid Adjust(Media Fee)': '-348.00','TrueView Budget Adjust (Media Fee)': '-9376.00'}}

Or is there any better way to merge such data?


问:
Consume nodejs library from Rust
I need to use an existing nodejs library from my Rust project and I am thinking of adding the node library as a git subtree and execute node whatever.js commands from Rust. But this doesn't seem ideal to me...

Is there any better way of embedding a nodejs library in my Rust project so I can call functions from that library in my Rust application?

答: Ended up using IPC between Rust and Node.</p>

Title: Consume nodejs library from Rust


问:
How to fix this error? Failed validating 'oneOf' in schema
I am creating an API using Flask, Connexion and SQLAlchemy to access a database. To do this I needed the following dependencies:

Flask-SQLAlchemy

Flask-Marshmallow

Marshmallow-SQLAlchemy

Marshmallow

When I run the file with the app instance using the command python3 <filename>, this is the error produced:

```<code>Traceback (most recent call last):
  File "server.py", line 16, in <module>
    connex_app.add_api("swagger.yml")
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apps/flask_app.py", line 57, in add_api
    api = super(FlaskApp, self).add_api(specification, **kwargs)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apps/abstract.py", line 153, in add_api
    options=api_options.as_dict())
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apis/abstract.py", line 75, in __init__
    self.specification = Specification.load(specification, arguments=arguments)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 153, in load
    return cls.from_file(spec, arguments=arguments)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 107, in from_file
    return cls.from_dict(spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 144, in from_dict
    return Swagger2Specification(spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 38, in __init__
    self._validate_spec(raw_spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 214, in _validate_spec
    raise InvalidSpecification.create_from(e)
connexion.exceptions.InvalidSpecification: None is not valid under any of the given schemas

Failed validating 'oneOf' in schema['properties']['paths']['patternProperties']['^/']['properties']['delete']['properties']['responses']['patternProperties']['^([0-9]{3})$|^(default)$']:
    {'oneOf': [{'$ref': '#/definitions/response'},
               {'$ref': '#/definitions/jsonReference'}]}

On instance['paths']['/people/{person_id}']['delete']['responses']['200']:
</code>```

Below is the swagger.yml file:

```<code>swagger: "2.0"
info:
  description: This is the swagger file that goes with our server code
  version: "1.0.0"
  title: Swagger Rest Article
consumes:
  - application/json
produces:
  - application/json

basePath: /api

# Paths supported by the server application
paths:
  /people:
    get:
      operationId: people.read_all
      tags:
        - People
      summary: Read the entire set of people, sorted by last name
      description: Read the entire set of people, sorted by last name
      responses:
        200:
          description: Successfully read people set operation
          schema:
            type: array
            items:
              properties:
                person_id:
                  type: string
                  description: Id of the person
                fname:
                  type: string
                  description: First name of the person
                lname:
                  type: string
                  description: Last name of the person
                timestamp:
                  type: string
                  description: Creation/Update timestamp of the person

    post:
      operationId: people.create
      tags:
        - People
      summary: Create a person
      description: Create a new person
      parameters:
        - name: person
          in: body
          description: Person to create
          required: True
          schema:
            type: object
            properties:
              fname:
                type: string
                description: First name of person to create
              lname:
                type: string
                description: Last name of person to create
      responses:
        201:
          description: Successfully created person
          schema:
            properties:
              person_id:
                type: string
                description: Id of the person
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

  /people/{person_id}:
    get:
      operationId: people.read_one
      tags:
        - People
      summary: Read one person
      description: Read one person
      parameters:
        - name: person_id
          in: path
          description: Id of the person to get
          type: integer
          required: True
      responses:
        200:
          description: Successfully read person from people data operation
          schema:
            type: object
            properties:
              person_id:
                type: string
                description: Id of the person
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

    put:
      operationId: people.update
      tags:
        - People
      summary: Update a person
      description: Update a person
      parameters:
        - name: person_id
          in: path
          description: Id the person to update
          type: integer
          required: True
        - name: person
          in: body
          schema:
            type: object
            properties:
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
      responses:
        200:
          description: Successfully updated person
          schema:
            properties:
              person_id:
                type: string
                description: Id of the person in the database
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

    delete:
      operationId: people.delete
      tags:
        - People
      summary: Delete a person from the people list
      description: Delete a person
      parameters:
        - name: person_id
          in: path
          type: integer
          description: Id of the person to delete
          required: true
      responses:
        200:
</code>```

I can't figure out how to solve the error.

答:
I forgot to include the description right below the delete response 200.This is the line i had forgotten.</p>
```<code>description: successfully deleted a person
</code>```

Body:
I am creating an API using Flask, Connexion and SQLAlchemy to access a database. To do this I needed the following dependencies:

Flask-SQLAlchemy

Flask-Marshmallow

Marshmallow-SQLAlchemy

Marshmallow

When I run the file with the app instance using the command python3 <filename>, this is the error produced:

Traceback (most recent call last):
  File "server.py", line 16, in <module>
    connex_app.add_api("swagger.yml")
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apps/flask_app.py", line 57, in add_api
    api = super(FlaskApp, self).add_api(specification, **kwargs)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apps/abstract.py", line 153, in add_api
    options=api_options.as_dict())
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/apis/abstract.py", line 75, in __init__
    self.specification = Specification.load(specification, arguments=arguments)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 153, in load
    return cls.from_file(spec, arguments=arguments)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 107, in from_file
    return cls.from_dict(spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 144, in from_dict
    return Swagger2Specification(spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 38, in __init__
    self._validate_spec(raw_spec)
  File "/home/fidelis/repo/proj4/env/lib/python3.6/site-packages/connexion/spec.py", line 214, in _validate_spec
    raise InvalidSpecification.create_from(e)
connexion.exceptions.InvalidSpecification: None is not valid under any of the given schemas

Failed validating 'oneOf' in schema['properties']['paths']['patternProperties']['^/']['properties']['delete']['properties']['responses']['patternProperties']['^([0-9]{3})$|^(default)$']:
    {'oneOf': [{'$ref': '#/definitions/response'},
               {'$ref': '#/definitions/jsonReference'}]}

On instance['paths']['/people/{person_id}']['delete']['responses']['200']:

Below is the swagger.yml file:

swagger: "2.0"
info:
  description: This is the swagger file that goes with our server code
  version: "1.0.0"
  title: Swagger Rest Article
consumes:
  - application/json
produces:
  - application/json

basePath: /api

# Paths supported by the server application
paths:
  /people:
    get:
      operationId: people.read_all
      tags:
        - People
      summary: Read the entire set of people, sorted by last name
      description: Read the entire set of people, sorted by last name
      responses:
        200:
          description: Successfully read people set operation
          schema:
            type: array
            items:
              properties:
                person_id:
                  type: string
                  description: Id of the person
                fname:
                  type: string
                  description: First name of the person
                lname:
                  type: string
                  description: Last name of the person
                timestamp:
                  type: string
                  description: Creation/Update timestamp of the person

    post:
      operationId: people.create
      tags:
        - People
      summary: Create a person
      description: Create a new person
      parameters:
        - name: person
          in: body
          description: Person to create
          required: True
          schema:
            type: object
            properties:
              fname:
                type: string
                description: First name of person to create
              lname:
                type: string
                description: Last name of person to create
      responses:
        201:
          description: Successfully created person
          schema:
            properties:
              person_id:
                type: string
                description: Id of the person
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

  /people/{person_id}:
    get:
      operationId: people.read_one
      tags:
        - People
      summary: Read one person
      description: Read one person
      parameters:
        - name: person_id
          in: path
          description: Id of the person to get
          type: integer
          required: True
      responses:
        200:
          description: Successfully read person from people data operation
          schema:
            type: object
            properties:
              person_id:
                type: string
                description: Id of the person
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

    put:
      operationId: people.update
      tags:
        - People
      summary: Update a person
      description: Update a person
      parameters:
        - name: person_id
          in: path
          description: Id the person to update
          type: integer
          required: True
        - name: person
          in: body
          schema:
            type: object
            properties:
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
      responses:
        200:
          description: Successfully updated person
          schema:
            properties:
              person_id:
                type: string
                description: Id of the person in the database
              fname:
                type: string
                description: First name of the person
              lname:
                type: string
                description: Last name of the person
              timestamp:
                type: string
                description: Creation/Update timestamp of the person record

    delete:
      operationId: people.delete
      tags:
        - People
      summary: Delete a person from the people list
      description: Delete a person
      parameters:
        - name: person_id
          in: path
          type: integer
          description: Id of the person to delete
          required: true
      responses:
        200:

I can't figure out how to solve the error.

Body:
I forgot to include the description right below the delete response 200.This is the line i had forgotten.

description: successfully deleted a person


问:
Skipping the first column while renaming column using for loop in python
The ask is simple, for renaming multiple dataframe's with a single code I have written the below but when I am using the code the column which contains the primary key is also getting renamed what I want my code to do is to skip the first column and rename the rest.

Codes have been provided below for better understanding of what I am trying to achieve:

```<code>import pandas as pd

USA = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")
BRA = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")
CAN = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")

df_dict = {"USA":USA, "BRA":BRA, "CAN":CAN}

for name, df in df_dict.items():
        df.columns = df.columns + "_" + name
</code>```

Which gives me the below output:

```<code>Primary Key_CAN local stat_CAN  valid stat_CAN  valid date_CAN
123                Approved        completed      2018-02-02
554                Restrict        pending        2020-06-05
789                Declined        pending        2016-08-07
</code>```

Which is perfect but with one problem I want the loop to skip the first column that is "Primary key"
Making my expected output to be below:

```<code>Primary Key   local stat_CAN      valid stat_CAN valid date_CAN
123                Approved        completed      2018-02-02
554                Restrict        pending        2020-06-05
789                Declined        pending        2016-08-07
</code>```

答:
This will work for you</p>

```<code>for name, df in df_dict.items():
        new_col = {c:c+"_"+name for c in df.columns[1:]}
        df.rename(columns=new_col, inplace = True)
</code>```

Body:
The ask is simple, for renaming multiple dataframe's with a single code I have written the below but when I am using the code the column which contains the primary key is also getting renamed what I want my code to do is to skip the first column and rename the rest.

Codes have been provided below for better understanding of what I am trying to achieve:

import pandas as pd

USA = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")
BRA = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")
CAN = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")

df_dict = {"USA":USA, "BRA":BRA, "CAN":CAN}

for name, df in df_dict.items():
        df.columns = df.columns + "_" + name

Which gives me the below output:

Primary Key_CAN local stat_CAN  valid stat_CAN  valid date_CAN
123                Approved        completed      2018-02-02
554                Restrict        pending        2020-06-05
789                Declined        pending        2016-08-07

Which is perfect but with one problem I want the loop to skip the first column that is "Primary key"
Making my expected output to be below:

Primary Key   local stat_CAN      valid stat_CAN valid date_CAN
123                Approved        completed      2018-02-02
554                Restrict        pending        2020-06-05
789                Declined        pending        2016-08-07

Body:
This will work for you

for name, df in df_dict.items():
        new_col = {c:c+"_"+name for c in df.columns[1:]}
        df.rename(columns=new_col, inplace = True)


问:
Selenium: Scroll through every page of an element with overflow auto
On a website we have an element with scrolbars generated with the css property overflow = auto.

How can I scroll through all pages of this element in a selnium test?

答:
Get the total height and the visible height of the element and then iterate through the pages while scrolling on each iteration.</p>

```<code>let id = "some-id";
let divTotalHeight = await driver.executeScript("return document.getElementById(id).scrollHeight");
let divVisibleHeight = await driver.executeScript("return document.getElementById(id).clientHeight");
for (let i = 0; i * divVisibleHeight < divTotalHeight; i++) {
    // do something, e.g. take a screenshot
    await driver.executeScript("document.getElementById(id).scrollBy(0, " + divVisibleHeight + ")");
}
</code>```

Body:
Get the total height and the visible height of the element and then iterate through the pages while scrolling on each iteration.

let id = "some-id";
let divTotalHeight = await driver.executeScript("return document.getElementById(id).scrollHeight");
let divVisibleHeight = await driver.executeScript("return document.getElementById(id).clientHeight");
for (let i = 0; i * divVisibleHeight < divTotalHeight; i++) {
    // do something, e.g. take a screenshot
    await driver.executeScript("document.getElementById(id).scrollBy(0, " + divVisibleHeight + ")");
}


问:
JMeter giving Error percentage in CLI but not in GUI
I have a small microservice running in a docker container that I am trying to obtain the latency of using JMeter CLI. I made the test using the JMeter GUI and ran the test from it first. And the error percentage then was 0. But when I run the same test using the CLI I get a value for error percentage. And I get the below warnings:

```<code>Creating summariser <summary>
Created the tree successfully using /Users/sulekahelmini/Documents/fyp/jmeter_scripts/factorial.jmx
Starting standalone test @ Tue Feb 18 02:20:35 IST 2020 (1581972635848)
Waiting for possible Shutdown/StopTestNow/HeapDump/ThreadDump message on port 4445
summary =     50 in 00:00:02 =   25.0/s Avg:    50 Min:     4 Max:   323 Err:     0 (0.00%)
Tidying up ...    @ Tue Feb 18 02:20:38 IST 2020 (1581972638095)
... end of run
2020-02-18 02:20:39,012 WARN o.a.j.u.JMeterUtils: Exception 'null' occurred when fetching String property:'sampleresult.default.encoding', defaulting to: ISO-8859-1
2020-02-18 02:20:39,022 WARN o.a.j.u.JMeterUtils: Exception 'null' occurred when fetching String property:'jmeterPlugin.prefixPlugins'
2020-02-18 02:20:39,022 INFO k.a.j.PluginsCMDWorker: Using JMeterPluginsCMD v. N/A
2020-02-18 02:20:39,025 INFO o.a.j.u.JMeterUtils: Setting Locale to en_LK
2020-02-18 02:20:39,030 INFO k.a.j.JMeterPluginsUtils: Loading user properties from: /Users/sulekahelmini/Documents/fyp/apache-jmeter-5.2.1/bin/user.properties
2020-02-18 02:20:39,030 INFO k.a.j.JMeterPluginsUtils: Loading system properties from: /Users/sulekahelmini/Documents/fyp/apache-jmeter-5.2.1/bin/system.properties
2020-02-18 02:20:40,083 WARN o.a.j.g.ObjectTableModel: Header count=13 but classes count=11
2020-02-18 02:20:40,083 WARN o.a.j.g.ObjectTableModel: Header count=13 but writeFunctor count=11
2020-02-18 02:20:40,210 INFO o.a.j.s.SaveService: Testplan (JMX) version: 2.2. Testlog (JTL) version: 2.2
2020-02-18 02:20:40,215 INFO o.a.j.s.SaveService: Using SaveService properties file encoding UTF-8
2020-02-18 02:20:40,217 INFO o.a.j.s.SaveService: Using SaveService properties version 5.0
2020-02-18 02:20:40,224 INFO o.a.j.s.SampleResult: Note: Sample TimeStamps are START times
2020-02-18 02:20:40,224 INFO o.a.j.s.SampleResult: sampleresult.default.encoding is set to ISO-8859-1
2020-02-18 02:20:40,225 INFO o.a.j.s.SampleResult: sampleresult.useNanoTime=true
2020-02-18 02:20:40,225 INFO o.a.j.s.SampleResult: sampleresult.nanoThreadSleep=5000
2020-02-18 02:20:40,226 INFO o.a.j.s.SampleEvent: List of sample_variables: []
2020-02-18 02:20:40,450 INFO k.a.j.v.AggregateReportGui: Saving CSV to /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/agg_test.csv
</code>```

This is the code that I used to run the test and convert the result to csv:

```<code>#run test
  cd /Users/sulekahelmini/Documents/fyp/apache-jmeter-5.2.1/bin && sh jmeter -n -t /Users/sulekahelmini/Documents/fyp/jmeter_scripts/factorial.jmx -l /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_results.jtl
  #convert result to csv
  cd /Users/sulekahelmini/Documents/fyp/apache-jmeter-5.2.1/bin && ./JMeterPluginsCMD.sh --generate-csv /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/agg_test.csv --input-jtl /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_results.jtl --plugin-type AggregateReport
</code>```

Shown below is the generated aggregated report (using the jtl file). Note that there is an error percentage there.

Also, note that my JMeter is not inside a container. What am I doing wrong here? How do I not get an error percentage when running in GUI?

答:
I fail to see where did you get a value for error percentage as it seems to be zero:

summary =     50 in 00:00:02 =   25.0/s Avg:    50 Min:     4 Max:   323 Err:     0 (0.00%)

If you're seeing errors in the generated /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/agg_test.csv it might be the case that the file existed previously and contains "old" results with failures.

Moreover I think you're writing something into that file using Aggregate Report listener and later on appending the last results into the same file using JMeter Plugins Command Line Tool.

In order to get "clean" and valid results:

Remove /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/agg_test.csv file

Remove /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_results.jtl file

Remove Aggregate Report listener (and all other listeners) from your Test Plan as listeners don't add any value and only consume resources

Repeat your 2 commands in the terminal

You should see the agg_test.csv file without any errors

Body:
I have a small microservice running in a docker container that I am trying to obtain the latency of using JMeter CLI. I made the test using the JMeter GUI and ran the test from it first. And the error percentage then was 0. But when I run the same test using the CLI I get a value for error percentage. And I get the below warnings:

Creating summariser
Created the tree successfully using /Users/sulekahelmini/Documents/fyp/jmeter_scripts/factorial.jmx
Starting standalone test @ Tue Feb 18 02:20:35 IST 2020 (1581972635848)
Waiting for possible Shutdown/StopTestNow/HeapDump/ThreadDump message on port 4445
summary =     50 in 00:00:02 =   25.0/s Avg:    50 Min:     4 Max:   323 Err:     0 (0.00%)
Tidying up ...    @ Tue Feb 18 02:20:38 IST 2020 (1581972638095)
... end of run
2020-02-18 02:20:39,012 WARN o.a.j.u.JMeterUtils: Exception 'null' occurred when fetching String property:'sampleresult.default.encoding', defaulting to: ISO-8859-1
2020-02-18 02:20:39,022 WARN o.a.j.u.JMeterUtils: Exception 'null' occurred when fetching String property:'jmeterPlugin.prefixPlugins'
2020-02-18 02:20:39,022 INFO k.a.j.PluginsCMDWorker: Using JMeterPluginsCMD v. N/A
2020-02-18 02:20:39,025 INFO o.a.j.u.JMeterUtils: Setting Locale to en_LK
2020-02-18 02:20:39,030 INFO k.a.j.JMeterPluginsUtils: Loading user properties from: /Users/sulekahelmini/Documents/fyp/apache-jmeter-5.2.1/bin/user.properties
2020-02-18 02:20:39,030 INFO k.a.j.JMeterPluginsUtils: Loading system properties from: /Users/sulekahelmini/Documents/fyp/apache-jmeter-5.2.1/bin/system.properties
2020-02-18 02:20:40,083 WARN o.a.j.g.ObjectTableModel: Header count=13 but classes count=11
2020-02-18 02:20:40,083 WARN o.a.j.g.ObjectTableModel: Header count=13 but writeFunctor count=11
2020-02-18 02:20:40,210 INFO o.a.j.s.SaveService: Testplan (JMX) version: 2.2. Testlog (JTL) version: 2.2
2020-02-18 02:20:40,215 INFO o.a.j.s.SaveService: Using SaveService properties file encoding UTF-8
2020-02-18 02:20:40,217 INFO o.a.j.s.SaveService: Using SaveService properties version 5.0
2020-02-18 02:20:40,224 INFO o.a.j.s.SampleResult: Note: Sample TimeStamps are START times
2020-02-18 02:20:40,224 INFO o.a.j.s.SampleResult: sampleresult.default.encoding is set to ISO-8859-1
2020-02-18 02:20:40,225 INFO o.a.j.s.SampleResult: sampleresult.useNanoTime=true
2020-02-18 02:20:40,225 INFO o.a.j.s.SampleResult: sampleresult.nanoThreadSleep=5000
2020-02-18 02:20:40,226 INFO o.a.j.s.SampleEvent: List of sample_variables: []
2020-02-18 02:20:40,450 INFO k.a.j.v.AggregateReportGui: Saving CSV to /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/agg_test.csv

This is the code that I used to run the test and convert the result to csv:

#run test
  cd /Users/sulekahelmini/Documents/fyp/apache-jmeter-5.2.1/bin && sh jmeter -n -t /Users/sulekahelmini/Documents/fyp/jmeter_scripts/factorial.jmx -l /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_results.jtl
  #convert result to csv
  cd /Users/sulekahelmini/Documents/fyp/apache-jmeter-5.2.1/bin && ./JMeterPluginsCMD.sh --generate-csv /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/agg_test.csv --input-jtl /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/jmeter_results.jtl --plugin-type AggregateReport

Shown below is the generated aggregated report (using the jtl file). Note that there is an error percentage there.

Also, note that my JMeter is not inside a container. What am I doing wrong here? How do I not get an error percentage when running in GUI?


问:
_userManager.GetUserAsync(User) returns null
I am trying to check a users email confirmation status after login and then direct them accordigly.

Based on these two threads:

ASP.NET Core Identity - get current user

How get current user in asp.net core

I tried this:

```<code>var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    ClaimsPrincipal currentUser = this.User;
    var thisUser = await _userManager.GetUserAsync(currentUser);
    if(thisUser.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }
}
</code>```

And also this:

```<code>var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    var thisUser = await _userManager.GetUserAsync(HttpContext.User);
    if(thisUser.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }
}
</code>```

From inside controller but thisUser is always null.

How do I check on logon that their email is confirmed and re-direct appropriately?

答:
From the docs:

Identity is enabled by calling UseAuthentication. UseAuthentication
  adds authentication middleware to the request pipeline.

So, inside the Configure method, if you forgot setting up

```<code>app.UseAuthentication();
</code>```

you will get the same result without any error.

Body:
I am trying to check a users email confirmation status after login and then direct them accordigly.

Based on these two threads:

ASP.NET Core Identity - get current user

How get current user in asp.net core

I tried this:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    ClaimsPrincipal currentUser = this.User;
    var thisUser = await _userManager.GetUserAsync(currentUser);
    if(thisUser.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }
}

And also this:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    var thisUser = await _userManager.GetUserAsync(HttpContext.User);
    if(thisUser.EmailConfirmed)
    {
        return View("~/Views/Task/Index.cshtml");
    }
    else
    {
        return View("ConfirmEmail");
    }
}

From inside controller but thisUser is always null.

How do I check on logon that their email is confirmed and re-direct appropriately?

Body:
From the docs:

Identity is enabled by calling UseAuthentication. UseAuthentication
  adds authentication middleware to the request pipeline.

So, inside the Configure method, if you forgot setting up

app.UseAuthentication();

you will get the same result without any error.