问:
Corda with token and accounts
We are working with token and accounts at Corda with Kotlin. I will detail the scenario to clarify.
We have a node1 and a node2.
We created a "OurTokenType" that extends from TokenType.
We created two accounts (seller and buyer) on node1 and shared them with node2.
By the business rule of the application, node2 is the one who issues the tokens (FungibleToken), and the issue worked correctly. In the end, node1 and node2 have access to the FungibleStates for the issue transaction.
Our problem is in the transfer of these tokens. When we try to transfer the tokens from the account seller to the buyer.
In our scenario, the transfer of tokens can happen on node1 or node2.
When we transfer through node1, which is the host of the accounts, we can use the MoveFungibleTokensFlow class that works and the FungibleStates on node1 are updated to the correct value. However, when we added node2 as an observer in the observerSessions parameter, the FungibleStates on node2 were not updated correctly.
And when we do the transfer by node2, which is NOT the host of the accounts, using the MoveFungibleTokensFlow class, it doesn't work, it generates an exception of com.r3.corda.lib.tokens.selection.InsufficientBalanceException: Insufficient spendable states identified, even with balance .

My question is, can I use the MoveFungibleTokensFlow class to transfer between accounts even if they are on another host?
And when we run on the node that hosts the accounts, what is the problem to update the FungibleStates when using observerSessions?
Or if I must follow the example of the link https://github.com/corda/samples-kotlin/tree/master/Accounts/worldcupticketbooking?

答:
MoveFungibleTokensFlow doesn't have an input parameter that specifies who's the source of the moved tokens, and that's because it considers the initiator of the flow as the source of the tokens.

class MoveFungibleTokensFlow
@JvmOverloads
constructor(
        val partiesAndAmounts: List<PartyAndAmount<TokenType>>,
        override val participantSessions: List<FlowSession>,
        override val observerSessions: List<FlowSession> = emptyList(),
        val queryCriteria: QueryCriteria? = null,
        val changeHolder: AbstractParty? = null
) : AbstractMoveTokensFlow() {
```

You are not correct about "both node1 and node2 see the issued tokens", in FungibleToken the only participant is the holder of the tokens, so when tokens are issued to seller and buyer accounts, the only participant is the node that hosts those accounts (i.e. node1).

Going back to my first point, because only node1 has the issued tokens, and you're running the move flow on node2 (the flow consider node2 as the source of the tokens, but node2 doesn't have them); that's why you're getting the insufficient balance error.

Even if you added node2 as an observer when you issued the tokens to buyer and seller (i.e. both node1 and node2 have the resulting tokens); if you dig deep through the code of MoveFungibleTokensflow which inherits from AbstractMoveTokensFlow which relies on ObserverAwareFinalityFlow to sign the transaction, you'll see inside ObserverAwareFinalityFlow that it doesn't call CollectSignatures flow, it only signs the transaction locally (see here); meaning only the node that holds the private keys of the accounts can sign on the move command, and since node1 is the host of buyer and seller; then node1 is the owner of the private/public keys and only node1 can sign on behalf of buyer and seller. So even if you shared buyer and seller accounts with node2; only node1 can sign, and since you're calling MoveFungibleTokensFlow from node2 (your 2nd scenario), it will fail when it reaches the part where it needs to sign on behalf of seller (to move its tokens), because node2 doesn't own the private key of that account.

On a side note, when you call MoveFungibleTokesnFlow from node1 to move the tokens of seller to buyer; make sure that you supply a value for queryCriteria to select only the tokens that belong to seller; if you don't supply a value; then the flow will pick any tokens that are hosted on node1 so you might end up moving tokens that belong to other accounts.

Also make sure to supply a value for changeHolder, so that the change goes back to seller, if you keep it empty; any resulting change will be assigned to the initiating node (i.e node1) instead of the account.

You can find lots of helpful tips in my article on Tokens SDK.

Also, R3 recently released a free Corda course; it has a great section on Tokens SDK.

In order for you to be able to move tokens from seller to buyer using node1 or node2 you have to rely on the utility function addMoveTokens() instead of the ready flows (i.e. MoveFungibleTokensFlow) (because of the above mentioned reasons). So you have to create the transaction yourself, then add the tokens to be moved using addMoveTokens(), then you have to collect the signatures (of the seller) using CollectSignatures flow (the seller will sign in the responder flow); also you have to take care of finalizing the transaction.

Just to clarify the above flow, your flow should check if it's the host of the seller; then it can sign locally, if it's not the host; then you have to create a FlowSession with the host of the account so you can collect its signature (i.e. its approval to move the token that it holds).

Samples repo has some examples that use addMoveTokens(); I recommend spending some time to explore them.

Title: Corda with token and accounts

Body:
MoveFungibleTokensFlow doesn't have an input parameter that specifies who's the source of the moved tokens, and that's because it considers the initiator of the flow as the source of the tokens.

class MoveFungibleTokensFlow
@JvmOverloads
constructor(
        val partiesAndAmounts: List<PartyAndAmount<TokenType>>,
        override val participantSessions: List<FlowSession>,
        override val observerSessions: List<FlowSession> = emptyList(),
        val queryCriteria: QueryCriteria? = null,
        val changeHolder: AbstractParty? = null
) : AbstractMoveTokensFlow() {

You are not correct about "both node1 and node2 see the issued tokens", in FungibleToken the only participant is the holder of the tokens, so when tokens are issued to seller and buyer accounts, the only participant is the node that hosts those accounts (i.e. node1).

Going back to my first point, because only node1 has the issued tokens, and you're running the move flow on node2 (the flow consider node2 as the source of the tokens, but node2 doesn't have them); that's why you're getting the insufficient balance error.

Even if you added node2 as an observer when you issued the tokens to buyer and seller (i.e. both node1 and node2 have the resulting tokens); if you dig deep through the code of MoveFungibleTokensflow which inherits from AbstractMoveTokensFlow which relies on ObserverAwareFinalityFlow to sign the transaction, you'll see inside ObserverAwareFinalityFlow that it doesn't call CollectSignatures flow, it only signs the transaction locally (see here); meaning only the node that holds the private keys of the accounts can sign on the move command, and since node1 is the host of buyer and seller; then node1 is the owner of the private/public keys and only node1 can sign on behalf of buyer and seller. So even if you shared buyer and seller accounts with node2; only node1 can sign, and since you're calling MoveFungibleTokensFlow from node2 (your 2nd scenario), it will fail when it reaches the part where it needs to sign on behalf of seller (to move its tokens), because node2 doesn't own the private key of that account.

On a side note, when you call MoveFungibleTokesnFlow from node1 to move the tokens of seller to buyer; make sure that you supply a value for queryCriteria to select only the tokens that belong to seller; if you don't supply a value; then the flow will pick any tokens that are hosted on node1 so you might end up moving tokens that belong to other accounts.

Also make sure to supply a value for changeHolder, so that the change goes back to seller, if you keep it empty; any resulting change will be assigned to the initiating node (i.e node1) instead of the account.

You can find lots of helpful tips in my article on Tokens SDK.

Also, R3 recently released a free Corda course; it has a great section on Tokens SDK.

In order for you to be able to move tokens from seller to buyer using node1 or node2 you have to rely on the utility function addMoveTokens() instead of the ready flows (i.e. MoveFungibleTokensFlow) (because of the above mentioned reasons). So you have to create the transaction yourself, then add the tokens to be moved using addMoveTokens(), then you have to collect the signatures (of the seller) using CollectSignatures flow (the seller will sign in the responder flow); also you have to take care of finalizing the transaction.

Just to clarify the above flow, your flow should check if it's the host of the seller; then it can sign locally, if it's not the host; then you have to create a FlowSession with the host of the account so you can collect its signature (i.e. its approval to move the token that it holds).

Samples repo has some examples that use addMoveTokens(); I recommend spending some time to explore them.


来源: stackexchange

问:
Why does my Python freeze when I do an overflow calculation?
I'm a MATLAB user trying to understand Python so sorry if this is obvious.

If I say

```<code>print(9**9)
</code>```

I get:
387420489

Great.

If I say print(9**9**9)
Python just sits there indefinitely and freezes (I use Spyder version 4). Ctrl-C doesn't stop it.
Why does it not just immediately return Inf? Is this expected behavior?

答: When doing numerical calculations with integers, python is not limited to machine-specific numbers such as "int32", and therefore a number such as "2147483647" does not mean much to it. Instead, it uses a "big integer" library, which can, in principle, express any large number, provided there is enough memory for it. When facing a computation such as 9**9**9 python tries to perform it exactly, producing the exact result, however big it may be. For this particular calculation it just takes a lot of time (and memory, presumably internally python is trying to allocate more and more memory as needed).

ContentLicense: CC BY-SA 4.0

Body:
I'm a MATLAB user trying to understand Python so sorry if this is obvious.

If I say

print(9**9)

I get:
387420489

Great.

If I say print(9**9**9)
Python just sits there indefinitely and freezes (I use Spyder version 4). Ctrl-C doesn't stop it.
Why does it not just immediately return Inf? Is this expected behavior?


问:
Is it possible to set a JS listener on attribute of an element?
I want to run a JavaScript function when the width of an element grows to a certain size. Listeners properly speaking only seem to be for 'events.' But is there any way to set a "listener" on a CSS attribute, like width? If so, how?</p>

答:
If you have the need to listen to an element size in 2020 you can use a ResizeObserver

https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver

You can try the following snippet to print the dimension changes of an element

```<code>const resizeObserver = new ResizeObserver(entries => {
    for (let entry of entries)
        console.log(entry);
});

resizeObserver.observe(htmlElement);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you have the need to listen to an element size in 2020 you can use a ResizeObserver

https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver

You can try the following snippet to print the dimension changes of an element

const resizeObserver = new ResizeObserver(entries => {
    for (let entry of entries)
        console.log(entry);
});

resizeObserver.observe(htmlElement);


问:
How do you get a file in C++?
So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter).  My first question is, how do I read in a file?  The document is on my desktop in a folder and the file is named document01.cry.  I'm not sure the command I need to put that file into the program.

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)

