问:
Reading NAS folders via powershell
Hi :) Here's my problem:
I want to see how many subfolders my NAS has.
Via Google I found the following:

```<code>Get-ChildItem -Path \\<#NASIP#>\ | SELECT Attributes, Name, CreationTime | Format-Table -AutoSize;
</code>```

I can extend this command so that I know how many (e.g. "8") there are at the end.
But now this command does not work as intended.
If I use the Pure IP: \\<#NASIP#>\ the following error is displayed:

```<code>Get-ChildItem : The path "\\<#NASIP##>\" cannot be found, because it does not exist.
</code>```

If I now specify a subfolder e.g. pictures:  \\<#NASIP#>\pictures

```<code>                Attributes Name           CreationTime
                ---------- ----           ------------
System, Directory, Archive xxxxxx         xxxxxxxxxx 15:26:37
        Directory, Archive xxxxxx         xxxxxxxxxx 20:51:17
        Directory, Archive xxxxxx         xxxxxxxxxx 11:35:26
        Directory, Archive xxxxxx         xxxxxxxxxx 21:19:19
</code>```

the command works without any problems and I get everything output correctly.
Does anybody know what this could be?

Greetings Zala

答:
Found the solution. Since the NAS does not share folders but shares, it does not work with Get-ChildItem.
As an alternative I now do it via Net view. This works without problems.
An example how the command can look like:

```<code>net view \\$target /all | ?{$_ -match 'platte*'} | %{$_ -match '^(.+?)\s+Platte*'|out-null;$matches[1]}
</code>```

Greetings Zala

Title: Reading NAS folders via powershell

Body:
Hi :) Here's my problem:
I want to see how many subfolders my NAS has.
Via Google I found the following:

Get-ChildItem -Path \\<#NASIP#>\ | SELECT Attributes, Name, CreationTime | Format-Table -AutoSize;

I can extend this command so that I know how many (e.g. "8") there are at the end.
But now this command does not work as intended.
If I use the Pure IP: \\<#NASIP#>\ the following error is displayed:

Get-ChildItem : The path "\\<#NASIP##>\" cannot be found, because it does not exist.

If I now specify a subfolder e.g. pictures:  \\<#NASIP#>\pictures

                Attributes Name           CreationTime
                ---------- ----           ------------
System, Directory, Archive xxxxxx         xxxxxxxxxx 15:26:37
        Directory, Archive xxxxxx         xxxxxxxxxx 20:51:17
        Directory, Archive xxxxxx         xxxxxxxxxx 11:35:26
        Directory, Archive xxxxxx         xxxxxxxxxx 21:19:19

the command works without any problems and I get everything output correctly.
Does anybody know what this could be?

Greetings Zala

Body:
Found the solution. Since the NAS does not share folders but shares, it does not work with Get-ChildItem.
As an alternative I now do it via Net view. This works without problems.
An example how the command can look like:

net view \\$target /all | ?{$_ -match 'platte*'} | %{$_ -match '^(.+?)\s+Platte*'|out-null;$matches[1]}

Greetings Zala


来源: stackexchange

问:
How to set key/value default state for TypeScript React app
I am having to convert a React app to Typescript and I can't figure out to property set the initial state of hash object.

original js

```<code>export default class Wizard extends PureComponent {
    constructor(props) {
        super(props);

        this.state = this.initialState();
    }

    /** Setup Steps */
    initialState = () => {
        const state = {
            activeStep: 0,
            hashKeys: {},
        };

        // Set initial classes
        // Get hash only in client side
        const hash = typeof window === 'object' ? this.getHash() : '';
        const children = React.Children.toArray(this.getSteps());
        children.forEach((child, i) => {
            // Create hashKey map
            state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`;
            state.hashKeys[state.hashKeys[i]] = i;
        });

        ...

        return state;
    }
...
</code>```

My Failed Attempt

```<code>export interface TState {
  activeStep?: number
  hashKeys: {
    [key: number]: string
  }
}

export default class StepWizard extends PureComponent<{},TState> {
   constructor(props: IStepWizardProps) {
       super(props)
       this.state = this.initialState()
   }

   initialState = () => {
    const state = {
      activeStep: 0,
      hashKeys: {},  /* <---- This seems to be the problem */
    }

    // Set initial classes
    // Get hash only in client side
    const hash = typeof window === "object" ? this.getHash() : ""

    const children = React.Children.toArray(this.getSteps())
    children.forEach((child, i) => {
      // Create hashKey map
      // the following give a TS error
      // ERROR: (property) hashKeys: {}
      //           Element implicitly has an 'any' type because expression of type 'number'
      //           can't be used to index type '{}'.
      //        No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)
      state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`
      state.hashKeys[state.hashKeys[i]] = i
    })

   ...

</code>```

I get for state.hasKeys[i] (property) hashKeys: {}
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'.
  No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)

答:
The problem seems to come from the definition of hashKeys as {}.

Typescript doesn't know what the types of data will be for the key/value, but, you can tell it!

const hashKeys = {} as Record<number, string>;

const x = hashKeys[0];
```

<p>For your example:</p>

<pre class="lang-js prettyprint-override"><code>        const state = {
            activeStep: 0,
            hashKeys: {} as Record<string, string>, // or whatever your types are
        };
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having to convert a React app to Typescript and I can't figure out to property set the initial state of hash object.

original js

export default class Wizard extends PureComponent {
    constructor(props) {
        super(props);

        this.state = this.initialState();
    }

    /** Setup Steps */
    initialState = () => {
        const state = {
            activeStep: 0,
            hashKeys: {},
        };

        // Set initial classes
        // Get hash only in client side
        const hash = typeof window === 'object' ? this.getHash() : '';
        const children = React.Children.toArray(this.getSteps());
        children.forEach((child, i) => {
            // Create hashKey map
            state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`;
            state.hashKeys[state.hashKeys[i]] = i;
        });

        ...

        return state;
    }
...

My Failed Attempt

export interface TState {
  activeStep?: number
  hashKeys: {
    [key: number]: string
  }
}

export default class StepWizard extends PureComponent<{},TState> {
   constructor(props: IStepWizardProps) {
       super(props)
       this.state = this.initialState()
   }