The code so far:

```<code>#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}
</code>```

PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there.  I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!

EDIT:: Also curious, is there a way to input the file you want?
(I.e.:

```<code>char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);
</code>```

This code doesn't work. It shoots back an error saying the char can't be converted to a const char *.  How can this problem be fixed?

EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

答:
Although your queston has been answered, two little tips:
1) Instead of counting x and y to see if you are on an odd or even character you can do the following:

```<code>int count=0;
while(!infile.eof())
{
    infile.get(letter);
    count++;
    if(count%2==0)
    {
        cout<<letter;
    }
}
</code>```

% essentially means 'remainder when divided by,' so 11%3 is two. in the above it gives odd or even.

2) Assuming you only need to run it on windows:

```<code>system("pause");
</code>```

will make the window stay open when its finished running so you don't need the last getchar() call (you may have to #include<Windows.h> for that to work).

OwnerDisplayName: Jeff

ContentLicense: CC BY-SA 2.5

Title: How do you get a file in C++?

Body:
So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter).  My first question is, how do I read in a file?  The document is on my desktop in a folder and the file is named document01.cry.  I'm not sure the command I need to put that file into the program.

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)

The code so far:

#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}

PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there.  I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!

EDIT:: Also curious, is there a way to input the file you want?
(I.e.:

char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);

This code doesn't work. It shoots back an error saying the char can't be converted to a const char *.  How can this problem be fixed?

EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

LastEditorDisplayName: EvilTeach

Body:
Although your queston has been answered, two little tips:
1) Instead of counting x and y to see if you are on an odd or even character you can do the following:

int count=0;
while(!infile.eof())
{
    infile.get(letter);
    count++;
    if(count%2==0)
    {
        cout<<letter;
    }
}

% essentially means 'remainder when divided by,' so 11%3 is two. in the above it gives odd or even.

2) Assuming you only need to run it on windows:

system("pause");

will make the window stay open when its finished running so you don't need the last getchar() call (you may have to #include<Windows.h> for that to work).

OwnerDisplayName: DaedalusFall


问:
PL/SQL DB triggers - Make insertion fail if a given condition is not met
I have a small test database I'm using for learning SQL.

There's a Duel table, which contains two Pilot foreign keys (the duelists). I want to check if the duelists haven't already "met" before insertion.

Pseudocode:

```<code>before insertion on Duel
for each row already in the table
  if ((new_row.numpilot1 = old_row.numpilot1 and new_row.numpilot2 = old_row.numpilot2) OR
      (new_row.numpilot1 = old_row.numpilot2 and new_row.numpilot2 = old_row.numpilot1)
     )
    insertion fails
</code>```

One other alternative would be

```<code>tempnum integer;
select numpilot1 into tempnum from duel
where (:NEW.numpilot1 = numpilot1 and :NEW.numpilot2 = numpilot2) OR
      (:NEW.numpilot1 = numpilot2 and :NEW.numpilot2 = numpilot1);

if tempnum == null
    fail insertion
</code>```

What is the PL/SQL (Oracle DBMS) version of this?

答:
Normally, you wouldn't use a trigger for this sort of requirement.  Instead, you'd create a couple of constraints on the table.  I would suggest a unique constraint on (numpilot1, numpilot2) along with a check constraint that ensures that numpilot1 < numpilot2.

```<code>ALTER TABLE duel
  ADD CONSTRAINT unique_pilot_combination
          UNIQUE( numpilot1, numpilot2 );

ALTER TABLE duel
  ADD CONSTRAINT chk_pilot1_lt_pilot2
           CHECK( numpilot1_fk < numpilot2_fk );
</code>```

If you wanted to do this sort of thing in a trigger, it would be quite a bit more complicated.  In general, a row-level trigger on DUEL cannot query the DUEL table-- doing so would create a mutating table exception.  You would need to create a collection in a package, a before statement trigger that initializes the collection, a row-level trigger that inserts the new pilot keys into the collection, and an after statement trigger that reads the data in the collection and does the validation.  That's quite a few moving pieces to manage in addition to the potential performance hit.  If you're really stuck with the trigger solution, however, there is an example of using the three trigger solution to work around mutating table exceptions on Tim Hall's site.

Body:
I have a small test database I'm using for learning SQL.

There's a Duel table, which contains two Pilot foreign keys (the duelists). I want to check if the duelists haven't already "met" before insertion.

Pseudocode:

before insertion on Duel
for each row already in the table
  if ((new_row.numpilot1 = old_row.numpilot1 and new_row.numpilot2 = old_row.numpilot2) OR
      (new_row.numpilot1 = old_row.numpilot2 and new_row.numpilot2 = old_row.numpilot1)
     )
    insertion fails

One other alternative would be

tempnum integer;
select numpilot1 into tempnum from duel
where (:NEW.numpilot1 = numpilot1 and :NEW.numpilot2 = numpilot2) OR
      (:NEW.numpilot1 = numpilot2 and :NEW.numpilot2 = numpilot1);

if tempnum == null
    fail insertion

What is the PL/SQL (Oracle DBMS) version of this?

Body:
Normally, you wouldn't use a trigger for this sort of requirement.  Instead, you'd create a couple of constraints on the table.  I would suggest a unique constraint on (numpilot1, numpilot2) along with a check constraint that ensures that numpilot1 < numpilot2.

ALTER TABLE duel
  ADD CONSTRAINT unique_pilot_combination
          UNIQUE( numpilot1, numpilot2 );

ALTER TABLE duel
  ADD CONSTRAINT chk_pilot1_lt_pilot2
           CHECK( numpilot1_fk < numpilot2_fk );

If you wanted to do this sort of thing in a trigger, it would be quite a bit more complicated.  In general, a row-level trigger on DUEL cannot query the DUEL table-- doing so would create a mutating table exception.  You would need to create a collection in a package, a before statement trigger that initializes the collection, a row-level trigger that inserts the new pilot keys into the collection, and an after statement trigger that reads the data in the collection and does the validation.  That's quite a few moving pieces to manage in addition to the potential performance hit.  If you're really stuck with the trigger solution, however, there is an example of using the three trigger solution to work around mutating table exceptions on Tim Hall's site.


问:
Can action parameter be a model in ASP.NET WEB API?
I have an action where I am supposed to capture many primitive values including Enum types. I have created a model to match the required values.Can action parameter be a model in ASP.NET WEB API? Or I need to create a view model?</p>

答:
You don't necessarily need to create a view model.

Models, view models, DTOs can all just be classes with properties on.

How each can or cannot be used is a decision you need to make.

Usually the main requirement from an API endpoint perspective is that the class into which the parameters are being deserialised has a default constructor. Then the parameters from the request will be assigned to properties of the equivalent name.


问:
How can I define a UNIQUE constraint that applies to multiple columns in a DataSet table?
I have the following table defined in a .sql script file.

```<code>CREATE TABLE [HwComponent](
    [HwComponentId] [int] NOT NULL,
    [HwComponentTypeId] [int] NOT NULL,
    [ManufactureId] [int] NOT NULL,
    [SerialNumber] [nvarchar](100) NOT NULL,
    [AssignmentType] [nvarchar](1000) NOT NULL,
    [IsFunctional] [nvarchar](10) NOT NULL,
    [Note] [nvarchar](4000) NULL,

    CONSTRAINT [PK_HwComponent] PRIMARY KEY ([HwComponentId]),
    CONSTRAINT (FK1_HwComponent] FOREIGN KEY ([HwComponentTypeId]) REFERENCES [HwComponentType] ([HwComponentTypeId)] ON DELETE NO ACTION ON UPDATE NO ACTION
    CONSTRAINT (FK2_HwComponent] FOREIGN KEY ([HwComponentTypeId], [ManufactureId]) REFERENCES [HwComponentTypeManufacturerInfo] ([HwComponentTypeId], [ManufactureId]) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT (UI1_HwComponent] UNIQUE ([HwComponentTypeId], [ManufactureId], [SerialNumber]))

GO
</code>```

I now need to define a new table in the DataSet Designer to match.

I believe I have everything defined correctly, except the UNIQUE constraint that requires all 3 columns be considered together as the unique constraint.

How do I define the UNIQUE constraint for this table in the DataSet Designer?

SQL CE Service 4.0 SP1:
VS Prof 2017 - Version 15.8.7

答:
Does this work for you?

```<code>CREATE UNIQUE INDEX ixYourConstraint ON HwComponent (col1, col2);
</code>```

This similar post might be of help to you:
MsSql Compact, unique constraint on two and more columns

Body:
I have the following table defined in a .sql script file.