   initialState = () => {
    const state = {
      activeStep: 0,
      hashKeys: {},  /* <---- This seems to be the problem */
    }

    // Set initial classes
    // Get hash only in client side
    const hash = typeof window === "object" ? this.getHash() : ""

    const children = React.Children.toArray(this.getSteps())
    children.forEach((child, i) => {
      // Create hashKey map
      // the following give a TS error
      // ERROR: (property) hashKeys: {}
      //           Element implicitly has an 'any' type because expression of type 'number'
      //           can't be used to index type '{}'.
      //        No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)
      state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`
      state.hashKeys[state.hashKeys[i]] = i
    })

   ...

I get for state.hasKeys[i] (property) hashKeys: {}
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'.
  No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)

Body:
The problem seems to come from the definition of hashKeys as {}.

Typescript doesn't know what the types of data will be for the key/value, but, you can tell it!

const hashKeys = {} as Record<number, string>;

const x = hashKeys[0];

For your example:

        const state = {
            activeStep: 0,
            hashKeys: {} as Record<string, string>, // or whatever your types are
        };


问:
Is there a way to figure out what sql query is timing out with entity framework and the .NET Data Provider for SQL Server, from the application side?
The subject line says most of it. We have a search screen on our entity framework web app that is timing out and giving "System.Data.SqlClient.SqlException: Execution Timeout Expired. " error, which I believe is not a sql server error but a .net provider front end error. I believe this is due to the sql query made upon searching timing out, probably due to bad code or parameter sniffing. This app has a lot of problematic code. However, the app team are saying it is essentially on me to figure out their problem, as I manage the database, and I'm trying to push back.

My question is, is there anyway they could be debugging what the problem sql is on their end (the application side, not the database side)? Or could they only figure out what query is causing the problem with me doing some kind of trace looking at query executions that stop or something.

I don't know enough about web apps or the entity framework to know how their logs or tracing abilities should be. But to me it makes sense that they would have a log of the sql statement they are executing against our database that is timing out for them, since it is their app that is creating the statement before running it against our database. If anyone knows how to do this and advise them, I would be really grateful. I would like to teach them how to fish in terms of identifying their problematic code because there is a LOT of it.

答: "Timeout Expired" may be masking the root cause. For example when there's a conversion error on the client and the statement is executed in using block, and the row count is large, it may time out when consuming remaining rows in Dispose(). Been there, done that. I'd start with SQL Profiler to watch for long running queries.


问:
How can I set onclick to dynamic buttons while created and correspond to the correct index
So I have a simple question, my button onclick events that's created dynamically, only appears to reference the last index.  In my for loop, if I used i, I get the error "Uncaught TypeError: Cannot read property 'setAttribute' of undefine".  If I put in an index like 5, I will get the correct button.  I am sure it's something I'm overlooking and I have referenced other documents out here to no luck.  </p>

```<code><html>
<body>
<div id="numbers"></div>

<?php
$read = file('numbers.txt');?>
<script>
var rest = '<?php echo json_encode($read[0]); ?>'
rest = String(rest).replace('"','').replace('"','')
rest = rest.split(',')
console.log(rest)
for(i=0;i<rest.length;i++){
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode(rest[i]);
    btn.id = "but"+String(i);
    btn.setAttribute("style","color:red;font-size:23px");
    btn.appendChild(t);
    document.body.appendChild(btn);
    btn.addEventListener("click", function test(){
        btn[i].setAttribute("style","color:green;font-size:23px");
            });
}

</script>

</body>
</html>
</code>```

<p>***other example</p>

```<code><html>
<body>
<div id="numbers"></div>

<?php
$read = file('numbers.txt');?>
<script>
var rest = '<?php echo json_encode($read[0]); ?>'
rest = String(rest).replace('"','').replace('"','')
rest = rest.split(',')
console.log(rest)
for(i=0;i<rest.length;i++){
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode(rest[i]);
    btn.id = "but"+String(i);
    btn.setAttribute("style","color:red;font-size:23px");
    btn.appendChild(t);
    document.body.appendChild(btn);
    btn.onclick = function test(){
        document.getElementsByTagName('button')[i].setAttribute("style","color:green;font-size:23px");
            }
}

</script>

</body>
</html>
</code>```

答:
a simple fix would be the following

```<code>btn.addEventListener("click", function test(){
    this.setAttribute("style","color:green;font-size:23px");
});
</code>```

the issue with the doing something like --

```<code>btn.setAttribute("style","color:green;font-size:23px");
</code>```

or

```<code>document.getElementsByTagName('button')[i].setAttribute("style","color:green;font-size:23px");
</code>```

is that on adding event listeners, the functions are not executed immediately, instead they are executed when the user clicks on the button, at which point the loop has finished executing, and both 'i' and 'btn' refer to the last button created.

Thus using 'this' immediately solves the problem.

Body:
So I have a simple question, my button onclick events that's created dynamically, only appears to reference the last index.  In my for loop, if I used i, I get the error "Uncaught TypeError: Cannot read property 'setAttribute' of undefine".  If I put in an index like 5, I will get the correct button.  I am sure it's something I'm overlooking and I have referenced other documents out here to no luck.

<?php
$read = file('numbers.txt');?>

***other example

<?php
$read = file('numbers.txt');?>

Body:
a simple fix would be the following

btn.addEventListener("click", function test(){
    this.setAttribute("style","color:green;font-size:23px");
});

the issue with the doing something like --

btn.setAttribute("style","color:green;font-size:23px");

or

document.getElementsByTagName('button')[i].setAttribute("style","color:green;font-size:23px");

is that on adding event listeners, the functions are not executed immediately, instead they are executed when the user clicks on the button, at which point the loop has finished executing, and both 'i' and 'btn' refer to the last button created.

Thus using 'this' immediately solves the problem.


问:
What is a Covered Index?
I've just heard the term covered index in some database discussion - what does it mean?</p>

答:
A covering index is an index that contains all of, and possibly more, the columns you need for your query.

For instance, this:

```<code>SELECT *
FROM tablename
WHERE criteria
</code>```

will typically use indexes to speed up the resolution of which rows to retrieve using criteria, but then it will go to the full table to retrieve the rows.

However, if the index contained the columns column1, column2 and column3, then this sql:

```<code>SELECT column1, column2
FROM tablename
WHERE criteria
</code>```

and, provided that particular index could be used to speed up the resolution of which rows to retrieve, the index already contains the values of the columns you're interested in, so it won't have to go to the table to retrieve the rows, but can produce the results directly from the index.

This can also be used if you see that a typical query uses 1-2 columns to resolve which rows, and then typically adds another 1-2 columns, it could be beneficial to append those extra columns (if they're the same all over) to the index, so that the query processor can get everything from the index itself.

Here's an article: Index Covering Boosts SQL Server Query Performance on the subject.

OwnerDisplayName: BelowNinety

ContentLicense: CC BY-SA 2.5

Title: What is a Covered Index?

Body:
A covering index is an index that contains all of, and possibly more, the columns you need for your query.

For instance, this:

SELECT *
FROM tablename
WHERE criteria

will typically use indexes to speed up the resolution of which rows to retrieve using criteria, but then it will go to the full table to retrieve the rows.

However, if the index contained the columns column1, column2 and column3, then this sql:

SELECT column1, column2
FROM tablename
WHERE criteria

and, provided that particular index could be used to speed up the resolution of which rows to retrieve, the index already contains the values of the columns you're interested in, so it won't have to go to the table to retrieve the rows, but can produce the results directly from the index.

This can also be used if you see that a typical query uses 1-2 columns to resolve which rows, and then typically adds another 1-2 columns, it could be beneficial to append those extra columns (if they're the same all over) to the index, so that the query processor can get everything from the index itself.

Here's an article: Index Covering Boosts SQL Server Query Performance on the subject.

OwnerDisplayName: lassevk

ContentLicense: CC BY-SA 3.0


问:
asynchronous communication between server and webbowser
The server is monitoring the events in client web browser...If any events occured in client web browser,the server should be notified about that event and server should respond to that event (like invoking another java class in the server itself)...please help me with the code</p>

答: See jQuery as a starter.</p>

OwnerDisplayName: vishwa

Body: See jQuery as a starter.


问:
How can I "think OOP" when using R?
I am a statistics graduate student who works a lot with R.  I am familiar with OOP in other programming contexts.  I even see its use in various statistical packages that define new classes for storing data.

At this stage in my graduate career, I am usually coding some algorithm for some class assignment--something that takes in raw data and gives some kind of output.  I would like to make it easier to reuse code, and establish good coding habits, especially before I move on to more involved research.  Please offer some advice on how to "think OOP" when doing statistical programming in R.

答:
I take exception to David Mertz's "The methods package is still somewhat tentative from what I can tell, but some moderately tweaked version of it seems certain to continue in later R versions" mentioned in the link in BiggsTRC answer.  In my opinion, programming with classes and methods and using the methods package (S4) is the proper way to "think OOP" in R.

The last paragraph of chapter 9.2 "Programming with New Classes" (page 335) of John M. Chambers' "Software for Data  Analysis" (2008) states:
"The amount of programming involved in using a new class may be much more than that involved in defining the class.  You owe it to the users of your new classes to make that programming as effective as possible (even if you expect to be your own main user).  So the fact that the programming style in this chapter and in Chapter 10 ["Methods and Generic Functions"] is somewhat different is not a coincidence.  We're doing some more serious programming here."

Consider studying the methods package (S4).

Title: How can I "think OOP" when using R?


问:
nodejs/JS: Objects not being updated in array
Firstly, I am a complete noob to Javascript and Node.js.

I tried to write a simple program that creates an array of planes that all have the same values except in index, which should take on the value of each index in the for loop from 0 - 2.

Here is my code

```<code>var plane = {
    index: -1,
    name: "A380",
    seats: {
        first: 40,
        buisness: 90,
        economy: 300
    },
    wheels: 8,
}

var planeArray = []

for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push(plane)
  }

  console.log(planeArray)
</code>```

But when I print the output, the indices of all the planes are 2. Here is my output.

```<code>[
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]
</code>```

Here is my expected output.

```<code>[
  {
    index: 0,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 1,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]
</code>```

I don't understand why.
Could someone help me out. Also, any additional explanations/resources helpful for learning node.js would be greatly appreciated

答:
The problem here is that the object being added in the array goes as a reference and not as the value of the object
you can either try either of the below two solutions.
This way you pass the object value instead of its reference.</p>

```<code>for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push({...plane})
  }
</code>```

```<code>for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push(JSON.parse(JSON.stringify(plane)))
  }
</code>```

Body:
Firstly, I am a complete noob to Javascript and Node.js.

I tried to write a simple program that creates an array of planes that all have the same values except in index, which should take on the value of each index in the for loop from 0 - 2.

Here is my code

var plane = {
    index: -1,
    name: "A380",
    seats: {
        first: 40,
        buisness: 90,
        economy: 300
    },
    wheels: 8,
}

var planeArray = []

for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push(plane)
  }

  console.log(planeArray)

But when I print the output, the indices of all the planes are 2. Here is my output.

[
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]

Here is my expected output.

[
  {
    index: 0,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 1,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  },
  {
    index: 2,
    name: 'A380',
    seats: { first: 40, buisness: 90, economy: 300 },
    wheels: 8
  }
]

I don't understand why.
Could someone help me out. Also, any additional explanations/resources helpful for learning node.js would be greatly appreciated

Body:
The problem here is that the object being added in the array goes as a reference and not as the value of the object
you can either try either of the below two solutions.
This way you pass the object value instead of its reference.

for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push({...plane})
  }

for (var i = 0; i < 3; i++) {
    plane.index = i
    planeArray.push(JSON.parse(JSON.stringify(plane)))
  }


问:
is there a possible way to catch no connection or timeout Exception in firestore?
I am making my app that when it firestore tries to communicate with the server then when it fails it will display to the user that he has no connection

first of all this code checks if the id that came from google Auth is already registered to the firestore

```<code>public FirebaseHelper CheckAccount(String id, final OnCheckAccountListener checkAccountListener){
    DocumentReference docIdRef = db.collection(Values.users).document(id);
    docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()){
                    DocumentSnapshot document = task.getResult();
                    checkAccountListener.AccountExist(document.exists());
                }else{
                    if (task.getException().equals(FirebaseFirestoreException.Code.UNAVAILABLE)){
                        //Shows user that he/she is offline
                        checkAccountListener.onNoConnection();
                    }else {
                        //other catastrophic error
                        checkAccountListener.onError(task.getException().getMessage());
                    }
                }
        }
    });
    return this;
}
public interface OnCheckAccountListener{
    void AccountExist(boolean itExists);
    void onNoConnection();
    void onError(String Error);
}
</code>```

now when i disconnect my internet then auth my account it will check the account then task.isSuccessful() is false and instead of displaying no connection like this

no connection dialog

it shows this

error dialog

and as you can see the reason is client is offline

there is a possible solution but its not nice

the solution is just

```<code>if(task.getException().getMessage().contains("offline")
</code>```

sorry if bad explanation if you need more details just reply thx!

and if your wondering why there is an interface in the code
because it runs in different classes just to neat things up!
and the pictures are customdialog
and i also made a loading dialog like this!

enter image description here

all image in the dialog are GIF's and they are awesome!

答:
Firestore does not have connection errors that you can catch.  The SDK will automatically initiate and retry broken connections in the background for as long as your app process is alive.  You don't have any direct control over how this works.

For a list of error codes that you can get by handling an FirebaseFirestoreException object, read the API documenatation.

Body:
I am making my app that when it firestore tries to communicate with the server then when it fails it will display to the user that he has no connection

first of all this code checks if the id that came from google Auth is already registered to the firestore

public FirebaseHelper CheckAccount(String id, final OnCheckAccountListener checkAccountListener){
    DocumentReference docIdRef = db.collection(Values.users).document(id);
    docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()){
                    DocumentSnapshot document = task.getResult();
                    checkAccountListener.AccountExist(document.exists());
                }else{
                    if (task.getException().equals(FirebaseFirestoreException.Code.UNAVAILABLE)){
                        //Shows user that he/she is offline
                        checkAccountListener.onNoConnection();
                    }else {
                        //other catastrophic error
                        checkAccountListener.onError(task.getException().getMessage());
                    }
                }
        }
    });
    return this;
}
public interface OnCheckAccountListener{
    void AccountExist(boolean itExists);
    void onNoConnection();
    void onError(String Error);
}

now when i disconnect my internet then auth my account it will check the account then task.isSuccessful() is false and instead of displaying no connection like this

no connection dialog

it shows this

error dialog

and as you can see the reason is client is offline

there is a possible solution but its not nice

the solution is just

if(task.getException().getMessage().contains("offline")

sorry if bad explanation if you need more details just reply thx!

and if your wondering why there is an interface in the code
because it runs in different classes just to neat things up!
and the pictures are customdialog
and i also made a loading dialog like this!

enter image description here

all image in the dialog are GIF's and they are awesome!


问:
The position argument error and resolving it
I am trying to implement a shopping cart in python and have this code but the error is that when i am calling a print_menu function , the arguments are not correct.  </p>

```<code>    class ItemToPurchase:
    def __init__(self, item_name= 'none', item_price=0, item_quantity=0, item_description = 'none'):

        self.item_name = item_name

        self.item_price = item_price

        self.item_quantity = item_quantity

        self.item_description = item_description

    def print_item_cost(self):

        string = '{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price, (self.item_quantity* self.item_price))

        cost = self.item_quantity * self.item_price

        return string, cost

    def print_item_description(self):

        string = '{}: {}'.format(self.item_name, self.item_description)

        print(string, end=' ')

        return string

class ShoppingCart:

    def __init__(self,customer_name= None ,current_date='January 1,2016',cart_items=[]):

        self.customer_name = customer_name

        self.current_date = current_date

        self.cart_items = cart_items

    def add_item(self):
        print('\nADD ITEM TO CART', end='\n')
        item_name = str(input('Enter the item name:'))
        item_description = str(input('\nEnter the item description:'))
        item_price = int(input('\nEnter the item price:'))
        item_quantity = int(input('\nEnter the item quantity:\n'))
        self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))

    def remove_item(self):
        print()
        print('REMOVE ITEM FROM CART', end='\n')
        string = str(input('Enter name of item to remove:\n'))
        i = 0
        for item in self.cart_items:
            if(item.item_name == string):
                del self.cart_items[i]
                i += 1
                flag=True
                break
            else:
                flag=False
            if(flag==False):
                print('Item not found in cart. Nothing removed.')

    def modify_item(self):

        print('\nCHANGE ITEM QUANTITY', end='\n')
        name = str(input('Enter the item name:'))
        for item in self.cart_items:
            if(item.item_name == name):
                quantity = int(input('Enter the new quantity:'))
                item.item_quantity = quantity
                flag=True
                break
            else:

                flag=False

            if(flag==False):

                 print('Item not found in cart. Nothing modified.')

    def get_num_items_in_cart(self):

        num_items = 0

        for item in self.cart_items:
            num_items += item.item_quantity
        return num_items

    def get_cost_of_cart(self):

        total_cost = 0
        cost = 0
        for item in self.cart_items:

                cost = (item.item_quantity * item.item_price)

                total_cost += cost
        return total_cost

    def print_total(self):

        total_cost = self.get_cost_of_cart()

        if (total_cost == 0):

            print('SHOPPING CART IS EMPTY')

        else:

            self.output_cart()

    def print_descriptions(self):

        print('OUTPUT ITEMS\' DESCRIPTIONS')

        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date),end='\n')

        print('\nItem Descriptions', end='\n')

        for item in self.cart_items:

            print('{}: {}'.format(item.item_name, item.item_description), end='\n')

    def output_cart(self):

        new=ShoppingCart()

        print('OUTPUT SHOPPING CART', end='\n')

        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date),end='\n')

        print('Number of Items:', new.get_num_items_in_cart(), end='\n\n')

        self.total_cost = self.get_cost_of_cart()

        if (self.total_cost == 0):

            print('SHOPPING CART IS EMPTY')

        else:

            pass

        tc = 0

        for item in self.cart_items:

            print('{} {} @ ${} = ${}'.format(item.item_name, item.item_quantity,

            item.item_price, (item.item_quantity * item.item_price)), end='\n')

            tc += (item.item_quantity * item.item_price)

            print('\nTotal: ${}'.format(tc), end='\n')

    def print_menu(ShoppingCart):

        customer_Cart = newCart

        string=' '

    #declare the string menu

        menu = ('\nMENU\n'

         'a - Add item to cart\n'

         'r - Remove item from cart\n'

         'c - Change item quantity\n'

         'i - Output items\' descriptions\n'

         'o - Output shopping cart\n'

         'q - Quit\n')

        command = ''

    #Using while loop

    #to iterate until user enters q

        while(command != 'q'):

            string=''

            print(menu, end='\n')

        #Prompt the Command

            command = input('Choose an option: ')

        #repeat the loop until user enters a,i,r,c,q commands

        while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'):

             command = input('Choose an option: ')

        #If the input command is a

             if(command == 'a'):

            #call the method to the add elements to the cart

                 customer_Cart.add_item(string)

        #If the input command is o

             if(command == 'o'):

            #call the method to the display the elements in the cart

                    customer_Cart.output_cart()

        #If the input command is i

             if(command == 'i'):

            #call the method to the display the elements in the cart

                customer_Cart.print_descriptions()

        #If the input command is i

             if(command == 'r'):

                customer_Cart.remove_item()

             if(command == 'c'):

                customer_Cart.modify_item()

if __name__ == "__main__":
    customer_name = str(input('Enter customer\'s name:'))
    current_date = str(input('\nEnter today\'s date:'))
    print()
    print()
    print('Customer name:', customer_name, end='\n')
    print('Today\'s date:', current_date, end='\n')
    newCart = ShoppingCart(customer_name, current_date)
    newCart.print_menu(newCart)
</code>```

<p>i have created an instance of class ShopppingCart but it is not working. i am trying to get a user input and then display the menu for user to choose and implement one of the functions defined in the shopping cart class . Can anyone help me with resolving this issue. </p>

答:
This issue is happening because of function's argument, ShoppingCart. You have called the first argument ShoppingCart, which in reality is the ShoppingCart object; usually this is the self argument. Python does not care what you name it: self, ShoppingCart, corona. The first argument will always be the object that called the function. When calling this function with these lines of code:

```<code>newCart = ShoppingCart(customer_name, current_date)
newCart.print_menu(newCart)
</code>```

you are using the newCart object to call the function and then passing the newCart object as an argument. You don't need to do this. Python already passes the object, so you don't have to.

I'm assuming this is the error you received:

```<code>Traceback (most recent call last):
  File "c:/Users/jeffg/Desktop/ProgrammingProjects/StackOverFlow/shoppingcart.py", line 246, in <module>
    newCart.print_menu(newCart)
TypeError: print_menu() takes 1 positional argument but 2 were given
</code>```

This error takes place because you're function is defined to only take one argument. You didn't account for the self argument. To fix this, the code would need to be modified to something like this:

```<code>def print_menu(self, newCart):
   customer_Cart = newCart
</code>```

Although as discussed before, you don't need the newCart object to be passed, since you already have access to the newCart object with self. You can then slim down the function to this:

```<code>def print_menu(self):
</code>```

And instead of using customer_Cart to call the functions, you can use self:

```<code>while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'):
   command = input('Choose an option: ')
   if(command == 'a'):
   self.add_item(string)
</code>```

I would also recommend using elif statements instead of using numerous if statements inside your print_menu() function.

Body:
I am trying to implement a shopping cart in python and have this code but the error is that when i am calling a print_menu function , the arguments are not correct.

    class ItemToPurchase:
    def __init__(self, item_name= 'none', item_price=0, item_quantity=0, item_description = 'none'):

        self.item_name = item_name

        self.item_price = item_price

        self.item_quantity = item_quantity

        self.item_description = item_description

    def print_item_cost(self):

        string = '{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price, (self.item_quantity* self.item_price))

        cost = self.item_quantity * self.item_price

        return string, cost

    def print_item_description(self):

        string = '{}: {}'.format(self.item_name, self.item_description)

        print(string, end=' ')

        return string

class ShoppingCart:

    def __init__(self,customer_name= None ,current_date='January 1,2016',cart_items=[]):

        self.customer_name = customer_name

        self.current_date = current_date

        self.cart_items = cart_items

    def add_item(self):
        print('\nADD ITEM TO CART', end='\n')
        item_name = str(input('Enter the item name:'))
        item_description = str(input('\nEnter the item description:'))
        item_price = int(input('\nEnter the item price:'))
        item_quantity = int(input('\nEnter the item quantity:\n'))
        self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))

    def remove_item(self):
        print()
        print('REMOVE ITEM FROM CART', end='\n')
        string = str(input('Enter name of item to remove:\n'))
        i = 0
        for item in self.cart_items:
            if(item.item_name == string):
                del self.cart_items[i]
                i += 1
                flag=True
                break
            else:
                flag=False
            if(flag==False):
                print('Item not found in cart. Nothing removed.')

    def modify_item(self):

        print('\nCHANGE ITEM QUANTITY', end='\n')
        name = str(input('Enter the item name:'))
        for item in self.cart_items:
            if(item.item_name == name):
                quantity = int(input('Enter the new quantity:'))
                item.item_quantity = quantity
                flag=True
                break
            else:

                flag=False

            if(flag==False):

                 print('Item not found in cart. Nothing modified.')

    def get_num_items_in_cart(self):

        num_items = 0

        for item in self.cart_items:
            num_items += item.item_quantity
        return num_items

    def get_cost_of_cart(self):

        total_cost = 0
        cost = 0
        for item in self.cart_items:

                cost = (item.item_quantity * item.item_price)

                total_cost += cost
        return total_cost

    def print_total(self):

        total_cost = self.get_cost_of_cart()

        if (total_cost == 0):

            print('SHOPPING CART IS EMPTY')

        else:

            self.output_cart()

    def print_descriptions(self):

        print('OUTPUT ITEMS\' DESCRIPTIONS')

        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date),end='\n')

        print('\nItem Descriptions', end='\n')

        for item in self.cart_items:

            print('{}: {}'.format(item.item_name, item.item_description), end='\n')

    def output_cart(self):

        new=ShoppingCart()

        print('OUTPUT SHOPPING CART', end='\n')

        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date),end='\n')

        print('Number of Items:', new.get_num_items_in_cart(), end='\n\n')

        self.total_cost = self.get_cost_of_cart()

        if (self.total_cost == 0):

            print('SHOPPING CART IS EMPTY')

        else:

            pass

        tc = 0

        for item in self.cart_items:

            print('{} {} @ ${} = ${}'.format(item.item_name, item.item_quantity,

            item.item_price, (item.item_quantity * item.item_price)), end='\n')

            tc += (item.item_quantity * item.item_price)

            print('\nTotal: ${}'.format(tc), end='\n')

    def print_menu(ShoppingCart):

        customer_Cart = newCart

        string=' '

    #declare the string menu

        menu = ('\nMENU\n'

         'a - Add item to cart\n'

         'r - Remove item from cart\n'

         'c - Change item quantity\n'

         'i - Output items\' descriptions\n'

         'o - Output shopping cart\n'

         'q - Quit\n')

        command = ''

    #Using while loop

    #to iterate until user enters q

        while(command != 'q'):

            string=''

            print(menu, end='\n')

        #Prompt the Command

            command = input('Choose an option: ')

        #repeat the loop until user enters a,i,r,c,q commands

        while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'):

             command = input('Choose an option: ')

        #If the input command is a

             if(command == 'a'):

            #call the method to the add elements to the cart

                 customer_Cart.add_item(string)

        #If the input command is o

             if(command == 'o'):

            #call the method to the display the elements in the cart

                    customer_Cart.output_cart()

        #If the input command is i

             if(command == 'i'):

            #call the method to the display the elements in the cart

                customer_Cart.print_descriptions()

        #If the input command is i

             if(command == 'r'):

                customer_Cart.remove_item()

             if(command == 'c'):

                customer_Cart.modify_item()

if __name__ == "__main__":
    customer_name = str(input('Enter customer\'s name:'))
    current_date = str(input('\nEnter today\'s date:'))
    print()
    print()
    print('Customer name:', customer_name, end='\n')
    print('Today\'s date:', current_date, end='\n')
    newCart = ShoppingCart(customer_name, current_date)
    newCart.print_menu(newCart)

i have created an instance of class ShopppingCart but it is not working. i am trying to get a user input and then display the menu for user to choose and implement one of the functions defined in the shopping cart class . Can anyone help me with resolving this issue.

Body:
This issue is happening because of function's argument, ShoppingCart. You have called the first argument ShoppingCart, which in reality is the ShoppingCart object; usually this is the self argument. Python does not care what you name it: self, ShoppingCart, corona. The first argument will always be the object that called the function. When calling this function with these lines of code:

newCart = ShoppingCart(customer_name, current_date)
newCart.print_menu(newCart)

you are using the newCart object to call the function and then passing the newCart object as an argument. You don't need to do this. Python already passes the object, so you don't have to.

I'm assuming this is the error you received:

Traceback (most recent call last):
  File "c:/Users/jeffg/Desktop/ProgrammingProjects/StackOverFlow/shoppingcart.py", line 246, in <module>
    newCart.print_menu(newCart)
TypeError: print_menu() takes 1 positional argument but 2 were given

This error takes place because you're function is defined to only take one argument. You didn't account for the self argument. To fix this, the code would need to be modified to something like this:

def print_menu(self, newCart):
   customer_Cart = newCart

Although as discussed before, you don't need the newCart object to be passed, since you already have access to the newCart object with self. You can then slim down the function to this:

def print_menu(self):

And instead of using customer_Cart to call the functions, you can use self:

while (command != 'a' and command != 'o' and command != 'i' and command != 'r' and command != 'c' and command != 'q'):
   command = input('Choose an option: ')
   if(command == 'a'):
   self.add_item(string)

I would also recommend using elif statements instead of using numerous if statements inside your print_menu() function.


问:
Can Typescript guard / discriminate based on field presence (undefined / absent) rather than value?
Can anyone explain why Typescript can narrow types with the in keyword, but not by presence an non-undefined value? I'm porting a large codebase from JS to TS, and very extensive use has been made of the if (x.something) { ... } construct.

```<code>declare const x: { a?: object } | { b: number };