CREATE TABLE [HwComponent](
    [HwComponentId] [int] NOT NULL,
    [HwComponentTypeId] [int] NOT NULL,
    [ManufactureId] [int] NOT NULL,
    [SerialNumber] [nvarchar](100) NOT NULL,
    [AssignmentType] [nvarchar](1000) NOT NULL,
    [IsFunctional] [nvarchar](10) NOT NULL,
    [Note] [nvarchar](4000) NULL,

    CONSTRAINT [PK_HwComponent] PRIMARY KEY ([HwComponentId]),
    CONSTRAINT (FK1_HwComponent] FOREIGN KEY ([HwComponentTypeId]) REFERENCES [HwComponentType] ([HwComponentTypeId)] ON DELETE NO ACTION ON UPDATE NO ACTION
    CONSTRAINT (FK2_HwComponent] FOREIGN KEY ([HwComponentTypeId], [ManufactureId]) REFERENCES [HwComponentTypeManufacturerInfo] ([HwComponentTypeId], [ManufactureId]) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT (UI1_HwComponent] UNIQUE ([HwComponentTypeId], [ManufactureId], [SerialNumber]))

GO

I now need to define a new table in the DataSet Designer to match.

I believe I have everything defined correctly, except the UNIQUE constraint that requires all 3 columns be considered together as the unique constraint.

How do I define the UNIQUE constraint for this table in the DataSet Designer?

SQL CE Service 4.0 SP1:
VS Prof 2017 - Version 15.8.7

Body:
Does this work for you?

CREATE UNIQUE INDEX ixYourConstraint ON HwComponent (col1, col2);

This similar post might be of help to you:
MsSql Compact, unique constraint on two and more columns


问:
LINQ to Entities - Addressing class properties with their string names
I have a Kendo grid that has serverside filtering turned on. The field to filter by is passed as a string. For example, I want to filter by "SampleId". Now, I need to write a LINQ to Entities query that can filter by using the strongly-typed property SampleId. For example:

```<code>    db.Cases.Where(x=>targetlist.Contains(x.SampleId))
</code>```

where targetlist is a list of items from the filter.

So, in effect, is there a way to write a query such that "SampleId" can directly translate to Case.SampleId?

I have tried reflection and made use of the GetProperty and GetValue and LINQ to Entities does not like it.

Any suggestions will be much appreciated!

EDIT (by pid for original poster srinaik2020):

@zaitsman: this is the code posted in an comment further below and is the actual resolution of the problem, based on the accepted answer.

```<code>public static class MyExtensions
{
    public static string GetPropertyByName(this CaseV case1, string name)
    {
        var x = typeof (CaseV).GetProperty(name).GetValue(case1);

        if (x != null)
        {
            return x.ToString();
        } else {
            return "none";
        }
    }
}
</code>```

答:
I didn't think any of these answered actually how to do the getproperty so included my working code after further research.  mymodelclass is the class of the entity/model used to MyFilteredData.</p>

```<code>        var srchItem1 = typeof(mymodelclass).GetProperty("Name");
        var srchItem2 = typeof(mymodelclass).GetProperty("Description");
        var srchItem3 = typeof(mymodelclass).GetProperty("LongDescription");
        if (MySearchText != null && srchItem1 != null)
            {
                if (srchItem2 == null) { srchItem2 = srchItem1; }
                if (srchItem3 == null) { srchItem3 = srchItem1; }
                MyFilteredData = MyFilteredData.
                        Where(c => srchItem1.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower()) ||
                        srchItem2.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower()) ||
                        srchItem3.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower())
                );
            }
</code>```

Body:
I have a Kendo grid that has serverside filtering turned on. The field to filter by is passed as a string. For example, I want to filter by "SampleId". Now, I need to write a LINQ to Entities query that can filter by using the strongly-typed property SampleId. For example:

    db.Cases.Where(x=>targetlist.Contains(x.SampleId))

where targetlist is a list of items from the filter.

So, in effect, is there a way to write a query such that "SampleId" can directly translate to Case.SampleId?

I have tried reflection and made use of the GetProperty and GetValue and LINQ to Entities does not like it.

Any suggestions will be much appreciated!

EDIT (by pid for original poster srinaik2020):

@zaitsman: this is the code posted in an comment further below and is the actual resolution of the problem, based on the accepted answer.

public static class MyExtensions
{
    public static string GetPropertyByName(this CaseV case1, string name)
    {
        var x = typeof (CaseV).GetProperty(name).GetValue(case1);

        if (x != null)
        {
            return x.ToString();
        } else {
            return "none";
        }
    }
}

Body:
I didn't think any of these answered actually how to do the getproperty so included my working code after further research.  mymodelclass is the class of the entity/model used to MyFilteredData.

        var srchItem1 = typeof(mymodelclass).GetProperty("Name");
        var srchItem2 = typeof(mymodelclass).GetProperty("Description");
        var srchItem3 = typeof(mymodelclass).GetProperty("LongDescription");
        if (MySearchText != null && srchItem1 != null)
            {
                if (srchItem2 == null) { srchItem2 = srchItem1; }
                if (srchItem3 == null) { srchItem3 = srchItem1; }
                MyFilteredData = MyFilteredData.
                        Where(c => srchItem1.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower()) ||
                        srchItem2.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower()) ||
                        srchItem3.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower())
                );
            }


问:
Eclipse Web Page Editor not opening JSP or HTML File
Eclipse Version : 2020-03 (4.15.0)

So I am trying to open an HTML File in Web Page Editor for Visual Inspection of a Page as well as for building it via GUI, but it turns out to be a blank tab with no option for Design or Source whenever I am trying to open a File.

Thanks in Advance.

答: That's bug 561367, an API incompatibility introduced when modifying drag and drop behavior. You can go back to 2019-12 or update to 2020-06--the https://download.eclipse.org/releases/2020-06 site should already contain the fix.</p>


问:
Can the android emulator run on an ARM device
I need to do a lot of android testing where the device I use has to be ARM based. While it is possible to create these devices in the default android emulator they are of course very slow on my x86 development machine.

A lot of this testing runs headless and automatically so I thought about setting up an ARM server and emulate the devices there in the hope that the performance would be better. While looking around I realized that there is nearly no information about this. Is it possible to run an android emulator (ether the one provided with the SDK or any other) on a ARM machine to get higher performance for the virtual devices?

答:
This is actually a very good question.

Some cloud services like Amazon are providing the arm based machines. With those machines, we can run android emulators in cheap price.

Google doesn't provide the android emulator binary for arm.
But you can build those emulator binaries from AOSP. You have to do some work such as editing of cross-compile build files, adding target directories and building related third party libraries in arm architecture.

If you need any further information, I would attach detailed technical tips or step-by-step manuals.


问:
Editing timeslot for SQL in Python
I have an excel file that consists of hourly basis values, date and time as timeslot.

I want to import this excel to PostgreSQL DB, but I need to edit the date and time before. Otherwise its giving error.

Editing that date and time in excel also okay but I think doing it in python would be much easier.

I want to transform that date and time into this timeslot:

```<code>2018-05-27 00:00:00
</code>```

答:
I solve it like this, and it worked. Someone may wonder about the solution. </p>

```<code>import pandas as pd
from xlwt import Workbook
from datetime import datetime

df = pd.read_excel('yourexcell file.xlsx')
date=[]

for i in df.index:
    start_date = df['date'][i] #date column name in excel file
    start_time=df['time'][i] #time column name in excel file

    date_time = datetime.strptime(start_date, "%d.%m.%Y")

    comb=datetime.combine(date_time,start_time)

    date.append(comb)
#dateandtime combined and ready.

wb = Workbook()
sheet = wb.add_sheet('Sheet 1')

for k in range(len(date)):
    sheet.write(k,0,date[k])
wb.save('datetime_generated'+".CSV")
print("csv file saved.")
</code>```

<p>and here it is:
    output
    2018-05-27 00:00:00 </p>

Title: Editing timeslot for SQL in Python

Body:
I have an excel file that consists of hourly basis values, date and time as timeslot.

I want to import this excel to PostgreSQL DB, but I need to edit the date and time before. Otherwise its giving error.

Editing that date and time in excel also okay but I think doing it in python would be much easier.

I want to transform that date and time into this timeslot:

2018-05-27 00:00:00

Body:
I solve it like this, and it worked. Someone may wonder about the solution.

import pandas as pd
from xlwt import Workbook
from datetime import datetime

df = pd.read_excel('yourexcell file.xlsx')
date=[]

for i in df.index:
    start_date = df['date'][i] #date column name in excel file
    start_time=df['time'][i] #time column name in excel file

    date_time = datetime.strptime(start_date, "%d.%m.%Y")

    comb=datetime.combine(date_time,start_time)

    date.append(comb)
#dateandtime combined and ready.

wb = Workbook()
sheet = wb.add_sheet('Sheet 1')

for k in range(len(date)):
    sheet.write(k,0,date[k])
wb.save('datetime_generated'+".CSV")
print("csv file saved.")

and here it is:
    output
    2018-05-27 00:00:00


问:
How to get the content of nested Parentheses in groups
I'm trying to split a string such that every array element would have characters between open and close parenthesis.
let me just show:

```<code>myString = "(2*((3-2)+(5-3)))"
</code>```

So my array should have values like that:

```<code>myArray[0] = 2*((3-2)+(5-3));

myArray[1] = (3-2)+(5-3);

myArray[2] = (3-2);

myArray[3] = (5-3);
</code>```

I tried to do that by using .split() but it didn't work out as expected. I'm kinda new to the whole RegEx topic

This is my latest approach:

```<code>for (int i = 0; i <sb.length() ; i++) {
            if(sb.charAt(i)=='('){
                open=i;
                between=0;
                end=0;
                for (int j = i+1; j <sb.length() ; j++) {
                    if(sb.charAt(j)=='('){
                        between++;
                    }
                }for (int x = i+1; x <sb.length() ; x++) {
                    if(sb.charAt(x)==')'){
                        end++;
                    }
                    if(end==between){
                        a.add(sb.substring(open,x+2));
                        break;
                    }
                }
            }
        }
</code>```

答:
I don't know how to make this with regexp, but without regex I would think of something like this:

```<code>    private void findBetweenNestedBrackets(String input, List<String> matches) {
    if(input.contains("(")) {
        int firstBracket = input.indexOf("(") + 1;
        int lastBracket = input.lastIndexOf(")");
        if(firstBracket > lastBracket) {
            String firstInsideBracket = input.substring(0, lastBracket);
            String secondInsideBracket = input.substring(firstBracket);
            matches.add(firstInsideBracket);
            matches.add(secondInsideBracket);
            findBetweenNestedBrackets(firstInsideBracket, matches);
            findBetweenNestedBrackets(secondInsideBracket, matches);
        } else {
            String insideBracket = input.substring(firstBracket, lastBracket);
            matches.add(insideBracket);
            findBetweenNestedBrackets(insideBracket, matches);
        }
    }
}

@Test
public void test() {
    final String input = "(2*((3-2)+(5-3)))";
    List<String> matches = new ArrayList<>();
    findBetweenNestedBrackets(input, matches);
    matches.forEach(System.out::println);
}
</code>```

This solution is not perfect, it will print this:

2*((3-2)+(5-3))

(3-2)+(5-3)

3-2)+(5-3  I assume this is not what you wanted, but you can get rid of such later

3-2

5-3

but I belive its close to what you are trying to achive.

Body:
I'm trying to split a string such that every array element would have characters between open and close parenthesis.
let me just show:

myString = "(2*((3-2)+(5-3)))"

So my array should have values like that:

myArray[0] = 2*((3-2)+(5-3));

myArray[1] = (3-2)+(5-3);

myArray[2] = (3-2);

myArray[3] = (5-3);

I tried to do that by using .split() but it didn't work out as expected. I'm kinda new to the whole RegEx topic

This is my latest approach:

for (int i = 0; i <sb.length() ; i++) {
            if(sb.charAt(i)=='('){
                open=i;
                between=0;
                end=0;
                for (int j = i+1; j <sb.length() ; j++) {
                    if(sb.charAt(j)=='('){
                        between++;
                    }
                }for (int x = i+1; x <sb.length() ; x++) {
                    if(sb.charAt(x)==')'){
                        end++;
                    }
                    if(end==between){
                        a.add(sb.substring(open,x+2));
                        break;
                    }
                }
            }
        }

Body:
I don't know how to make this with regexp, but without regex I would think of something like this:

    private void findBetweenNestedBrackets(String input, List<String> matches) {
    if(input.contains("(")) {
        int firstBracket = input.indexOf("(") + 1;
        int lastBracket = input.lastIndexOf(")");
        if(firstBracket > lastBracket) {
            String firstInsideBracket = input.substring(0, lastBracket);
            String secondInsideBracket = input.substring(firstBracket);
            matches.add(firstInsideBracket);
            matches.add(secondInsideBracket);
            findBetweenNestedBrackets(firstInsideBracket, matches);
            findBetweenNestedBrackets(secondInsideBracket, matches);
        } else {
            String insideBracket = input.substring(firstBracket, lastBracket);
            matches.add(insideBracket);
            findBetweenNestedBrackets(insideBracket, matches);
        }
    }
}

@Test
public void test() {
    final String input = "(2*((3-2)+(5-3)))";
    List<String> matches = new ArrayList<>();
    findBetweenNestedBrackets(input, matches);
    matches.forEach(System.out::println);
}

This solution is not perfect, it will print this:

2*((3-2)+(5-3))

(3-2)+(5-3)

3-2)+(5-3  I assume this is not what you wanted, but you can get rid of such later

3-2

5-3

but I belive its close to what you are trying to achive.


问:
Manually implement structured binding in C++14
Would it be possible to implement C++17 structured bindings using C++14?
I am targetting a simple proof of concept with the following syntax:

int a,b;
(a,b)=std::tuple<int,int>(4,2);
```

<p>The way I imagined it is :</p>

<pre class="lang-cpp prettyprint-override"><code>template <typename T, typename U>
operator=(operator()(T a, U b), std::tuple<T,U>(x,y))
</code>```

So the = receives a "tied tuple" left and assigns the right to it.

Would this even be possible? - Is it implementable with C++14, or does lexing/parsing need to take place in the background to enable it?

EDIT Is this possible without using std::tie, but using the (a,b) syntax?

答:
Sure. This even already exists in the standard library as std::tie():

```<code>std::tie(a, b) = std::make_tuple(4, 2);
</code>```

Note that this only works for tuples on the right-hand side. You could fairly straightforwardly extend this to work for raw arrays. But getting it to work for aggregates is much harder - without extra language support you'd need magic_get for that.

If you literally want:

```<code>(a, b) = std::make_tuple(4, 2);
</code>```

to work, then the only way to do that is basically trash all the rest of the code you have by adding a global operator,() that does std::tie() for you:

```<code>template <typename T, typename U>
auto operator,(T& t, U& u) { return std::tie(t, u); }

template <typename... T, typename U>
auto operator,(std::tuple<T&...> t, U& u) { return std::tuple_cat(t, std::tie(u)); }
</code>```

So that:

```<code>(a, b) = std::make_tuple(4, 2);
</code>```

itself transforms into:

```<code>std::tie(a, b) = std::make_tuple(4, 2);
</code>```

But like... don't do that.

Body:
Would it be possible to implement C++17 structured bindings using C++14?
I am targetting a simple proof of concept with the following syntax:

int a,b;
(a,b)=std::tuple<int,int>(4,2);

The way I imagined it is :

template <typename T, typename U>
operator=(operator()(T a, U b), std::tuple<T,U>(x,y))

So the = receives a "tied tuple" left and assigns the right to it.

Would this even be possible? - Is it implementable with C++14, or does lexing/parsing need to take place in the background to enable it?

EDIT Is this possible without using std::tie, but using the (a,b) syntax?

Body:
Sure. This even already exists in the standard library as std::tie():

std::tie(a, b) = std::make_tuple(4, 2);

Note that this only works for tuples on the right-hand side. You could fairly straightforwardly extend this to work for raw arrays. But getting it to work for aggregates is much harder - without extra language support you'd need magic_get for that.

If you literally want:

(a, b) = std::make_tuple(4, 2);

to work, then the only way to do that is basically trash all the rest of the code you have by adding a global operator,() that does std::tie() for you:

template <typename T, typename U>
auto operator,(T& t, U& u) { return std::tie(t, u); }

template <typename... T, typename U>
auto operator,(std::tuple<T&...> t, U& u) { return std::tuple_cat(t, std::tie(u)); }

So that:

(a, b) = std::make_tuple(4, 2);

itself transforms into:

std::tie(a, b) = std::make_tuple(4, 2);

But like... don't do that.


问:
How to search through a DB using a cursor( sqlite query) in android
I am an android beginner. I am trying to design this simple application which takes the name of a city from the user using an editText View , compares that in the database , and returns the ZIP code of that city.
Now ,I'm having a problem with the implementation of cursors. Please help.How can i query the database to fetch the corresponding code.</p>

```<code>        EditText city;
    Button add,show1;
    RadioGroup choose;
    String k;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //final ContentValues values = new ContentValues();
        city=(EditText)findViewById(R.id.editText1);
        add=(Button)findViewById(R.id.add);
        choose=(RadioGroup)findViewById(R.id.radio01);
        show1=(Button)findViewById(R.id.button1);
        k=city.getText().toString();
        createDatabase();
    }
        catch(Exception e)
        {

        }

show1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        db=openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
        try{

        if(k == "CITY")
        {
            String[] result_columns=new String[]{"_id","CITY","CODE"};
            Cursor cursor = db.query(TABLE_NAME, result_columns,
                    "CITY" +"=?", new String[]{"k"}, null, null, null);

    cursor.moveToFirst();

        String xnewcode=cursor.getString(0);
        Toast.makeText(activity1.this, xnewcode, Toast.LENGTH_LONG).show();
        cursor.moveToNext();

            //db.close();
        }}
        catch(Exception e)
        {
            Toast.makeText(activity1.this,"Fault in showing " + e,Toast.LENGTH_LONG).show();

        }

    }

});
</code>```

答:
I think that you've forgot some checks. However, it really depends on the language in which the cities are written - the SQLite operator "LIKE" is case-insensitive only for English letters. If your cities are in another language, consider storing them in upper/lower case in the database and converting the input string to upper/lower case in java (String.toUpper/LowerCase() ).

```<code>String[] result_columns=new String[]{"_id","CITY","CODE"};
        Cursor cursor = db.query(TABLE_NAME, result_columns,
                "CITY" +" like '%?%'", new String[]{"k"}, null, null, null);

if(cursor != null)
{
  while(cursor.moveToNext())
  {
    String xnewcode=cursor.getString(1);
    Toast.makeText(activity1.this, xnewcode, Toast.LENGTH_LONG).show();
  }
}
</code>```

You can store all results in an array and show them to the user, asking him to choose the right one.

EDIT: If you are not familiar, the "x LIKE Y" statement compares x to any substring from Y with length = x.length. It's pretty useful, because you can't guarantee that the user will enter the whole city name. So with my example if the user enters "york", the Cursor will return values like "new york", "yorkshire", "york" and so on.

Body:
I am an android beginner. I am trying to design this simple application which takes the name of a city from the user using an editText View , compares that in the database , and returns the ZIP code of that city.
Now ,I'm having a problem with the implementation of cursors. Please help.How can i query the database to fetch the corresponding code.

        EditText city;
    Button add,show1;
    RadioGroup choose;
    String k;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //final ContentValues values = new ContentValues();
        city=(EditText)findViewById(R.id.editText1);
        add=(Button)findViewById(R.id.add);
        choose=(RadioGroup)findViewById(R.id.radio01);
        show1=(Button)findViewById(R.id.button1);
        k=city.getText().toString();
        createDatabase();
    }
        catch(Exception e)
        {

        }