if ('a' in x) {
  const Q = x.a;  // Q: object | undefined, correct but not very helpful - still have to test Q for non-undefined
}

if (x.a) {
  const Q = x.a; // Doesn't work, but if it did, Q: object, which is helpful
}

if (typeof x.a !== "undefined") {
  const Q = x.a; // Same as above
}
</code>```

Note that if it's not a union, it works as expected:

```<code>declare const x: { a?: object }

if ('a' in x) {
  const Q = x.a;  // Q: object | undefined, correct but not very helpful
}

if (x.a) {
  const Q = x.a; // Q: object (yay!)
}
</code>```

答:
The problem

There are a few rules to keep in mind:

You are allowed to read only the properties that exist on every member of the union. That's why if (x.a) errors — a is not defined on the second member of your union.

Object types are allowed to have excess properties. TypeScript uses structural typing. This means that a type { foo: string, bar: number } is, in general, assignable to type { foo: string }. That's why if ('a' in x) doesn't work — any type with a property called a would pass that check. We have no guarantee that the value will be an object, though. It's not safe to assume it.

In order to disjoin unions, prefer user-defined type guards over inline checks like typeof x === "string". Type guards have a special syntax that tells TypeScript to narrow the checked type. That's why if (typeof x.a !== "undefined") doesn't work in your example.

The solution

Make your union exclusive. Tell TypeScript that if a exists, then b will never be defined, and vice versa.

```<code>declare const x: { a?: object, b?: undefined } | { b: number, a?: undefined }
</code>```

Note that we're marking the unwanted properties as optional. If instead we did { a?: object, b?: undefined } | { b: number, a?: undefined }, then the unwanted properties would be required, and x would have to have them set explicitly to undefined.

You can now use these methods to work with x.

```<code>function isDefined<T>(candidate: T | null | undefined): candidate is T {
  return candidate != null;
}

if (x.a) {
  const Q = x.a; // object
}

if (isDefined(x.a)) {
  const Q = x.a; // object
}

if (typeof x.a !== "undefined") {
  const Q = x.a; // object
}
</code>```

Note that you still cannot use the method using the in operator. There is a good reason for that: it prevents false positives. Our unwanted properties are allowed to exist on the object for as long as their value is explicitly set to undefined. Consider the following example:

```<code>function test(x: { a?: object, b?: undefined } | { b: number, a?: undefined }): void {
  if ('a' in x) {
    x.a; // object | undefined (good). We cannot expect object here.
  }
}

test({ b: 1, a: undefined }); // "a" is not an object!
</code>```

Tip: use ExclusiveUnion helper

Instead of marking the unwanted properties as ?undefined, we can create a helper to do that for us.

```<code>declare const x: ExclusiveUnion<{ a?: object } | { b: number }>;
</code>```

Implementation:

```<code>type DistributedKeyOf<T> =
  T extends any
    ? keyof T
    : never;

type CreateExclusiveUnion<T, U = T> =
  T extends any
    ? T & Partial<Record<Exclude<DistributedKeyOf<U>, keyof T>, never>>
    : never;

type ExclusiveUnion<T> = CreateExclusiveUnion<T>;
</code>```

Body:
Can anyone explain why Typescript can narrow types with the in keyword, but not by presence an non-undefined value? I'm porting a large codebase from JS to TS, and very extensive use has been made of the if (x.something) { ... } construct.

declare const x: { a?: object } | { b: number };

if ('a' in x) {
  const Q = x.a;  // Q: object | undefined, correct but not very helpful - still have to test Q for non-undefined
}

if (x.a) {
  const Q = x.a; // Doesn't work, but if it did, Q: object, which is helpful
}

if (typeof x.a !== "undefined") {
  const Q = x.a; // Same as above
}

Note that if it's not a union, it works as expected:

declare const x: { a?: object }

if ('a' in x) {
  const Q = x.a;  // Q: object | undefined, correct but not very helpful
}

if (x.a) {
  const Q = x.a; // Q: object (yay!)
}

Body:
The problem

There are a few rules to keep in mind:

You are allowed to read only the properties that exist on every member of the union. That's why if (x.a) errors — a is not defined on the second member of your union.

Object types are allowed to have excess properties. TypeScript uses structural typing. This means that a type { foo: string, bar: number } is, in general, assignable to type { foo: string }. That's why if ('a' in x) doesn't work — any type with a property called a would pass that check. We have no guarantee that the value will be an object, though. It's not safe to assume it.

In order to disjoin unions, prefer user-defined type guards over inline checks like typeof x === "string". Type guards have a special syntax that tells TypeScript to narrow the checked type. That's why if (typeof x.a !== "undefined") doesn't work in your example.

The solution

Make your union exclusive. Tell TypeScript that if a exists, then b will never be defined, and vice versa.

declare const x: { a?: object, b?: undefined } | { b: number, a?: undefined }

Note that we're marking the unwanted properties as optional. If instead we did { a?: object, b?: undefined } | { b: number, a?: undefined }, then the unwanted properties would be required, and x would have to have them set explicitly to undefined.

You can now use these methods to work with x.

function isDefined<T>(candidate: T | null | undefined): candidate is T {
  return candidate != null;
}

if (x.a) {
  const Q = x.a; // object
}

if (isDefined(x.a)) {
  const Q = x.a; // object
}

if (typeof x.a !== "undefined") {
  const Q = x.a; // object
}

Note that you still cannot use the method using the in operator. There is a good reason for that: it prevents false positives. Our unwanted properties are allowed to exist on the object for as long as their value is explicitly set to undefined. Consider the following example:

function test(x: { a?: object, b?: undefined } | { b: number, a?: undefined }): void {
  if ('a' in x) {
    x.a; // object | undefined (good). We cannot expect object here.
  }
}

test({ b: 1, a: undefined }); // "a" is not an object!

Tip: use ExclusiveUnion helper

Instead of marking the unwanted properties as ?undefined, we can create a helper to do that for us.

declare const x: ExclusiveUnion<{ a?: object } | { b: number }>;

Implementation:

type DistributedKeyOf<T> =
  T extends any
    ? keyof T
    : never;

type CreateExclusiveUnion<T, U = T> =
  T extends any
    ? T & Partial<Record<Exclude<DistributedKeyOf<U>, keyof T>, never>>
    : never;

type ExclusiveUnion<T> = CreateExclusiveUnion<T>;


问:
Hello, I actually want to understand the following code. Can someone please elaborate the code what exactly it is doing. why is it crashing at line 31
I am not able to understand why is it crashing with a segment fault error. I assume it is returning an invalid pointer @operatingtrialClass(nullptr)->sum();
Can somebody explain why?</p>

```<code>#include <iostream>

class trialClass{
public:

    trialClass () = default;
    ~trialClass ();

    virtual int sum () = 0;
    virtual int mul () = 0;
};

class secondtrial{
public:

    static trialClass * operatingtrialClass (trialClass * l_trialClass)
    {
        trialClass * m_trialClass;
        if (l_trialClass != nullptr)
            m_trialClass = l_trialClass;

        return m_trialClass;
    }

    static int sum ()
    {
        int a = 2;
        int b = 3;
        int sum = a + b;

        /*Crash point*/
        return operatingtrialClass(nullptr)->sum();
    }

};