show1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        db=openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
        try{

        if(k == "CITY")
        {
            String[] result_columns=new String[]{"_id","CITY","CODE"};
            Cursor cursor = db.query(TABLE_NAME, result_columns,
                    "CITY" +"=?", new String[]{"k"}, null, null, null);

    cursor.moveToFirst();

        String xnewcode=cursor.getString(0);
        Toast.makeText(activity1.this, xnewcode, Toast.LENGTH_LONG).show();
        cursor.moveToNext();

            //db.close();
        }}
        catch(Exception e)
        {
            Toast.makeText(activity1.this,"Fault in showing " + e,Toast.LENGTH_LONG).show();

        }

    }

});

Body:
I think that you've forgot some checks. However, it really depends on the language in which the cities are written - the SQLite operator "LIKE" is case-insensitive only for English letters. If your cities are in another language, consider storing them in upper/lower case in the database and converting the input string to upper/lower case in java (String.toUpper/LowerCase() ).

String[] result_columns=new String[]{"_id","CITY","CODE"};
        Cursor cursor = db.query(TABLE_NAME, result_columns,
                "CITY" +" like '%?%'", new String[]{"k"}, null, null, null);

if(cursor != null)
{
  while(cursor.moveToNext())
  {
    String xnewcode=cursor.getString(1);
    Toast.makeText(activity1.this, xnewcode, Toast.LENGTH_LONG).show();
  }
}

You can store all results in an array and show them to the user, asking him to choose the right one.

EDIT: If you are not familiar, the "x LIKE Y" statement compares x to any substring from Y with length = x.length. It's pretty useful, because you can't guarantee that the user will enter the whole city name. So with my example if the user enters "york", the Cursor will return values like "new york", "yorkshire", "york" and so on.


问:
How to define an enumerated type (enum) in C?
I'm not sure what is the proper syntax for using C enums. I have the following code:

```<code>enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;
</code>```

But this does not compile, with the following error:

```<code>error: conflicting types for ‘strategy’
error: previous declaration of ‘strategy’ was here
</code>```

What am I doing wrong?

答:
C

```<code>enum stuff q;
enum stuff {a, b=-4, c, d=-2, e, f=-3, g} s;
</code>```

Declaration which acts as a tentative definition of a signed integer s with complete type and declaration which acts as a tentative definition of signed integer q with incomplete type in the scope (which resolves to the complete type in the scope because the type definition is present anywhere in the scope) (like any tentative definition, the identifiers q and s can be redeclared with the incomplete or complete version of the same type int or enum stuff multiple times but only defined once in the scope i.e. int q = 3; and can only be redefined in a subscope, and only usable after the definition). Also you can only use the complete type of enum stuff once in the scope because it acts as a type definition.

A compiler enumeration type definition for enum stuff is also made present at file scope (usable before and below) as well as a forward type declaration (the type enum stuff can have multiple declarations but only one definition/completion in the scope and can be redefined in a subscope). It also acts as a compiler directive to substitute a with rvalue 0, b with -4, c with 5, d with -2, e with -3, f with -1 and g with -2 in the current scope. The enumeration constants now apply after the definition until the next redefinition in a different enum which cannot be on the same scope level.

```<code>typedef enum bool {false, true} bool;

//this is the same as
enum bool {false, true};
typedef enum bool bool;

//or
enum bool {false, true};
typedef unsigned int bool;

//remember though, bool is an alias for _Bool if you include stdbool.h.
//and casting to a bool is the same as the !! operator
</code>```

The tag namespace shared by enum, struct and union is separate and must be prefixed by the type keyword (enum, struct or union) in C i.e. after enum a {a} b, enum a c must be used and not a c. Because the tag namespace is separate to the identifier namespace, enum a {a} b is allowed but enum a {a, b} b is not because the constants are in the same namespace as the variable identifiers, the identifier namespace. typedef enum a {a,b} b is also not allowed because typedef-names are part of the identifier namespace.

The type of enum bool and the constants follow the following pattern in C:

```<code>+--------------+-----+-----+-----+
|   enum bool  | a=1 |b='a'| c=3 |
+--------------+-----+-----+-----+
| unsigned int | int | int | int |
+--------------+-----+-----+-----+

+--------------+-----+-----+-----+
|   enum bool  | a=1 | b=-2| c=3 |
+--------------+-----+-----+-----+
|      int     | int | int | int |
+--------------+-----+-----+-----+

+--------------+-----+---------------+-----+
|   enum bool  | a=1 |b=(-)0x80000000| c=2 |
+--------------+-----+---------------+-----+
| unsigned int | int |  unsigned int | int |
+--------------+-----+---------------+-----+

+--------------+-----+---------------+-----+
|   enum bool  | a=1 |b=(-)2147483648| c=2 |
+--------------+-----+---------------+-----+
| unsigned int | int |  unsigned int | int |
+--------------+-----+---------------+-----+

+-----------+-----+---------------+------+
| enum bool | a=1 |b=(-)0x80000000| c=-2 |
+-----------+-----+---------------+------+
|    long   | int |      long     |  int |
+-----------+-----+---------------+------+

+-----------+-----+---------------+------+
| enum bool | a=1 | b=2147483648  | c=-2 |
+-----------+-----+---------------+------+
|    long   | int |      long     |  int |
+-----------+-----+---------------+------+

+-----------+-----+---------------+------+
| enum bool | a=1 | b=-2147483648 | c=-2 |
+-----------+-----+---------------+------+
|    int    | int |      int      |  int |
+-----------+-----+---------------+------+

+---------------+-----+---------------+-----+
|   enum bool   | a=1 | b=99999999999 | c=1 |
+---------------+-----+---------------+-----+
| unsigned long | int | unsigned long | int |
+---------------+-----+---------------+-----+

+-----------+-----+---------------+------+
| enum bool | a=1 | b=99999999999 | c=-1 |
+-----------+-----+---------------+------+
|    long   | int |      long     |  int |
+-----------+-----+---------------+------+

</code>```

This compiles fine in C:

```<code>#include <stdio.h>
enum c j;
enum c{f, m} p;
typedef int d;
typedef int c;
enum c j;
enum m {n} ;
int main() {
  enum c j;
  enum d{l};
  enum d q;
  enum m y;
  printf("%llu", j);
}
</code>```

C++

In C++, enums can have a type

```<code>enum Bool: bool {True, False} Bool;
enum Bool: bool {True, False, maybe} Bool; //error
</code>```

In this situation, the constants and the identifier all have the same type, bool, and an error will occur if a number cannot be represented by that type. Maybe = 2, which isn't a bool. Also, True, False and Bool cannot be lower case otherwise they will clash with language keywords. An enum also cannot have a pointer type.

The rules for enums are different in C++.

```<code>#include <iostream>
c j; //not allowed, unknown type name c before enum c{f} p; line
enum c j; //not allowed, forward declaration of enum type not allowed and variable can have an incomplete type but not when it's still a forward declaration in C++ unlike C
enum c{f, m} p;
typedef int d;
typedef int c; // not allowed in C++ as it clashes with enum c, but if just int c were used then the below usages of c j; would have to be enum c j;
[enum] c j;
enum m {n} ;
int main() {
  [enum] c j;
  enum d{l}; //not allowed in same scope as typedef but allowed here
  d q;
  m y; //simple type specifier not allowed, need elaborated type specifier enum m to refer to enum m here
  p v; // not allowed, need enum p to refer to enum p
  std::cout << j;
}
</code>```

Enums variables in C++ are no longer just unsigned integers etc, they're also of enum type and can only be assigned constants in the enum. This can however be cast away.

```<code>#include <stdio.h>
enum a {l} c;
enum d {f} ;
int main() {
  c=0; // not allowed;
  c=l;
  c=(a)1;
  c=(enum a)4;
  printf("%llu", c); //4
}
</code>```

Enum classes

enum struct is identical to enum class