int main()
{
    //trialClass * p_trialClass;enter code here
    secondtrial * sec = new secondtrial;
    //secondtrial::operatingtrialClass(reinterpret_cast<trialClass*>(sec));
    std::cout<<sec->sum()<<std::endl;
}
</code>```

答:
In

```<code>static trialClass * operatingtrialClass (trialClass * l_trialClass)
{
    trialClass * m_trialClass;
    if (l_trialClass != nullptr)
        m_trialClass = l_trialClass;

    return m_trialClass;
}
</code>```

trialClass * m_trialClass; points m_trialClass nowhere useful or safe. If l_trialClass is a nullptr, which it is, m_trialClass is returned without ever being pointed at something safe, making the operatingtrialClass(nullptr)->sum(); in

```<code>static int sum ()
{
    int a = 2;
    int b = 3;
    int sum = a + b;

    /*Crash point*/
    return operatingtrialClass(nullptr)->sum();
}
</code>```

an adventure in the wild and wacky world of Undefined Behaviour (UB) because we don't know where the returned pointer points. Anything can happen in UB-land, and in this case that anything is a crash. It could just as easily not crash and produce a result that fools you into thinking the program is correct. Nasty stuff, UB.

How best to solve this depends entirely on what you want the program to do. You could

```<code>static trialClass * operatingtrialClass (trialClass * l_trialClass)
{
    static trialClass defaultTC; // a generic and safe trialClass
    static trialClass * m_trialClass = &defaultTC; // point at the safe trialClass
                                                   // note the use of static to allow m_trialClass
                                                   // to persist across multiple calls.
                                                   // it's pretty much useless if it gets
                                                   // recreated every time.
    if (l_trialClass != nullptr)
        m_trialClass = l_trialClass;

    return m_trialClass;
}
</code>```

so that you always have a safe trialClass, but this may not be the correct option for your unspecified use case.

Side note: secondtrial contains no state. Without state you can save yourself a bit of work and make a namespace.

Body:
I am not able to understand why is it crashing with a segment fault error. I assume it is returning an invalid pointer @operatingtrialClass(nullptr)->sum();
Can somebody explain why?

#include <iostream>

class trialClass{
public:

    trialClass () = default;
    ~trialClass ();

    virtual int sum () = 0;
    virtual int mul () = 0;
};

class secondtrial{
public:

    static trialClass * operatingtrialClass (trialClass * l_trialClass)
    {
        trialClass * m_trialClass;
        if (l_trialClass != nullptr)
            m_trialClass = l_trialClass;

        return m_trialClass;
    }

    static int sum ()
    {
        int a = 2;
        int b = 3;
        int sum = a + b;

        /*Crash point*/
        return operatingtrialClass(nullptr)->sum();
    }

};

int main()
{
    //trialClass * p_trialClass;enter code here
    secondtrial * sec = new secondtrial;
    //secondtrial::operatingtrialClass(reinterpret_cast<trialClass*>(sec));
    std::cout<<sec->sum()<<std::endl;
}

Body:
In

static trialClass * operatingtrialClass (trialClass * l_trialClass)
{
    trialClass * m_trialClass;
    if (l_trialClass != nullptr)
        m_trialClass = l_trialClass;

    return m_trialClass;
}

trialClass * m_trialClass; points m_trialClass nowhere useful or safe. If l_trialClass is a nullptr, which it is, m_trialClass is returned without ever being pointed at something safe, making the operatingtrialClass(nullptr)->sum(); in

static int sum ()
{
    int a = 2;
    int b = 3;
    int sum = a + b;

    /*Crash point*/
    return operatingtrialClass(nullptr)->sum();
}

an adventure in the wild and wacky world of Undefined Behaviour (UB) because we don't know where the returned pointer points. Anything can happen in UB-land, and in this case that anything is a crash. It could just as easily not crash and produce a result that fools you into thinking the program is correct. Nasty stuff, UB.

How best to solve this depends entirely on what you want the program to do. You could

static trialClass * operatingtrialClass (trialClass * l_trialClass)
{
    static trialClass defaultTC; // a generic and safe trialClass
    static trialClass * m_trialClass = &defaultTC; // point at the safe trialClass
                                                   // note the use of static to allow m_trialClass
                                                   // to persist across multiple calls.
                                                   // it's pretty much useless if it gets
                                                   // recreated every time.
    if (l_trialClass != nullptr)
        m_trialClass = l_trialClass;

    return m_trialClass;
}

so that you always have a safe trialClass, but this may not be the correct option for your unspecified use case.

Side note: secondtrial contains no state. Without state you can save yourself a bit of work and make a namespace.


问:
How to specify a condition inside a for_loop
How do i use a condition inside a for_each such that , the below resource is created/triggered only when validation_method == "DNS" else ignores the creation of a resource. However in earlier terraform (11 versions) we can use

count =  var.validation_method == "DNS" ? length(var.domain_names) : 0

My var.domain_names is map(list(string)) , eg

```<code>domain_names = {
    "foo.com" = ["*.foo.com"]
  }
</code>```

Please suggest me some solutions. Using terraform 0.12.20 version

```<code>resource "aws_route53_record" "validation" {
  for_each   = var.validation_method == "DNS" ? var.domain_names :
  name       = aws_acm_certificate.certificate[each.key].domain_validation_options.0.resource_record_name
  type       = aws_acm_certificate.certificate[each.key].domain_validation_options.0.resource_record_type
  zone_id    = data.aws_route53_zone.selected[each.key].zone_id
  ttl        = "300"
  records    = [aws_acm_certificate.certificate.domain_validation_options.0.resource_record_value]
  depends_on = [aws_acm_certificate.certificate.domain_name]
}
</code>```

答:
As you noted, you need to have consistent types on both sides of the ternary. Since you are using a map(list(string)) the right side, in order to create no resources, would need to be an empty map: {}.

```<code>variable "domain_names" {
  type = map(list(string))
  default = {
    "foo.com" = ["*.foo.com"]
  }
}

resource "aws_route53_record" "validation" {
  for_each   = var.validation_method == "DNS" ? var.domain_names : {}
  ...
}
</code>```

Body:
How do i use a condition inside a for_each such that , the below resource is created/triggered only when validation_method == "DNS" else ignores the creation of a resource. However in earlier terraform (11 versions) we can use

count =  var.validation_method == "DNS" ? length(var.domain_names) : 0

My var.domain_names is map(list(string)) , eg

domain_names = {
    "foo.com" = ["*.foo.com"]
  }

Please suggest me some solutions. Using terraform 0.12.20 version

resource "aws_route53_record" "validation" {
  for_each   = var.validation_method == "DNS" ? var.domain_names :
  name       = aws_acm_certificate.certificate[each.key].domain_validation_options.0.resource_record_name
  type       = aws_acm_certificate.certificate[each.key].domain_validation_options.0.resource_record_type
  zone_id    = data.aws_route53_zone.selected[each.key].zone_id
  ttl        = "300"
  records    = [aws_acm_certificate.certificate.domain_validation_options.0.resource_record_value]
  depends_on = [aws_acm_certificate.certificate.domain_name]
}

Body:
As you noted, you need to have consistent types on both sides of the ternary. Since you are using a map(list(string)) the right side, in order to create no resources, would need to be an empty map: {}.

variable "domain_names" {
  type = map(list(string))
  default = {
    "foo.com" = ["*.foo.com"]
  }
}

resource "aws_route53_record" "validation" {
  for_each   = var.validation_method == "DNS" ? var.domain_names : {}
  ...
}


问:
How to setup caching for specific headers in Firebase Cloud Functions?
I'm unsure if this is even possible. I'm making requests to an external api and on each request from my app I pass the user's query into a custom 'query' header in the Cloud Function (Typescript). ⤵

export const searchQuery = functions.https.onRequest(async (request, response) => {

    // : Reads request query data from user
    const query = request.headers.query;

...
```

<p>I attempted to setup caching so that with each query it caches the result separately but it doesn't seem to be working. ~</p>