```<code>#include <stdio.h>
enum class a {b} c;
int main() {
  printf("%llu", a::b<1) ; //not allowed
  printf("%llu", (int)a::b<1) ;
  printf("%llu", a::b<(a)1) ;
  printf("%llu", a::b<(enum a)1);
  printf("%llu", a::b<(enum class a)1) ; //not allowed
  printf("%llu", b<(enum a)1); //not allowed
}
</code>```

The scope resolution operator can still be used for non-scoped enums.

```<code>#include <stdio.h>
enum a: bool {l, w} ;
int main() {
  enum a: bool {w, l} f;
  printf("%llu", ::a::w);
}
</code>```

But because w cannot be defined as something else in the scope, there is no difference between ::w and ::a::w

Body:
I'm not sure what is the proper syntax for using C enums. I have the following code:

enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;

But this does not compile, with the following error:

error: conflicting types for ‘strategy’
error: previous declaration of ‘strategy’ was here

What am I doing wrong?

Body:
C

enum stuff q;
enum stuff {a, b=-4, c, d=-2, e, f=-3, g} s;

Declaration which acts as a tentative definition of a signed integer s with complete type and declaration which acts as a tentative definition of signed integer q with incomplete type in the scope (which resolves to the complete type in the scope because the type definition is present anywhere in the scope) (like any tentative definition, the identifiers q and s can be redeclared with the incomplete or complete version of the same type int or enum stuff multiple times but only defined once in the scope i.e. int q = 3; and can only be redefined in a subscope, and only usable after the definition). Also you can only use the complete type of enum stuff once in the scope because it acts as a type definition.

A compiler enumeration type definition for enum stuff is also made present at file scope (usable before and below) as well as a forward type declaration (the type enum stuff can have multiple declarations but only one definition/completion in the scope and can be redefined in a subscope). It also acts as a compiler directive to substitute a with rvalue 0, b with -4, c with 5, d with -2, e with -3, f with -1 and g with -2 in the current scope. The enumeration constants now apply after the definition until the next redefinition in a different enum which cannot be on the same scope level.

typedef enum bool {false, true} bool;

//this is the same as
enum bool {false, true};
typedef enum bool bool;

//or
enum bool {false, true};
typedef unsigned int bool;

//remember though, bool is an alias for _Bool if you include stdbool.h.
//and casting to a bool is the same as the !! operator

The tag namespace shared by enum, struct and union is separate and must be prefixed by the type keyword (enum, struct or union) in C i.e. after enum a {a} b, enum a c must be used and not a c. Because the tag namespace is separate to the identifier namespace, enum a {a} b is allowed but enum a {a, b} b is not because the constants are in the same namespace as the variable identifiers, the identifier namespace. typedef enum a {a,b} b is also not allowed because typedef-names are part of the identifier namespace.

The type of enum bool and the constants follow the following pattern in C:

+--------------+-----+-----+-----+
|   enum bool  | a=1 |b='a'| c=3 |
+--------------+-----+-----+-----+
| unsigned int | int | int | int |
+--------------+-----+-----+-----+

+--------------+-----+-----+-----+
|   enum bool  | a=1 | b=-2| c=3 |
+--------------+-----+-----+-----+
|      int     | int | int | int |
+--------------+-----+-----+-----+

+--------------+-----+---------------+-----+
|   enum bool  | a=1 |b=(-)0x80000000| c=2 |
+--------------+-----+---------------+-----+
| unsigned int | int |  unsigned int | int |
+--------------+-----+---------------+-----+

+--------------+-----+---------------+-----+
|   enum bool  | a=1 |b=(-)2147483648| c=2 |
+--------------+-----+---------------+-----+
| unsigned int | int |  unsigned int | int |
+--------------+-----+---------------+-----+

+-----------+-----+---------------+------+
| enum bool | a=1 |b=(-)0x80000000| c=-2 |
+-----------+-----+---------------+------+
|    long   | int |      long     |  int |
+-----------+-----+---------------+------+

+-----------+-----+---------------+------+
| enum bool | a=1 | b=2147483648  | c=-2 |
+-----------+-----+---------------+------+
|    long   | int |      long     |  int |
+-----------+-----+---------------+------+

+-----------+-----+---------------+------+
| enum bool | a=1 | b=-2147483648 | c=-2 |
+-----------+-----+---------------+------+
|    int    | int |      int      |  int |
+-----------+-----+---------------+------+

+---------------+-----+---------------+-----+
|   enum bool   | a=1 | b=99999999999 | c=1 |
+---------------+-----+---------------+-----+
| unsigned long | int | unsigned long | int |
+---------------+-----+---------------+-----+

+-----------+-----+---------------+------+
| enum bool | a=1 | b=99999999999 | c=-1 |
+-----------+-----+---------------+------+
|    long   | int |      long     |  int |
+-----------+-----+---------------+------+

This compiles fine in C:

#include <stdio.h>
enum c j;
enum c{f, m} p;
typedef int d;
typedef int c;
enum c j;
enum m {n} ;
int main() {
  enum c j;
  enum d{l};
  enum d q;
  enum m y;
  printf("%llu", j);
}

C++

In C++, enums can have a type

enum Bool: bool {True, False} Bool;
enum Bool: bool {True, False, maybe} Bool; //error

In this situation, the constants and the identifier all have the same type, bool, and an error will occur if a number cannot be represented by that type. Maybe = 2, which isn't a bool. Also, True, False and Bool cannot be lower case otherwise they will clash with language keywords. An enum also cannot have a pointer type.

The rules for enums are different in C++.

#include <iostream>
c j; //not allowed, unknown type name c before enum c{f} p; line
enum c j; //not allowed, forward declaration of enum type not allowed and variable can have an incomplete type but not when it's still a forward declaration in C++ unlike C
enum c{f, m} p;
typedef int d;
typedef int c; // not allowed in C++ as it clashes with enum c, but if just int c were used then the below usages of c j; would have to be enum c j;
[enum] c j;
enum m {n} ;
int main() {
  [enum] c j;
  enum d{l}; //not allowed in same scope as typedef but allowed here
  d q;
  m y; //simple type specifier not allowed, need elaborated type specifier enum m to refer to enum m here
  p v; // not allowed, need enum p to refer to enum p
  std::cout << j;
}

Enums variables in C++ are no longer just unsigned integers etc, they're also of enum type and can only be assigned constants in the enum. This can however be cast away.

#include <stdio.h>
enum a {l} c;
enum d {f} ;
int main() {
  c=0; // not allowed;
  c=l;
  c=(a)1;
  c=(enum a)4;
  printf("%llu", c); //4
}

Enum classes

enum struct is identical to enum class

#include <stdio.h>
enum class a {b} c;
int main() {
  printf("%llu", a::b<1) ; //not allowed
  printf("%llu", (int)a::b<1) ;
  printf("%llu", a::b<(a)1) ;
  printf("%llu", a::b<(enum a)1);
  printf("%llu", a::b<(enum class a)1) ; //not allowed
  printf("%llu", b<(enum a)1); //not allowed
}

The scope resolution operator can still be used for non-scoped enums.

#include <stdio.h>
enum a: bool {l, w} ;
int main() {
  enum a: bool {w, l} f;
  printf("%llu", ::a::w);
}

But because w cannot be defined as something else in the scope, there is no difference between ::w and ::a::w


问:
why is the address the same?

why is the address of temp (in the while loop in main) the same everytime the loop runs
  i am trying to insert into a linked list and then display and then output the middle element but initially in displaying it ran an infinite loop only displayint the first element. On printing the address after inserting and llist.add_ele_to_beg(&temp); its priting the same address each time ! why is this happening ?

```<code>#include<iostream>
#include <unistd.h>

using namespace std;

class LinkedList;
class Node
{
    private:
    Node* next;
    int value;
    friend class LinkedList;
    public:
    Node(int ele) // constructor - declared in private section
    // to prevent other classes creating objects of this class,
    // only this class can create the object
    {
        next = nullptr;
        value = ele;
    }
};

class LinkedList
{
    private:
    Node* head;
    public:
    LinkedList()
    {
        head = nullptr;
    }
    void add_ele_to_beg(Node *temp)
    {
        // Node *temp = new Node(); // dynamically alloctg Node object
        // temp->value = x;
        temp->next = this->head;
        this->head = temp;
    }
    void display()
    {
        Node *h = this->head;
        while(h)
        {
            cout << h << endl;
            cout << h->value << endl;
            h = h->next;
            cout << h << endl;
            cout << h->value << endl;
            exit(0);
        }
    }
    int findMiddle()
    {
        Node *fast, *slow = this->head;
        if(!slow)
        {
            return -1;
        }
        if(!slow->next)
        {
            return slow->value;
        }
        if(!slow->next->next)
        {
            return slow->value;
        }
        // n > 2
        fast = head->next->next;

        while(1)
        {
            slow = slow->next;
            if(!fast->next)
            {
                if(!fast->next->next)
                {
                    fast = fast->next->next;
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        return slow->value;
    }
};

int main()
{
    LinkedList llist;
    int n;
    cout << "enter n" << endl;
    cin >> n;
    // create a dummy node
    cout << "enter elements to be inserted in the beg" << endl;
    int ele;
    while(n--)
    {
        cin >> ele;
        Node temp(ele); // obj node created and ctor initialises
        llist.add_ele_to_beg(&temp); // sending address of node to make change to
        cout << &temp << endl;
        // node (passing by reference)
    }

    llist.display();

    cout << llist.findMiddle();
    cout << endl;
    return 0;
}
</code>```

答:
why is the address of temp (in the while loop in main) the same everytime the loop runs

Because object you get address of has automatic storage duration. It means that object lifetime ends at the end of block it was created (end of loop in your case) and you have dangling pointer after that. As that memory considered free after lifetime of object ends compiler reuses the same memory again for practical purpose (it does not have to, but it can and it makes sense).

To make it work properly you should create object with dynamic storage duration, which means you control lifetime of the object. You can use operator new for that, but it is better to use smart pointer instead of raw one and let it manage object lifetime. In such case you should use std::make_unique or std::make_shared depends on what kind of ownership you want. You can find details on how to do it here C++ Linked list using smart pointers

Title: why is the address the same?

Body:
why is the address of temp (in the while loop in main) the same everytime the loop runs
  i am trying to insert into a linked list and then display and then output the middle element but initially in displaying it ran an infinite loop only displayint the first element. On printing the address after inserting and llist.add_ele_to_beg(&temp); its priting the same address each time ! why is this happening ?

#include<iostream>
#include <unistd.h>

using namespace std;

class LinkedList;
class Node
{
    private:
    Node* next;
    int value;
    friend class LinkedList;
    public:
    Node(int ele) // constructor - declared in private section
    // to prevent other classes creating objects of this class,
    // only this class can create the object
    {
        next = nullptr;
        value = ele;
    }
};