<p><em>( caching does work without vary header set however it's only caching the first search result ) <br>
( all requests are sent as <code>GET</code> )</em></p>

<p>This is the block that sets the <code>'query'</code> header as a vary rule for caching (written in Typescript). ⤵</p>

<pre class="lang-js prettyprint-override"><code>...

    return await admin.auth().verifyIdToken(tokenId) // : Authenticates response
        .then(() => {

            // : Set cache-control
            console.log(request.headers);
            response.set('Vary', 'Accept-Encoding, query');
            response.set("Cache-Control", "public, s-maxage=600");
            response.set("Access-Control-Allow-Origin", "*");
            response.set("Access-Control-Allow-Methods", "GET");

            // : Grab API search data
            axio.get(urlAssembler).then(APIData => {
                response.status(200).send(APIData.data);
            }).catch(error => console.log(error));

        })
        .catch((err) => response.status(401).send(err));

...
</code>```

I have this setup on Cloud Functions w/ Firebase and not Cloud Functions with Firebase Hosting. I'm wondering if maybe there's a difference there but it seems there isn't.

In my firebase.json I noticed that it is setup for Cloud Functions and not for Firebase Hosting. Perhaps I need to set it up as Firebase Hosting to define cache-control for headers there?

This is my firebase.json ⤵

{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint",
      "npm --prefix \"$RESOURCE_DIR\" run build"
    ]
  }
}
```

答:
I contacted Firebase support regarding this and the individual helping me said that Firebase Hosting needs to be used in order to cache based on a header like described above.

I have not tested this yet so once I test it I will update this answer to confirm that it works.

There is an article suggested to me by the individual helping me from Firebase support for how to cache within a Cloud Function but I don't believe this makes use of a CDN.

Body:
I'm unsure if this is even possible. I'm making requests to an external api and on each request from my app I pass the user's query into a custom 'query' header in the Cloud Function (Typescript). ⤵

export const searchQuery = functions.https.onRequest(async (request, response) => {

    // : Reads request query data from user
    const query = request.headers.query;

...

I attempted to setup caching so that with each query it caches the result separately but it doesn't seem to be working. ~

( caching does work without vary header set however it's only caching the first search result )

( all requests are sent as GET )

This is the block that sets the 'query' header as a vary rule for caching (written in Typescript). ⤵

...

    return await admin.auth().verifyIdToken(tokenId) // : Authenticates response
        .then(() => {

            // : Set cache-control
            console.log(request.headers);
            response.set('Vary', 'Accept-Encoding, query');
            response.set("Cache-Control", "public, s-maxage=600");
            response.set("Access-Control-Allow-Origin", "*");
            response.set("Access-Control-Allow-Methods", "GET");

            // : Grab API search data
            axio.get(urlAssembler).then(APIData => {
                response.status(200).send(APIData.data);
            }).catch(error => console.log(error));

        })
        .catch((err) => response.status(401).send(err));

...

I have this setup on Cloud Functions w/ Firebase and not Cloud Functions with Firebase Hosting. I'm wondering if maybe there's a difference there but it seems there isn't.

In my firebase.json I noticed that it is setup for Cloud Functions and not for Firebase Hosting. Perhaps I need to set it up as Firebase Hosting to define cache-control for headers there?

This is my firebase.json ⤵

{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint",
      "npm --prefix \"$RESOURCE_DIR\" run build"
    ]
  }
}


问:
DynamoDB table query KeyConditionExpression error
How do I fix the below error and why does "operand type: M" show up? I have read aws docs and searched on stack overflow, but still couldn't solve this problem after a few hours. I want to query an item that is active and has a dateSold between the start and end date in iso format. I am interpreting the error "operand type: M" to mean that I am using the map type in my operands: dateSold, :start, and :end. However, all the operands are just strings.

The SQL command would have looked something like:
SELECT dateSold, profit FROM Items WHERE isActive = 'true' AND dateSold > start AND dateSold < end

Error:
"message":"Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: BETWEEN, operand type: M","code":"ValidationException"

Code:

```<code>AWS.config.update({ region: "us-east-2" });
    const documentClient = AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

    const options = {
        TableName: "Items",
        ProjectionExpression: "dateSold, profit",
        IndexName: "isActive-dateSold-index",
        KeyConditionExpression:
          "isActive = :isActive AND dateSold BETWEEN :start AND :end",
        ExpressionAttributeValues: {
          ":start": { S: start.toISOString() },
          ":end": { S: end.toISOString() },
          ":isActive": { S: "true" },
        },
      }

    const result = await documentClient
      .query(options)
      .promise()
</code>```

Schema:

```<code>Table: {
    AttributeDefinitions: [
    { AttributeName: "dateSold", AttributeType: "S" },
    { AttributeName: "id", AttributeType: "S" },
    { AttributeName: "isActive", AttributeType: "S" },
    ],
    TableName: "Items",
    KeySchema: [{ AttributeName: "id", KeyType: "HASH" }],
    GlobalSecondaryIndexes: [
    {
        IndexName: "isActive-dateSold-index",
        KeySchema: [
        { AttributeName: "isActive", KeyType: "HASH" },
        { AttributeName: "dateSold", KeyType: "RANGE" },
        ],
    },
    ],
},
</code>```

答:
You have:

```<code>ExpressionAttributeValues: {
          ":start": { S: start.toISOString() },
          ":end": { S: end.toISOString() },
          ":isActive": { S: "true" },
        },
</code>```

Some DynamoDB SDKs do the type encoding for you automatically. You don't need to write { S: start.toISOString() }, it may be enough to just write start.toIsoString(), without putting it in a map. I don't know if the SDK you're using is one of those. The Python one (boto3) does tis, for example.

By the way, how does S instead of "S" (a quoted string) in your code even work?

Body:
How do I fix the below error and why does "operand type: M" show up? I have read aws docs and searched on stack overflow, but still couldn't solve this problem after a few hours. I want to query an item that is active and has a dateSold between the start and end date in iso format. I am interpreting the error "operand type: M" to mean that I am using the map type in my operands: dateSold, :start, and :end. However, all the operands are just strings.

The SQL command would have looked something like:
SELECT dateSold, profit FROM Items WHERE isActive = 'true' AND dateSold > start AND dateSold < end

Error:
"message":"Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: BETWEEN, operand type: M","code":"ValidationException"

Code:

AWS.config.update({ region: "us-east-2" });
    const documentClient = AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

    const options = {
        TableName: "Items",
        ProjectionExpression: "dateSold, profit",
        IndexName: "isActive-dateSold-index",
        KeyConditionExpression:
          "isActive = :isActive AND dateSold BETWEEN :start AND :end",
        ExpressionAttributeValues: {
          ":start": { S: start.toISOString() },
          ":end": { S: end.toISOString() },
          ":isActive": { S: "true" },
        },
      }

    const result = await documentClient
      .query(options)
      .promise()

Schema:

Table: {
    AttributeDefinitions: [
    { AttributeName: "dateSold", AttributeType: "S" },
    { AttributeName: "id", AttributeType: "S" },
    { AttributeName: "isActive", AttributeType: "S" },
    ],
    TableName: "Items",
    KeySchema: [{ AttributeName: "id", KeyType: "HASH" }],
    GlobalSecondaryIndexes: [
    {
        IndexName: "isActive-dateSold-index",
        KeySchema: [
        { AttributeName: "isActive", KeyType: "HASH" },
        { AttributeName: "dateSold", KeyType: "RANGE" },
        ],
    },
    ],
},

Body:
You have:

ExpressionAttributeValues: {
          ":start": { S: start.toISOString() },
          ":end": { S: end.toISOString() },
          ":isActive": { S: "true" },
        },

Some DynamoDB SDKs do the type encoding for you automatically. You don't need to write { S: start.toISOString() }, it may be enough to just write start.toIsoString(), without putting it in a map. I don't know if the SDK you're using is one of those. The Python one (boto3) does tis, for example.

By the way, how does S instead of "S" (a quoted string) in your code even work?


问:
How do I draw ellipse in opengl with mvp
How to draw circle/ellipse and transform it with Model-View-Projection.

I draw an ellipse in a rectangle with glDrawElements(GL_TRIANGLES, ...).

I made a shader, It works, but how to transform it?

Vertex shader

#version 330 core

layout (location = 0) in vec2 position;

void main()
{
    gl_Position = vec4(position, 0.0, 1.0);
}
```

<p>fragment shader</p>

<pre class="lang-c prettyprint-override"><code>#version 400 core

uniform mat4 u_mvp;
uniform vec2 u_resolution;
out vec4 color;

float pow2(float x) { return x * x; }

void main()
{
    vec2 d = (gl_FragCoord.xy / u_resolution.xy) * 2 - vec2(1.0);
    vec4 pos = vec4(d, 0.0, 0.0);
    vec4 center = vec4(0.0);

    float r = distance(pos, center);
    r = step(0.5, r);
    color = vec4(0.7f, 0.8f, 0.1f, 1.0f - r);
}
</code>```

How to add MVP support?.

答:
There are different options, to achieve what you want. On of them is to create a function, which intersects a ray and sphere.

The following algorithm is taken from Peter Shirley's book Ray Tracing in One Weekend.

The ray is defined by an origin and a direction. The sphere is defined by a center point and a radius:

float hit_sphere(vec3 origin, vec3 direction, vec3 center, float radius)
{
    vec3 oc = origin - center;
    float a = dot(direction, direction);
    float b = 2.0 * dot(oc, direction);
    float c = dot(oc, oc) - radius*radius;
    float discriminant = b*b - 4*a*c;

    if (discriminant > 0.0)
    {
        float temp = (-b - sqrt(discriminant)) / (2*a);
        if (temp > 0.0)
            return 1.0;
        temp = (-b + sqrt(discriminant)) / (2*a);
        if (temp > 0.0)
            return 1.0;
    }
    return 0.0;
}
```

<p>Compute 2 points on the ray. Each point in normalized device space with the xy coordinates <code>xy = gl_FragCoord.xy / u_resolution.xy * 2.0 - 1.0</code> is on the same ray.
<code>vec4(xy, -1.0, 1.0)</code> is on the near plane and <code>vec4(xy, 1.0, 1.0)</code> is on the far plane. Transform this points by the <code>inverse</code> model view projection matrix (<code>u_mvp</code>) and divide the <code>xyz</code> components by the <code>w</code> component to get a ray in model space in cartesian coordinates.<br>
Size the algorithm computes 2 points on the ray, this works for perspective projection and orthographic projection.</p>

<pre class="lang-c prettyprint-override"><code>vec4 pn = inverse(u_mvp) * vec4(xy, -1.0, 1.0);
vec4 pf = inverse(u_mvp) * vec4(xy, 1.0, 1.0);

vec3 orig = pn.xyz/pn.w;
vec3 dir  = pf.xyz/pf.w - orig;
</code>```

Use the ray to intersect the sphere in model space:

vec3  center = vec3(0.0);
float radius = 1.0;
float r = hit_sphere(orig, dir, center, radius);
```

<p>I've tested the algorithm with the view matrix <code>glm::translate(glm::mat4(1), glm::vec3(0, 0, -3))</code> and the projection matrix <code>glm::perspective(glm::radians(90), aspect, 0.1, 10.0)</code></p>

<p>Fragment shader:</p>

<pre class="lang-c prettyprint-override"><code>#version 330 core

out vec4 frag_color;

uniform mat4 u_mvp;
uniform vec2 u_resolution;

float hit_sphere(vec3 origin, vec3 direction, vec3 center, float radius)
{
    vec3 oc = origin - center;
    float a = dot(direction, direction);
    float b = 2.0 * dot(oc, direction);
    float c = dot(oc, oc) - radius*radius;
    float discriminant = b*b - 4*a*c;

    if (discriminant > 0.0)
    {
        float temp = (-b - sqrt(discriminant)) / (2*a);
        if (temp > 0.0)
            return 1.0;
        temp = (-b + sqrt(discriminant)) / (2*a);
        if (temp > 0.0)
            return 1.0;
    }
    return 0.0;
}

void main()
{
    vec2 xy = gl_FragCoord.xy / u_resolution.xy * 2.0 - 1.0;

    vec4 pn = inverse(u_mvp) * vec4(xy, -1.0, 1.0);
    vec4 pf = inverse(u_mvp) * vec4(xy, 1.0, 1.0);

    vec3 orig = pn.xyz/pn.w;
    vec3 dir  = pf.xyz/pf.w - orig;

    vec3  center = vec3(0.0);
    float radius = 1.0;
    float r = hit_sphere(orig, dir, center, radius);

    vec4 backcolor = vec4(0.2, 0.3, 0.3, 1.0);
    vec4 color = vec4(0.7, 0.8, 0.1, 1.0);

    frag_color = mix(backcolor, color, r);
}
</code>```

Body:
How to draw circle/ellipse and transform it with Model-View-Projection.

I draw an ellipse in a rectangle with glDrawElements(GL_TRIANGLES, ...).

I made a shader, It works, but how to transform it?

Vertex shader

#version 330 core

layout (location = 0) in vec2 position;

void main()
{
    gl_Position = vec4(position, 0.0, 1.0);
}

fragment shader

#version 400 core

uniform mat4 u_mvp;
uniform vec2 u_resolution;
out vec4 color;

float pow2(float x) { return x * x; }

void main()
{
    vec2 d = (gl_FragCoord.xy / u_resolution.xy) * 2 - vec2(1.0);
    vec4 pos = vec4(d, 0.0, 0.0);
    vec4 center = vec4(0.0);

    float r = distance(pos, center);
    r = step(0.5, r);
    color = vec4(0.7f, 0.8f, 0.1f, 1.0f - r);
}

How to add MVP support?.

Body:
There are different options, to achieve what you want. On of them is to create a function, which intersects a ray and sphere.

The following algorithm is taken from Peter Shirley's book Ray Tracing in One Weekend.

The ray is defined by an origin and a direction. The sphere is defined by a center point and a radius:

float hit_sphere(vec3 origin, vec3 direction, vec3 center, float radius)
{
    vec3 oc = origin - center;
    float a = dot(direction, direction);
    float b = 2.0 * dot(oc, direction);
    float c = dot(oc, oc) - radius*radius;
    float discriminant = b*b - 4*a*c;

    if (discriminant > 0.0)
    {
        float temp = (-b - sqrt(discriminant)) / (2*a);
        if (temp > 0.0)
            return 1.0;
        temp = (-b + sqrt(discriminant)) / (2*a);
        if (temp > 0.0)
            return 1.0;
    }
    return 0.0;
}

Compute 2 points on the ray. Each point in normalized device space with the xy coordinates xy = gl_FragCoord.xy / u_resolution.xy * 2.0 - 1.0 is on the same ray.
vec4(xy, -1.0, 1.0) is on the near plane and vec4(xy, 1.0, 1.0) is on the far plane. Transform this points by the inverse model view projection matrix (u_mvp) and divide the xyz components by the w component to get a ray in model space in cartesian coordinates.

Size the algorithm computes 2 points on the ray, this works for perspective projection and orthographic projection.

vec4 pn = inverse(u_mvp) * vec4(xy, -1.0, 1.0);
vec4 pf = inverse(u_mvp) * vec4(xy, 1.0, 1.0);

vec3 orig = pn.xyz/pn.w;
vec3 dir  = pf.xyz/pf.w - orig;

Use the ray to intersect the sphere in model space:

vec3  center = vec3(0.0);
float radius = 1.0;
float r = hit_sphere(orig, dir, center, radius);

I've tested the algorithm with the view matrix glm::translate(glm::mat4(1), glm::vec3(0, 0, -3)) and the projection matrix glm::perspective(glm::radians(90), aspect, 0.1, 10.0)

Fragment shader:

#version 330 core

out vec4 frag_color;

uniform mat4 u_mvp;
uniform vec2 u_resolution;

float hit_sphere(vec3 origin, vec3 direction, vec3 center, float radius)
{
    vec3 oc = origin - center;
    float a = dot(direction, direction);
    float b = 2.0 * dot(oc, direction);
    float c = dot(oc, oc) - radius*radius;
    float discriminant = b*b - 4*a*c;

    if (discriminant > 0.0)
    {
        float temp = (-b - sqrt(discriminant)) / (2*a);
        if (temp > 0.0)
            return 1.0;
        temp = (-b + sqrt(discriminant)) / (2*a);
        if (temp > 0.0)
            return 1.0;
    }
    return 0.0;
}

void main()
{
    vec2 xy = gl_FragCoord.xy / u_resolution.xy * 2.0 - 1.0;

    vec4 pn = inverse(u_mvp) * vec4(xy, -1.0, 1.0);
    vec4 pf = inverse(u_mvp) * vec4(xy, 1.0, 1.0);

    vec3 orig = pn.xyz/pn.w;
    vec3 dir  = pf.xyz/pf.w - orig;

    vec3  center = vec3(0.0);
    float radius = 1.0;
    float r = hit_sphere(orig, dir, center, radius);

    vec4 backcolor = vec4(0.2, 0.3, 0.3, 1.0);
    vec4 color = vec4(0.7, 0.8, 0.1, 1.0);

    frag_color = mix(backcolor, color, r);
}


问:
Clicking on tab always open rootviewController
I am creating a tabBarApplication in which there is one tab on which camera opens.After clicking on the use tab of the imagepicker I push a new class.
Now my problem is when I again press camera tab that class gets open AND I want that camera should gets opened basically my rootviewcontroller of that tab.
Any suggestions will be appreciated.
Thanks in advance!</p>

答:
You can implement this delegate method, when the selected view controller is camera controller, you can popToRootViewController.</p>

```<code>- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
</code>```

Body:
You can implement this delegate method, when the selected view controller is camera controller, you can popToRootViewController.

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController


问:
Is there a function that finds the OR of every row in a boolean matrix in pytorch?
I have a matrix A of size n x m and all the entries are bools.  I want all my calculation to be on the GPU and I have matrix A stored as a tensor with each entry being the pytorch's bool datatype.  I want an output of a single vector, b, to be a 1 x m tensor that stores the OR of all rows in A.

What I want:

A matrix =

[a1,1, a1,2, , a1,3, ... , a1,m]

[a2,1, a2,2, , a2,3, ... , a2,m]

...

[an,1, an,2, , an,3, ... , an,m]

b = [b1, b2, , b3, , ..., bm]

s.t. bi = a1,i | a2,i | a3,i | ... | an,i
where | is the OR operator in Pytorch

essentially I want a function that applies row or column wise boolean operation. I know the | .__OR__ can be used and Pytorch's OR function takes two boolean tensor as inputs and I would need to loop over all rows to get my desired b vector.

Since OR is commutative (a|(b|c) = (a|b)|c), I would think pytorch would have some nice function that speeds it up by doing the | operations in parallel or in some divide and conquer method, instead of doing this with a loop. Any ideas or references to speed up the process of applying communicative row/column wise boolean operation with pytorch is welcomed.  Best if all operations are done on the GPU.

答:
See torch.any and torch.all.

Both take a dim argument and hence you can compute or/and of rows.


问:
I want to create a new column with the value that a string has matched on from a list
```<code>To_Find_lst = ["Q1","Q2","Q3","Q4","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
</code>```

DF:

```<code>   A                 B
Q1_MONDAY            55
Q3_LA                87
WEDNESDAY_FRIDAY     67
</code>```

I want to create a new column that will identify values from the list in col A and create a column C with the values it identified.

```<code>   A                 B         C
Q1_MONDAY            55.     Q1, MONDAY
Q3_LA                87.     Q3
WEDNESDAY_FRIDAY     67.     WEDNESDAY, FRIDAY
</code>```

答:
```<code>df['C'] = df.A.transform(lambda x: ','.join([i for i in x.split('_') if i in To_Find_lst]))
</code>```

Output

```<code>                  A   B                 C
0         Q1_MONDAY  55         Q1,MONDAY
1             Q3_LA  87                Q3
2  WEDNESDAY_FRIDAY  67  WEDNESDAY,FRIDAY
</code>```

Body:
To_Find_lst = ["Q1","Q2","Q3","Q4","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]

DF:

   A                 B
Q1_MONDAY            55
Q3_LA                87
WEDNESDAY_FRIDAY     67

I want to create a new column that will identify values from the list in col A and create a column C with the values it identified.

   A                 B         C
Q1_MONDAY            55.     Q1, MONDAY
Q3_LA                87.     Q3
WEDNESDAY_FRIDAY     67.     WEDNESDAY, FRIDAY

Body:
df['C'] = df.A.transform(lambda x: ','.join([i for i in x.split('_') if i in To_Find_lst]))

Output

                  A   B                 C
0         Q1_MONDAY  55         Q1,MONDAY
1             Q3_LA  87                Q3
2  WEDNESDAY_FRIDAY  67  WEDNESDAY,FRIDAY


问:
How to set key/value default state for TypeScript React app
I am having to convert a React app to Typescript and I can't figure out to property set the initial state of hash object.

original js

```<code>export default class Wizard extends PureComponent {
    constructor(props) {
        super(props);

        this.state = this.initialState();
    }

    /** Setup Steps */
    initialState = () => {
        const state = {
            activeStep: 0,
            hashKeys: {},
        };

        // Set initial classes
        // Get hash only in client side
        const hash = typeof window === 'object' ? this.getHash() : '';
        const children = React.Children.toArray(this.getSteps());
        children.forEach((child, i) => {
            // Create hashKey map
            state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`;
            state.hashKeys[state.hashKeys[i]] = i;
        });

        ...

        return state;
    }