class LinkedList
{
    private:
    Node* head;
    public:
    LinkedList()
    {
        head = nullptr;
    }
    void add_ele_to_beg(Node *temp)
    {
        // Node *temp = new Node(); // dynamically alloctg Node object
        // temp->value = x;
        temp->next = this->head;
        this->head = temp;
    }
    void display()
    {
        Node *h = this->head;
        while(h)
        {
            cout << h << endl;
            cout << h->value << endl;
            h = h->next;
            cout << h << endl;
            cout << h->value << endl;
            exit(0);
        }
    }
    int findMiddle()
    {
        Node *fast, *slow = this->head;
        if(!slow)
        {
            return -1;
        }
        if(!slow->next)
        {
            return slow->value;
        }
        if(!slow->next->next)
        {
            return slow->value;
        }
        // n > 2
        fast = head->next->next;

        while(1)
        {
            slow = slow->next;
            if(!fast->next)
            {
                if(!fast->next->next)
                {
                    fast = fast->next->next;
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        return slow->value;
    }
};

int main()
{
    LinkedList llist;
    int n;
    cout << "enter n" << endl;
    cin >> n;
    // create a dummy node
    cout << "enter elements to be inserted in the beg" << endl;
    int ele;
    while(n--)
    {
        cin >> ele;
        Node temp(ele); // obj node created and ctor initialises
        llist.add_ele_to_beg(&temp); // sending address of node to make change to
        cout << &temp << endl;
        // node (passing by reference)
    }

    llist.display();

    cout << llist.findMiddle();
    cout << endl;
    return 0;
}


问:
NSData to NSString in ObjectiveC
I am converting the APN Device token which is in NSData format to NSString, but i am some special characters,

```<code>- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSLog(@"Device Token 111 : %@", deviceToken);

    NSString *deviceStr = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
    NSLog(@"Device Token : %@", deviceStr);
    [deviceStr release];
}

Device Token 111 : <d8b62879 48de8f9f 90507519 da1d39cf 1b700f7f 022dcaf4 7532a8b7 a6f9afe4>
Device Token : Ø¶(yHÞPuÚ9Ïep-Êôu2¨·¦ù¯ä
</code>```

I have even tried with NSASCIIStringEncoding.
What am i doing wrong ?

答:
Try using the following method with [deviceToken bytes] as the first parameter.

```<code>const static char hexchar[] = "0123456789ABCDEF";
- (NSString*) bytes2hex:(const char* ) buffer length:(int)buf_len {
    size_t i;
    char *p;
    int len = (buf_len * 2) + 1;
    p = malloc(len);
    for (i = 0; i < buf_len; i++) {
        p[i * 2] = hexchar[(unsigned char)buffer[i] >> 4 & 0xf];
        p[i * 2 + 1] = hexchar[((unsigned char)buffer[i] ) & 0xf];
    }
    p[i * 2] = '\0';
    NSString * result = [NSString stringWithCString:p encoding:NSUTF8StringEncoding];
    free(p);
    return result;
}
</code>```

Title: NSData to NSString in ObjectiveC

Body:
I am converting the APN Device token which is in NSData format to NSString, but i am some special characters,

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSLog(@"Device Token 111 : %@", deviceToken);

    NSString *deviceStr = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
    NSLog(@"Device Token : %@", deviceStr);
    [deviceStr release];
}

Device Token 111 : <d8b62879 48de8f9f 90507519 da1d39cf 1b700f7f 022dcaf4 7532a8b7 a6f9afe4>
Device Token : Ø¶(yHÞPuÚ9Ïep-Êôu2¨·¦ù¯ä

I have even tried with NSASCIIStringEncoding.
What am i doing wrong ?

Body:
Try using the following method with [deviceToken bytes] as the first parameter.

const static char hexchar[] = "0123456789ABCDEF";
- (NSString*) bytes2hex:(const char* ) buffer length:(int)buf_len {
    size_t i;
    char *p;
    int len = (buf_len * 2) + 1;
    p = malloc(len);
    for (i = 0; i < buf_len; i++) {
        p[i * 2] = hexchar[(unsigned char)buffer[i] >> 4 & 0xf];
        p[i * 2 + 1] = hexchar[((unsigned char)buffer[i] ) & 0xf];
    }
    p[i * 2] = '\0';
    NSString * result = [NSString stringWithCString:p encoding:NSUTF8StringEncoding];
    free(p);
    return result;
}


问:
Passing TempData with RedirectToAction
Intro:
I am a .NET studet trying to learn ASP.NET Core MVC. So please be understanding. I have searched the web for an answer to my problem, but havent found a solution that works for me.

Problem:
I want to pass a validation message from my create post method to the index IActionmethod whenever a post has been created and them show it as an alert message for now. I have read on the web that ViewBag dosent survive a redirect, but a TempData does. This is my code so far.

Create post method:

```<code> public IActionResult CreatePost(string textContent, string headline, string type)
    {

        var catType = new Category() { CategoryType = type.ToUpper() };

        if (db.Category.Any(s => s.CategoryType.Trim().ToLower() == type.Trim().ToLower()))
            catType = db.Category.FirstOrDefault(s => s.CategoryType.Trim().ToLower() == type.Trim().ToLower());

        var newPost = new Post()
        {
            Content = textContent,
            Header = headline,
            DateOfPost = DateTime.Now,
            category = catType

        };
        db.Posts.Add(newPost);
        db.SaveChanges();

        TempData["validation"] = "Your post hase been publsihed";

        return RedirectToAction("Index");
    }
</code>```

The index method:

```<code>public IActionResult Index()
        {

        var validation = TempData["validation"];

            var posts = (from x in db.Posts
                         orderby x.DateOfPost descending
                         orderby x.PostID descending
                         select x);

            return View(posts);
        }
</code>```

I have tried this guide: ClickThis and this one: ClickThis2 but I got this message:

I know this line from gudie number 2 might be important, but didnt now how to apply it. -

var product = TempData["myTempData"] as Product;

The last thing I want to do is pass it to the index view, but dont know how. I am currently passing a model from the index.

Tell me if it is anything more you would like to see. Like dependencies.

All the help I get is gold and will be much appreciate!!!

答:
Providers

The TempData is using various providers for storing the state. By default the cookie based data provider is used.

Session is just an alternative

If your application do not use session I do not see any reason to use it only for TempData store.

Cookie Consent

ASP NET Core 2.1 have some new GDPR features based on cookies. By default, data should be stored in cookies only with the user's consent. If the user does not agree with the storing data in cookies, TempData cannot work. This behavior varies across versions of ASP NET Core.

If you do not want to hold any sensitive data in cookies, you can obviously change the settings.

```<code>    app.UseCookiePolicy(new CookiePolicyOptions
    {
        CheckConsentNeeded = context => false
    });
</code>```

You can set the CookiePolicyOptions separatelly in ConfigureServices as well. It is a quite cleaner.

Story continues

We have two kind of data in the cookies. Essential data (needed for running application) and non-essential (some user data). User consent is needed for non-essential data. TempData is non-essential. You can set you TempData as essential and user consent is not needed anymore:

```<code>services.Configure<CookieTempDataProviderOptions>(options => {
   options.Cookie.IsEssential = true;
});
</code>```

I highly recommend to think about this before copy / paste.

Title: Passing TempData with RedirectToAction

Body:
Intro:
I am a .NET studet trying to learn ASP.NET Core MVC. So please be understanding. I have searched the web for an answer to my problem, but havent found a solution that works for me.

Problem:
I want to pass a validation message from my create post method to the index IActionmethod whenever a post has been created and them show it as an alert message for now. I have read on the web that ViewBag dosent survive a redirect, but a TempData does. This is my code so far.

Create post method:

 public IActionResult CreatePost(string textContent, string headline, string type)
    {

        var catType = new Category() { CategoryType = type.ToUpper() };

        if (db.Category.Any(s => s.CategoryType.Trim().ToLower() == type.Trim().ToLower()))
            catType = db.Category.FirstOrDefault(s => s.CategoryType.Trim().ToLower() == type.Trim().ToLower());

        var newPost = new Post()
        {
            Content = textContent,
            Header = headline,
            DateOfPost = DateTime.Now,
            category = catType

        };
        db.Posts.Add(newPost);
        db.SaveChanges();

        TempData["validation"] = "Your post hase been publsihed";

        return RedirectToAction("Index");
    }

The index method:

public IActionResult Index()
        {

        var validation = TempData["validation"];

            var posts = (from x in db.Posts
                         orderby x.DateOfPost descending
                         orderby x.PostID descending
                         select x);

            return View(posts);
        }

I have tried this guide: ClickThis and this one: ClickThis2 but I got this message:

I know this line from gudie number 2 might be important, but didnt now how to apply it. -

var product = TempData["myTempData"] as Product;

The last thing I want to do is pass it to the index view, but dont know how. I am currently passing a model from the index.

Tell me if it is anything more you would like to see. Like dependencies.

All the help I get is gold and will be much appreciate!!!

Body:
Providers

The TempData is using various providers for storing the state. By default the cookie based data provider is used.

Session is just an alternative

If your application do not use session I do not see any reason to use it only for TempData store.

Cookie Consent

ASP NET Core 2.1 have some new GDPR features based on cookies. By default, data should be stored in cookies only with the user's consent. If the user does not agree with the storing data in cookies, TempData cannot work. This behavior varies across versions of ASP NET Core.

If you do not want to hold any sensitive data in cookies, you can obviously change the settings.

    app.UseCookiePolicy(new CookiePolicyOptions
    {
        CheckConsentNeeded = context => false
    });

You can set the CookiePolicyOptions separatelly in ConfigureServices as well. It is a quite cleaner.

Story continues

We have two kind of data in the cookies. Essential data (needed for running application) and non-essential (some user data). User consent is needed for non-essential data. TempData is non-essential. You can set you TempData as essential and user consent is not needed anymore:

services.Configure<CookieTempDataProviderOptions>(options => {
   options.Cookie.IsEssential = true;
});

I highly recommend to think about this before copy / paste.


问:
Laravel 419 error on POST request via axios React
I'm trying to send a POST request to my API which is running Laravel 7.

My route is as follows:

```<code>Route::get('/data', 'CartographieController@dataToJson');
Route::post('/addDraft', 'CartographieController@addDraft');
</code>```

this is my post function in controller:

```<code>public function addDraft(Request $request)
{
    $draft = Draft::create($request->all());
    return response()->json($draft, 201);
}
</code>```

I send the from React form here is:

```<code>handleAdd(event) {
event.preventDefault();

var draft = {
  description: this.state.description,
};

try {
  const nextData = clone(this.state);
  nextData.drafts.push(draft);
  //console.log("state" + this.state);
  this.setState({ drafts: nextData.drafts });
  console.log("state" + this.state);
} catch (error) {
  console.log(error);
}

axios
  .post("http://127.0.0.1:8000/addDraft/", this.state.drafts)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</code>```

As a response to the request I get:
Request failed with status code 419

答:
when it 419 mostly because you dont sent the csrf_token on the headers, do you ?

put this on the head your html document

```<code><meta name="csrf-token" content="{{ csrf_token() }}">
</code>```

and add headers x-csrf-token to your ajax

```<code>headers: {
    'x-csrf-token': document.querySelector("[name="csrf-token]").getAttribute('content')
}
</code>```

Body:
I'm trying to send a POST request to my API which is running Laravel 7.

My route is as follows:

Route::get('/data', 'CartographieController@dataToJson');
Route::post('/addDraft', 'CartographieController@addDraft');

this is my post function in controller:

public function addDraft(Request $request)
{
    $draft = Draft::create($request->all());
    return response()->json($draft, 201);
}

I send the from React form here is:

handleAdd(event) {
event.preventDefault();

var draft = {
  description: this.state.description,
};

try {
  const nextData = clone(this.state);
  nextData.drafts.push(draft);
  //console.log("state" + this.state);
  this.setState({ drafts: nextData.drafts });
  console.log("state" + this.state);
} catch (error) {
  console.log(error);
}

axios
  .post("http://127.0.0.1:8000/addDraft/", this.state.drafts)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

As a response to the request I get:
Request failed with status code 419

Body:
when it 419 mostly because you dont sent the csrf_token on the headers, do you ?

put this on the head your html document

<meta name="csrf-token" content="{{ csrf_token() }}">

and add headers x-csrf-token to your ajax

headers: {
    'x-csrf-token': document.querySelector("[name="csrf-token]").getAttribute('content')
}


问:
Unit testing an @ObservableObject in Swift Test Driven Development
I'm trying to learn how to use MVVM architecture with TDD to solve some of the problems with not being able to unit test Views in SwiftUI.

I have an Alarm struct which takes a date:

```<code>import Foundation

struct Alarm {
    var time: Date
}
</code>```

And I have a basic

```<code>class AlarmPickerViewModel: ObservableObject {
    @Published var alarm: Alarm

    init(alarm: Alarm) {
        self.alarm = alarm
    }

}
</code>```

I'm struggling to work out how to write a unit test that fails if the AlarmPickerViewModel isn't a subclass of ObservableObject and the alarm property isn't @Published.

I've looked at this question on the site but it doesn't seem to help me.

Any pointers on where I'm going wrong please?

答:
You can create a test that won't even compile if alarm is not @Published by simply creating a subscription to that property, since you will only be able to subscribe to it if it is @Published.

The ObservableObject conformance adds an objectWillChange Publisher to your object, so to test that, you simply need to subscribe to that Publisher. If AlarmPickerViewModel wasn't ObservableObject, the test won't even compile.

```<code>func testAlarmPickerViewModel() {
    let alarmPickerViewModel = AlarmPickerViewModel(alarm: Alarm(time: .distantFuture))

    alarmPickerViewModel.$alarm.sink(receiveValue: { print("ViewModel.alarm updated, new value: \($0)") })

    alarmPickerViewModel.objectWillChange.sink(receiveValue: { print("ViewModel updated: \($0)")})
}
</code>```

Body:
I'm trying to learn how to use MVVM architecture with TDD to solve some of the problems with not being able to unit test Views in SwiftUI.

I have an Alarm struct which takes a date:

import Foundation

struct Alarm {
    var time: Date
}

And I have a basic

class AlarmPickerViewModel: ObservableObject {
    @Published var alarm: Alarm

    init(alarm: Alarm) {
        self.alarm = alarm
    }

}

I'm struggling to work out how to write a unit test that fails if the AlarmPickerViewModel isn't a subclass of ObservableObject and the alarm property isn't @Published.

I've looked at this question on the site but it doesn't seem to help me.

Any pointers on where I'm going wrong please?

Body:
You can create a test that won't even compile if alarm is not @Published by simply creating a subscription to that property, since you will only be able to subscribe to it if it is @Published.

The ObservableObject conformance adds an objectWillChange Publisher to your object, so to test that, you simply need to subscribe to that Publisher. If AlarmPickerViewModel wasn't ObservableObject, the test won't even compile.

func testAlarmPickerViewModel() {
    let alarmPickerViewModel = AlarmPickerViewModel(alarm: Alarm(time: .distantFuture))

    alarmPickerViewModel.$alarm.sink(receiveValue: { print("ViewModel.alarm updated, new value: \($0)") })

    alarmPickerViewModel.objectWillChange.sink(receiveValue: { print("ViewModel updated: \($0)")})
}


答:
On printing the address after inserting and llist.add_ele_to_beg(&temp); its priting the same address each time ! why is this happening ?

It happens because temp is a local variable, so it lives on the stack, and the same set of local variables gets created and destroyed in the same place each time through the loop:

```<code>while(n--)
{
    cin >> ele;
    Node temp(ele); // obj node created and ctor initialises
    llist.add_ele_to_beg(&temp); // sending address of node to make change to
    cout << &temp << endl;
    // node (passing by reference)
}
</code>```

So temp gets created on top of the stack, and then you do some things to it, and then it goes out of scope (so gets destroyed), and then the stack is in the same state that it was in before that iteration of the loop. And then the process repeats.

It looks like what you probably mean to be doing is allocating a new node using new, so that the object is created on the heap. You can then call list.add_ele_to_beg() to add it to the list, and the object will live beyond the end of the loop's body.

Title: why is the address the same?

Body:
On printing the address after inserting and llist.add_ele_to_beg(&temp); its priting the same address each time ! why is this happening ?

It happens because temp is a local variable, so it lives on the stack, and the same set of local variables gets created and destroyed in the same place each time through the loop:

while(n--)
{
    cin >> ele;
    Node temp(ele); // obj node created and ctor initialises
    llist.add_ele_to_beg(&temp); // sending address of node to make change to
    cout << &temp << endl;
    // node (passing by reference)
}

So temp gets created on top of the stack, and then you do some things to it, and then it goes out of scope (so gets destroyed), and then the stack is in the same state that it was in before that iteration of the loop. And then the process repeats.

It looks like what you probably mean to be doing is allocating a new node using new, so that the object is created on the heap. You can then call list.add_ele_to_beg() to add it to the list, and the object will live beyond the end of the loop's body.