...
</code>```

My Failed Attempt

```<code>export interface TState {
  activeStep?: number
  hashKeys: {
    [key: number]: string
  }
}

export default class StepWizard extends PureComponent<{},TState> {
   constructor(props: IStepWizardProps) {
       super(props)
       this.state = this.initialState()
   }

   initialState = () => {
    const state = {
      activeStep: 0,
      hashKeys: {},  /* <---- This seems to be the problem */
    }

    // Set initial classes
    // Get hash only in client side
    const hash = typeof window === "object" ? this.getHash() : ""

    const children = React.Children.toArray(this.getSteps())
    children.forEach((child, i) => {
      // Create hashKey map
      // the following give a TS error
      // ERROR: (property) hashKeys: {}
      //           Element implicitly has an 'any' type because expression of type 'number'
      //           can't be used to index type '{}'.
      //        No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)
      state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`
      state.hashKeys[state.hashKeys[i]] = i
    })

   ...

</code>```

I get for state.hasKeys[i] (property) hashKeys: {}
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'.
  No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)

答:
Option 1: Type Union

export interface TState {
  activeStep?: number;
  hashKeys: {
    [key: number]: string
  } | {};
}
```

<p>This syntax indicates that <code>hashKeys</code> could take the shape of either <code>{[key: number]: string}</code> or <code>{}</code>.</p>

<p>If you wanted to improve the readability of that union, you could do this:</p>

<pre class="lang-js prettyprint-override"><code>type HashMap = {
  [key: number]: string;
}

export interface TState {
  activeStep?: number;
  hashKeys: HashMap | {};
}
</code>```

Option 2: Partial (pssst probably not optimal - see option 3)

Partial constructs a type with all properties set to optional, which means that {} fits the definition by having both non-existent key and value properties.

type HashMap = {
  [key: number]: string;
}

export interface TState {
  activeStep?: number;
  hashKeys: Partial<HashMap>
}
```

<p><br></p>

<h1>Option 3: Type assertion</h1>

<p>As pointed out in this answer, this approach does a better job of striking "a balance between correctness and productivity."</p>

<pre class="lang-js prettyprint-override"><code>type HashMap = {
  [key: number]: string;
}

export interface TState {
  activeStep?: number;
  hashKeys: HashMap;
}

//

const state = {
  activeStep: 0,
  hashKeys: {} as HashMap,
};
</code>```

Body:
I am having to convert a React app to Typescript and I can't figure out to property set the initial state of hash object.

original js

export default class Wizard extends PureComponent {
    constructor(props) {
        super(props);

        this.state = this.initialState();
    }

    /** Setup Steps */
    initialState = () => {
        const state = {
            activeStep: 0,
            hashKeys: {},
        };

        // Set initial classes
        // Get hash only in client side
        const hash = typeof window === 'object' ? this.getHash() : '';
        const children = React.Children.toArray(this.getSteps());
        children.forEach((child, i) => {
            // Create hashKey map
            state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`;
            state.hashKeys[state.hashKeys[i]] = i;
        });

        ...

        return state;
    }
...

My Failed Attempt

export interface TState {
  activeStep?: number
  hashKeys: {
    [key: number]: string
  }
}

export default class StepWizard extends PureComponent<{},TState> {
   constructor(props: IStepWizardProps) {
       super(props)
       this.state = this.initialState()
   }

   initialState = () => {
    const state = {
      activeStep: 0,
      hashKeys: {},  /* <---- This seems to be the problem */
    }

    // Set initial classes
    // Get hash only in client side
    const hash = typeof window === "object" ? this.getHash() : ""

    const children = React.Children.toArray(this.getSteps())
    children.forEach((child, i) => {
      // Create hashKey map
      // the following give a TS error
      // ERROR: (property) hashKeys: {}
      //           Element implicitly has an 'any' type because expression of type 'number'
      //           can't be used to index type '{}'.
      //        No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)
      state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`
      state.hashKeys[state.hashKeys[i]] = i
    })

   ...

I get for state.hasKeys[i] (property) hashKeys: {}
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'.
  No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)

Body:
Option 1: Type Union

export interface TState {
  activeStep?: number;
  hashKeys: {
    [key: number]: string
  } | {};
}

This syntax indicates that hashKeys could take the shape of either {[key: number]: string} or {}.

If you wanted to improve the readability of that union, you could do this:

type HashMap = {
  [key: number]: string;
}

export interface TState {
  activeStep?: number;
  hashKeys: HashMap | {};
}

Option 2: Partial (pssst probably not optimal - see option 3)

Partial constructs a type with all properties set to optional, which means that {} fits the definition by having both non-existent key and value properties.

type HashMap = {
  [key: number]: string;
}

export interface TState {
  activeStep?: number;
  hashKeys: Partial<HashMap>
}

Option 3: Type assertion

As pointed out in this answer, this approach does a better job of striking "a balance between correctness and productivity."

type HashMap = {
  [key: number]: string;
}

export interface TState {
  activeStep?: number;
  hashKeys: HashMap;
}

//

const state = {
  activeStep: 0,
  hashKeys: {} as HashMap,
};


问:
C++ Template specialization for constant variables
I am currently trying to have a compile-time constant variable that is template specialized for several types. Currently, I am using constant expressions such as the following generalized example:

template<typename T>
constexpr T GENERAL_CONSTANT = T(0.01);

template<> constexpr float GENERAL_CONSTANT<float> = float(0.02);

template<> constexpr double GENERAL_CONSTANT<double> = double(0.03);
```

<p>This code however only seems to work on some compilers/linkers. It will compile and work correctly for Clang 9.0.0 for Windows 10, Clang 6.0.0 for Windows 10, Clang 6.0.0 for Ubuntu 18.04, and GCC for Ubuntu 18.04. But has given the similar multiple redefinition errors in several other configurations such as Clang 10.0.0 on Windows 10 or Clang 10.0.0 on Unix, as well as a few others. The errors will often look similar to this:</p>

```/usr/bin/ld: <some path to a.cpp> multiple definition of `GENERAL_CONSTANT<double>'; <some path to a.cpp>: first defined here
/usr/bin/ld: <some path to a.cpp> multiple definition of `GENERAL_CONSTANT<float>'; <some path to a.cpp>: first defined here
```

Where 'a.cpp' is the file that uses the constant, but does not define them. So given that this error is happening inconsistently depending on compiler and machine, I was curious if this is a non-standard approach to this problem, and if that is true, what approach should I take instead?

答:
This code does compile as is. See This Demo.
Specialized template variables will still compile into the binary, even when marked constexpr. Since you are using the header and thus these variables in multiple translation units, you are getting a linker error.
You can tell this by the fact that ld is giving you the error.

Marking the specializations inline will prevent this from happening and fix the issue:

template<typename T>
constexpr T GENERAL_CONSTANT = T(0.01);

template<> inline constexpr float GENERAL_CONSTANT<float> = float(0.02);

template<> inline constexpr double GENERAL_CONSTANT<double> = double(0.03);
```

This is a compiler bug, because constexpr implies inline for variables and functions but apparently, certain compiler versions mess this up for template specializatons.

Body:
I am currently trying to have a compile-time constant variable that is template specialized for several types. Currently, I am using constant expressions such as the following generalized example:

template<typename T>
constexpr T GENERAL_CONSTANT = T(0.01);

template<> constexpr float GENERAL_CONSTANT<float> = float(0.02);

template<> constexpr double GENERAL_CONSTANT<double> = double(0.03);

This code however only seems to work on some compilers/linkers. It will compile and work correctly for Clang 9.0.0 for Windows 10, Clang 6.0.0 for Windows 10, Clang 6.0.0 for Ubuntu 18.04, and GCC for Ubuntu 18.04. But has given the similar multiple redefinition errors in several other configurations such as Clang 10.0.0 on Windows 10 or Clang 10.0.0 on Unix, as well as a few others. The errors will often look similar to this:

/usr/bin/ld: <some path to a.cpp> multiple definition of `GENERAL_CONSTANT<double>'; <some path to a.cpp>: first defined here
/usr/bin/ld: <some path to a.cpp> multiple definition of `GENERAL_CONSTANT<float>'; <some path to a.cpp>: first defined here

Where 'a.cpp' is the file that uses the constant, but does not define them. So given that this error is happening inconsistently depending on compiler and machine, I was curious if this is a non-standard approach to this problem, and if that is true, what approach should I take instead?

Body:
This code does compile as is. See This Demo.
Specialized template variables will still compile into the binary, even when marked constexpr. Since you are using the header and thus these variables in multiple translation units, you are getting a linker error.
You can tell this by the fact that ld is giving you the error.

Marking the specializations inline will prevent this from happening and fix the issue:

template<typename T>
constexpr T GENERAL_CONSTANT = T(0.01);

template<> inline constexpr float GENERAL_CONSTANT<float> = float(0.02);

template<> inline constexpr double GENERAL_CONSTANT<double> = double(0.03);

This is a compiler bug, because constexpr implies inline for variables and functions but apparently, certain compiler versions mess this up for template specializatons.


问:
Fetch id of clicked element using .live()
As per suggestions i changed my code to below

```<code><dl id="accRegion">
<#list command.instruments as instrType>
<dt ><a class="red">${instrType}</a></dt>
<dd >
    <#list command.logDates as logDate>
        <div id="${instrType}"><a class="orange">${logDate}</a></dt>
    </#list>
</dd>
</#list>
</code>```

but it still gets me the id of first element instead of the clicked one. Also, this dl is an accordion.

Here is the generated html fragment

```<code><dl id="accRegion">
<dt ><a class="red">Stocks</a></dt>
<dd >
        <div id="Stocks"><a class="orange">2011-05-31</a></dt>
</dd>
<dt ><a class="red">Futures</a></dt>

<dd >
        <div id="Futures"><a class="orange">2011-05-31</a></dt>
</dd>
</code>```

Trying below method

```<code>    $("#accRegion div").live('click',function(){
    alert($(this).attr("id"));
});
</code>```

答:
               you are using same id multiple times on a page ;whereas its is necessary that id must be unique on a pages; that's your main problem. and there is also alternative method of attr in jQuery v1.6.Yu can use jQuery.prop()

```<code>$("#accRegion dd dt").live('click',function(){
    alert($(this).prop("id"));
});
</code>```

DEMO

Body:
As per suggestions i changed my code to below

<#list command.instruments as instrType>

${instrType}

    <#list command.logDates as logDate>

${logDate}

    </#list>

</#list>

but it still gets me the id of first element instead of the clicked one. Also, this dl is an accordion.

Here is the generated html fragment

Stocks

2011-05-31

Futures

2011-05-31

Trying below method

    $("#accRegion div").live('click',function(){
    alert($(this).attr("id"));
});

Body:
               you are using same id multiple times on a page ;whereas its is necessary that id must be unique on a pages; that's your main problem. and there is also alternative method of attr in jQuery v1.6.Yu can use jQuery.prop()

$("#accRegion dd dt").live('click',function(){
    alert($(this).prop("id"));
});

DEMO


问:
Conversion from signed int to signed char?
I'm following an example from Stroustrups C_++ 4th Ed. Page 143, where there is Errata.  -160, should be -140.

Specifically the conversion of a signed int to a signed char.

```<code>#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    signed char sc = -140;
    cout << "signed int = " <<
    int((signed int) (0b11111111111111111111111101110100))
          << endl; // -140, 4 bytes
    cout << "signed int & 0xFF = " << int((signed int) -140 & 0xFF)
          << endl; // 116, narrow 2 bytes
    unsigned char uc = sc; // 256 - 140 = 116
    return 0;
}
</code>```

I understand how the conversion is a narrowing of 4 bytes, to 2 bytes which result in -140 being converted to 116.  I am confused on the comment Stroustrup adds for the line unsigned char uc = sc where it is // 256 - 140 = 116.  I see it results in the correct answer 116, but am unsure how that conversion is done.  I'm aware that an unsigned char max limit completely full of 1's is 255 or 2^8 - 1.  Does anyone know why this math in the comment works?

UPDATE:
The solution is -140 mod 256 = 116.

Thanks

答:
When converting a value to an unsigned type, the value is taken modulo N,

where N = 2sizeof(T)*CHAR_BIT.

In simple terms, it means that N*i is added to the value to put it in the  representable range, where i is an integer (possibly negative).

You can always determine a single specific value of i that puts the value into the representable range. In your case, i = 1, so, 256 * 1 is added to the value.

Body:
I'm following an example from Stroustrups C_++ 4th Ed. Page 143, where there is Errata.  -160, should be -140.

Specifically the conversion of a signed int to a signed char.

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    signed char sc = -140;
    cout << "signed int = " <<
    int((signed int) (0b11111111111111111111111101110100))
          << endl; // -140, 4 bytes
    cout << "signed int & 0xFF = " << int((signed int) -140 & 0xFF)
          << endl; // 116, narrow 2 bytes
    unsigned char uc = sc; // 256 - 140 = 116
    return 0;
}

I understand how the conversion is a narrowing of 4 bytes, to 2 bytes which result in -140 being converted to 116.  I am confused on the comment Stroustrup adds for the line unsigned char uc = sc where it is // 256 - 140 = 116.  I see it results in the correct answer 116, but am unsure how that conversion is done.  I'm aware that an unsigned char max limit completely full of 1's is 255 or 2^8 - 1.  Does anyone know why this math in the comment works?

UPDATE:
The solution is -140 mod 256 = 116.

Thanks


问:
How to capture selected cells values like excel in html table
In the below table:

How can the user select "Jill" and "Eve"?

How to style the cell that is similar to excel when the user selects or hovers the cell?

How to capture the user-selected values and console log it?

<!DOCTYPE html>

    Firstname
    Lastname
    Age

    Jill
    Smith
    50

    Eve
    Jackson
    94

    John
    Doe
    80

```

答:
They are plenty of option available below are some of it you can use.

Most recommended :

https://jspreadsheets.com/handsontable/

Bootstrap form input css like MS-Excel

https://codepen.io/oliviale/pen/rPjgmB

Simpler one is second one. If you want more fancy and beautiful then use first. Third one is full fledge feature like ms-excel